blob: d81151dc1aa24b89c09c6f4d804fe6320f2e125b [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
Eli Friedmanf6172ae2012-06-25 21:21:08 +0000290 // Note that we intentionally use std::map here so that references to
291 // values are stable.
292 typedef std::map<const Expr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000293 typedef MapTy::const_iterator temp_iterator;
294 /// Temporaries - Temporary lvalues materialized within this stack frame.
295 MapTy Temporaries;
296
Richard Smith08d6e032011-12-16 19:06:07 +0000297 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
298 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000299 const APValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000300 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000301 };
302
Richard Smithdd1f29b2011-12-12 09:28:41 +0000303 /// A partial diagnostic which we might know in advance that we are not going
304 /// to emit.
305 class OptionalDiagnostic {
306 PartialDiagnostic *Diag;
307
308 public:
309 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
310
311 template<typename T>
312 OptionalDiagnostic &operator<<(const T &v) {
313 if (Diag)
314 *Diag << v;
315 return *this;
316 }
Richard Smith789f9b62012-01-31 04:08:20 +0000317
318 OptionalDiagnostic &operator<<(const APSInt &I) {
319 if (Diag) {
320 llvm::SmallVector<char, 32> Buffer;
321 I.toString(Buffer);
322 *Diag << StringRef(Buffer.data(), Buffer.size());
323 }
324 return *this;
325 }
326
327 OptionalDiagnostic &operator<<(const APFloat &F) {
328 if (Diag) {
329 llvm::SmallVector<char, 32> Buffer;
330 F.toString(Buffer);
331 *Diag << StringRef(Buffer.data(), Buffer.size());
332 }
333 return *this;
334 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000335 };
336
Richard Smith83587db2012-02-15 02:18:13 +0000337 /// EvalInfo - This is a private struct used by the evaluator to capture
338 /// information about a subexpression as it is folded. It retains information
339 /// about the AST context, but also maintains information about the folded
340 /// expression.
341 ///
342 /// If an expression could be evaluated, it is still possible it is not a C
343 /// "integer constant expression" or constant expression. If not, this struct
344 /// captures information about how and why not.
345 ///
346 /// One bit of information passed *into* the request for constant folding
347 /// indicates whether the subexpression is "evaluated" or not according to C
348 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
349 /// evaluate the expression regardless of what the RHS is, but C only allows
350 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000351 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000352 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000353
Richard Smithbd552ef2011-10-31 05:52:43 +0000354 /// EvalStatus - Contains information about the evaluation.
355 Expr::EvalStatus &EvalStatus;
356
357 /// CurrentCall - The top of the constexpr call stack.
358 CallStackFrame *CurrentCall;
359
Richard Smithbd552ef2011-10-31 05:52:43 +0000360 /// CallStackDepth - The number of calls in the call stack right now.
361 unsigned CallStackDepth;
362
Richard Smith83587db2012-02-15 02:18:13 +0000363 /// NextCallIndex - The next call index to assign.
364 unsigned NextCallIndex;
365
Eli Friedmanf6172ae2012-06-25 21:21:08 +0000366 // Note that we intentionally use std::map here so that references
367 // to values are stable.
368 typedef std::map<const OpaqueValueExpr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000369
370 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000371 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000372 CallStackFrame BottomFrame;
373
Richard Smith180f4792011-11-10 06:34:14 +0000374 /// EvaluatingDecl - This is the declaration whose initializer is being
375 /// evaluated, if any.
376 const VarDecl *EvaluatingDecl;
377
378 /// EvaluatingDeclValue - This is the value being constructed for the
379 /// declaration whose initializer is being evaluated, if any.
380 APValue *EvaluatingDeclValue;
381
Richard Smithc1c5f272011-12-13 06:39:58 +0000382 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
383 /// notes attached to it will also be stored, otherwise they will not be.
384 bool HasActiveDiagnostic;
385
Richard Smith745f5142012-01-27 01:14:48 +0000386 /// CheckingPotentialConstantExpression - Are we checking whether the
387 /// expression is a potential constant expression? If so, some diagnostics
388 /// are suppressed.
389 bool CheckingPotentialConstantExpression;
390
Richard Smithbd552ef2011-10-31 05:52:43 +0000391 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000392 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000393 CallStackDepth(0), NextCallIndex(1),
394 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000395 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Argyrios Kyrtzidis649dfbc2012-03-15 18:07:13 +0000396 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000397
Richard Smith180f4792011-11-10 06:34:14 +0000398 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
399 EvaluatingDecl = VD;
400 EvaluatingDeclValue = &Value;
401 }
402
David Blaikie4e4d0842012-03-11 07:00:24 +0000403 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000404
Richard Smithc1c5f272011-12-13 06:39:58 +0000405 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000406 // Don't perform any constexpr calls (other than the call we're checking)
407 // when checking a potential constant expression.
408 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
409 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000410 if (NextCallIndex == 0) {
411 // NextCallIndex has wrapped around.
412 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
413 return false;
414 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000415 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
416 return true;
417 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
418 << getLangOpts().ConstexprCallDepth;
419 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000420 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000421
Richard Smith83587db2012-02-15 02:18:13 +0000422 CallStackFrame *getCallFrame(unsigned CallIndex) {
423 assert(CallIndex && "no call index in getCallFrame");
424 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
425 // be null in this loop.
426 CallStackFrame *Frame = CurrentCall;
427 while (Frame->Index > CallIndex)
428 Frame = Frame->Caller;
429 return (Frame->Index == CallIndex) ? Frame : 0;
430 }
431
Richard Smithc1c5f272011-12-13 06:39:58 +0000432 private:
433 /// Add a diagnostic to the diagnostics list.
434 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
435 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
436 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
437 return EvalStatus.Diag->back().second;
438 }
439
Richard Smith08d6e032011-12-16 19:06:07 +0000440 /// Add notes containing a call stack to the current point of evaluation.
441 void addCallStack(unsigned Limit);
442
Richard Smithc1c5f272011-12-13 06:39:58 +0000443 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000444 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000445 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
446 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000447 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000448 // If we have a prior diagnostic, it will be noting that the expression
449 // isn't a constant expression. This diagnostic is more important.
450 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000451 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000452 unsigned CallStackNotes = CallStackDepth - 1;
453 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
454 if (Limit)
455 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000456 if (CheckingPotentialConstantExpression)
457 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000458
Richard Smithc1c5f272011-12-13 06:39:58 +0000459 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000460 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000461 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
462 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000463 if (!CheckingPotentialConstantExpression)
464 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000465 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000466 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000467 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000468 return OptionalDiagnostic();
469 }
470
Richard Smith5cfc7d82012-03-15 04:53:45 +0000471 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
472 = diag::note_invalid_subexpr_in_const_expr,
473 unsigned ExtraNotes = 0) {
474 if (EvalStatus.Diag)
475 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
476 HasActiveDiagnostic = false;
477 return OptionalDiagnostic();
478 }
479
Richard Smithdd1f29b2011-12-12 09:28:41 +0000480 /// Diagnose that the evaluation does not produce a C++11 core constant
481 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000482 template<typename LocArg>
483 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000484 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000485 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000486 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000487 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
488 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000489 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000490 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000491 return Diag(Loc, DiagId, ExtraNotes);
492 }
493
494 /// Add a note to a prior diagnostic.
495 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
496 if (!HasActiveDiagnostic)
497 return OptionalDiagnostic();
498 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000499 }
Richard Smith099e7f62011-12-19 06:19:21 +0000500
501 /// Add a stack of notes to a prior diagnostic.
502 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
503 if (HasActiveDiagnostic) {
504 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
505 Diags.begin(), Diags.end());
506 }
507 }
Richard Smith745f5142012-01-27 01:14:48 +0000508
509 /// Should we continue evaluation as much as possible after encountering a
510 /// construct which can't be folded?
511 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000512 return CheckingPotentialConstantExpression &&
513 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000514 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000515 };
Richard Smithf15fda02012-02-02 01:16:57 +0000516
517 /// Object used to treat all foldable expressions as constant expressions.
518 struct FoldConstant {
519 bool Enabled;
520
521 explicit FoldConstant(EvalInfo &Info)
522 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
523 !Info.EvalStatus.HasSideEffects) {
524 }
525 // Treat the value we've computed since this object was created as constant.
526 void Fold(EvalInfo &Info) {
527 if (Enabled && !Info.EvalStatus.Diag->empty() &&
528 !Info.EvalStatus.HasSideEffects)
529 Info.EvalStatus.Diag->clear();
530 }
531 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000532
533 /// RAII object used to suppress diagnostics and side-effects from a
534 /// speculative evaluation.
535 class SpeculativeEvaluationRAII {
536 EvalInfo &Info;
537 Expr::EvalStatus Old;
538
539 public:
540 SpeculativeEvaluationRAII(EvalInfo &Info,
541 llvm::SmallVectorImpl<PartialDiagnosticAt>
542 *NewDiag = 0)
543 : Info(Info), Old(Info.EvalStatus) {
544 Info.EvalStatus.Diag = NewDiag;
545 }
546 ~SpeculativeEvaluationRAII() {
547 Info.EvalStatus = Old;
548 }
549 };
Richard Smith08d6e032011-12-16 19:06:07 +0000550}
Richard Smithbd552ef2011-10-31 05:52:43 +0000551
Richard Smithb4e85ed2012-01-06 16:39:00 +0000552bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
553 CheckSubobjectKind CSK) {
554 if (Invalid)
555 return false;
556 if (isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000557 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000558 << CSK;
559 setInvalid();
560 return false;
561 }
562 return true;
563}
564
565void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
566 const Expr *E, uint64_t N) {
567 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000568 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000569 << static_cast<int>(N) << /*array*/ 0
570 << static_cast<unsigned>(MostDerivedArraySize);
571 else
Richard Smith5cfc7d82012-03-15 04:53:45 +0000572 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000573 << static_cast<int>(N) << /*non-array*/ 1;
574 setInvalid();
575}
576
Richard Smith08d6e032011-12-16 19:06:07 +0000577CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
578 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000579 const APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000580 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000581 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000582 Info.CurrentCall = this;
583 ++Info.CallStackDepth;
584}
585
586CallStackFrame::~CallStackFrame() {
587 assert(Info.CurrentCall == this && "calls retired out of order");
588 --Info.CallStackDepth;
589 Info.CurrentCall = Caller;
590}
591
592/// Produce a string describing the given constexpr call.
593static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
594 unsigned ArgIndex = 0;
595 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000596 !isa<CXXConstructorDecl>(Frame->Callee) &&
597 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000598
599 if (!IsMemberCall)
600 Out << *Frame->Callee << '(';
601
602 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
603 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000604 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000605 Out << ", ";
606
607 const ParmVarDecl *Param = *I;
Richard Smith1aa0be82012-03-03 22:46:17 +0000608 const APValue &Arg = Frame->Arguments[ArgIndex];
609 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smith08d6e032011-12-16 19:06:07 +0000610
611 if (ArgIndex == 0 && IsMemberCall)
612 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000613 }
614
Richard Smith08d6e032011-12-16 19:06:07 +0000615 Out << ')';
616}
617
618void EvalInfo::addCallStack(unsigned Limit) {
619 // Determine which calls to skip, if any.
620 unsigned ActiveCalls = CallStackDepth - 1;
621 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
622 if (Limit && Limit < ActiveCalls) {
623 SkipStart = Limit / 2 + Limit % 2;
624 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000625 }
626
Richard Smith08d6e032011-12-16 19:06:07 +0000627 // Walk the call stack and add the diagnostics.
628 unsigned CallIdx = 0;
629 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
630 Frame = Frame->Caller, ++CallIdx) {
631 // Skip this call?
632 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
633 if (CallIdx == SkipStart) {
634 // Note that we're skipping calls.
635 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
636 << unsigned(ActiveCalls - Limit);
637 }
638 continue;
639 }
640
641 llvm::SmallVector<char, 128> Buffer;
642 llvm::raw_svector_ostream Out(Buffer);
643 describeCall(Frame, Out);
644 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
645 }
646}
647
648namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000649 struct ComplexValue {
650 private:
651 bool IsInt;
652
653 public:
654 APSInt IntReal, IntImag;
655 APFloat FloatReal, FloatImag;
656
657 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
658
659 void makeComplexFloat() { IsInt = false; }
660 bool isComplexFloat() const { return !IsInt; }
661 APFloat &getComplexFloatReal() { return FloatReal; }
662 APFloat &getComplexFloatImag() { return FloatImag; }
663
664 void makeComplexInt() { IsInt = true; }
665 bool isComplexInt() const { return IsInt; }
666 APSInt &getComplexIntReal() { return IntReal; }
667 APSInt &getComplexIntImag() { return IntImag; }
668
Richard Smith1aa0be82012-03-03 22:46:17 +0000669 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000670 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000671 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000672 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000673 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000674 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000675 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000676 assert(v.isComplexFloat() || v.isComplexInt());
677 if (v.isComplexFloat()) {
678 makeComplexFloat();
679 FloatReal = v.getComplexFloatReal();
680 FloatImag = v.getComplexFloatImag();
681 } else {
682 makeComplexInt();
683 IntReal = v.getComplexIntReal();
684 IntImag = v.getComplexIntImag();
685 }
686 }
John McCallf4cf1a12010-05-07 17:22:02 +0000687 };
John McCallefdb83e2010-05-07 21:00:08 +0000688
689 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000690 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000691 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000692 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000693 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000694
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000695 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000696 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000697 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000698 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000699 SubobjectDesignator &getLValueDesignator() { return Designator; }
700 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000701
Richard Smith1aa0be82012-03-03 22:46:17 +0000702 void moveInto(APValue &V) const {
703 if (Designator.Invalid)
704 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
705 else
706 V = APValue(Base, Offset, Designator.Entries,
707 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000708 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000709 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000710 assert(V.isLValue());
711 Base = V.getLValueBase();
712 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000713 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000714 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000715 }
716
Richard Smith83587db2012-02-15 02:18:13 +0000717 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000718 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000719 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000720 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000721 Designator = SubobjectDesignator(getType(B));
722 }
723
724 // Check that this LValue is not based on a null pointer. If it is, produce
725 // a diagnostic and mark the designator as invalid.
726 bool checkNullPointer(EvalInfo &Info, const Expr *E,
727 CheckSubobjectKind CSK) {
728 if (Designator.Invalid)
729 return false;
730 if (!Base) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000731 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000732 << CSK;
733 Designator.setInvalid();
734 return false;
735 }
736 return true;
737 }
738
739 // Check this LValue refers to an object. If not, set the designator to be
740 // invalid and emit a diagnostic.
741 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000742 // Outside C++11, do not build a designator referring to a subobject of
743 // any object: we won't use such a designator for anything.
744 if (!Info.getLangOpts().CPlusPlus0x)
745 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000746 return checkNullPointer(Info, E, CSK) &&
747 Designator.checkSubobject(Info, E, CSK);
748 }
749
750 void addDecl(EvalInfo &Info, const Expr *E,
751 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000752 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
753 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000754 }
755 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000756 if (checkSubobject(Info, E, CSK_ArrayToPointer))
757 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000758 }
Richard Smith86024012012-02-18 22:04:06 +0000759 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000760 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
761 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000762 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000763 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000764 if (checkNullPointer(Info, E, CSK_ArrayIndex))
765 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000766 }
John McCallefdb83e2010-05-07 21:00:08 +0000767 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000768
769 struct MemberPtr {
770 MemberPtr() {}
771 explicit MemberPtr(const ValueDecl *Decl) :
772 DeclAndIsDerivedMember(Decl, false), Path() {}
773
774 /// The member or (direct or indirect) field referred to by this member
775 /// pointer, or 0 if this is a null member pointer.
776 const ValueDecl *getDecl() const {
777 return DeclAndIsDerivedMember.getPointer();
778 }
779 /// Is this actually a member of some type derived from the relevant class?
780 bool isDerivedMember() const {
781 return DeclAndIsDerivedMember.getInt();
782 }
783 /// Get the class which the declaration actually lives in.
784 const CXXRecordDecl *getContainingRecord() const {
785 return cast<CXXRecordDecl>(
786 DeclAndIsDerivedMember.getPointer()->getDeclContext());
787 }
788
Richard Smith1aa0be82012-03-03 22:46:17 +0000789 void moveInto(APValue &V) const {
790 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000791 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000792 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000793 assert(V.isMemberPointer());
794 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
795 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
796 Path.clear();
797 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
798 Path.insert(Path.end(), P.begin(), P.end());
799 }
800
801 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
802 /// whether the member is a member of some class derived from the class type
803 /// of the member pointer.
804 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
805 /// Path - The path of base/derived classes from the member declaration's
806 /// class (exclusive) to the class type of the member pointer (inclusive).
807 SmallVector<const CXXRecordDecl*, 4> Path;
808
809 /// Perform a cast towards the class of the Decl (either up or down the
810 /// hierarchy).
811 bool castBack(const CXXRecordDecl *Class) {
812 assert(!Path.empty());
813 const CXXRecordDecl *Expected;
814 if (Path.size() >= 2)
815 Expected = Path[Path.size() - 2];
816 else
817 Expected = getContainingRecord();
818 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
819 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
820 // if B does not contain the original member and is not a base or
821 // derived class of the class containing the original member, the result
822 // of the cast is undefined.
823 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
824 // (D::*). We consider that to be a language defect.
825 return false;
826 }
827 Path.pop_back();
828 return true;
829 }
830 /// Perform a base-to-derived member pointer cast.
831 bool castToDerived(const CXXRecordDecl *Derived) {
832 if (!getDecl())
833 return true;
834 if (!isDerivedMember()) {
835 Path.push_back(Derived);
836 return true;
837 }
838 if (!castBack(Derived))
839 return false;
840 if (Path.empty())
841 DeclAndIsDerivedMember.setInt(false);
842 return true;
843 }
844 /// Perform a derived-to-base member pointer cast.
845 bool castToBase(const CXXRecordDecl *Base) {
846 if (!getDecl())
847 return true;
848 if (Path.empty())
849 DeclAndIsDerivedMember.setInt(true);
850 if (isDerivedMember()) {
851 Path.push_back(Base);
852 return true;
853 }
854 return castBack(Base);
855 }
856 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000857
Richard Smithb02e4622012-02-01 01:42:44 +0000858 /// Compare two member pointers, which are assumed to be of the same type.
859 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
860 if (!LHS.getDecl() || !RHS.getDecl())
861 return !LHS.getDecl() && !RHS.getDecl();
862 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
863 return false;
864 return LHS.Path == RHS.Path;
865 }
866
Richard Smithc1c5f272011-12-13 06:39:58 +0000867 /// Kinds of constant expression checking, for diagnostics.
868 enum CheckConstantExpressionKind {
869 CCEK_Constant, ///< A normal constant.
870 CCEK_ReturnValue, ///< A constexpr function return value.
871 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
872 };
John McCallf4cf1a12010-05-07 17:22:02 +0000873}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000874
Richard Smith1aa0be82012-03-03 22:46:17 +0000875static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000876static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
877 const LValue &This, const Expr *E,
878 CheckConstantExpressionKind CCEK = CCEK_Constant,
879 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000880static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
881static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000882static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
883 EvalInfo &Info);
884static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000885static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000886static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000887 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000888static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000889static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000890
891//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000892// Misc utilities
893//===----------------------------------------------------------------------===//
894
Richard Smith180f4792011-11-10 06:34:14 +0000895/// Should this call expression be treated as a string literal?
896static bool IsStringLiteralCall(const CallExpr *E) {
897 unsigned Builtin = E->isBuiltinCall();
898 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
899 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
900}
901
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000902static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000903 // C++11 [expr.const]p3 An address constant expression is a prvalue core
904 // constant expression of pointer type that evaluates to...
905
906 // ... a null pointer value, or a prvalue core constant expression of type
907 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000908 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000909
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000910 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
911 // ... the address of an object with static storage duration,
912 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
913 return VD->hasGlobalStorage();
914 // ... the address of a function,
915 return isa<FunctionDecl>(D);
916 }
917
918 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000919 switch (E->getStmtClass()) {
920 default:
921 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000922 case Expr::CompoundLiteralExprClass: {
923 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
924 return CLE->isFileScope() && CLE->isLValue();
925 }
Richard Smith180f4792011-11-10 06:34:14 +0000926 // A string literal has static storage duration.
927 case Expr::StringLiteralClass:
928 case Expr::PredefinedExprClass:
929 case Expr::ObjCStringLiteralClass:
930 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000931 case Expr::CXXTypeidExprClass:
Francois Pichete275a182012-04-16 04:08:35 +0000932 case Expr::CXXUuidofExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000933 return true;
934 case Expr::CallExprClass:
935 return IsStringLiteralCall(cast<CallExpr>(E));
936 // For GCC compatibility, &&label has static storage duration.
937 case Expr::AddrLabelExprClass:
938 return true;
939 // A Block literal expression may be used as the initialization value for
940 // Block variables at global or local static scope.
941 case Expr::BlockExprClass:
942 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000943 case Expr::ImplicitValueInitExprClass:
944 // FIXME:
945 // We can never form an lvalue with an implicit value initialization as its
946 // base through expression evaluation, so these only appear in one case: the
947 // implicit variable declaration we invent when checking whether a constexpr
948 // constructor can produce a constant expression. We must assume that such
949 // an expression might be a global lvalue.
950 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000951 }
John McCall42c8f872010-05-10 23:27:23 +0000952}
953
Richard Smith83587db2012-02-15 02:18:13 +0000954static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
955 assert(Base && "no location for a null lvalue");
956 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
957 if (VD)
958 Info.Note(VD->getLocation(), diag::note_declared_at);
959 else
960 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
961 diag::note_constexpr_temporary_here);
962}
963
Richard Smith9a17a682011-11-07 05:07:52 +0000964/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000965/// value for an address or reference constant expression. Return true if we
966/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000967static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
968 QualType Type, const LValue &LVal) {
969 bool IsReferenceType = Type->isReferenceType();
970
Richard Smithc1c5f272011-12-13 06:39:58 +0000971 APValue::LValueBase Base = LVal.getLValueBase();
972 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
973
Richard Smithb78ae972012-02-18 04:58:18 +0000974 // Check that the object is a global. Note that the fake 'this' object we
975 // manufacture when checking potential constant expressions is conservatively
976 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000977 if (!IsGlobalLValue(Base)) {
978 if (Info.getLangOpts().CPlusPlus0x) {
979 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000980 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
981 << IsReferenceType << !Designator.Entries.empty()
982 << !!VD << VD;
983 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000984 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000985 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000986 }
Richard Smith61e61622012-01-12 06:08:57 +0000987 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000988 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000989 }
Richard Smith83587db2012-02-15 02:18:13 +0000990 assert((Info.CheckingPotentialConstantExpression ||
991 LVal.getLValueCallIndex() == 0) &&
992 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +0000993
994 // Allow address constant expressions to be past-the-end pointers. This is
995 // an extension: the standard requires them to point to an object.
996 if (!IsReferenceType)
997 return true;
998
999 // A reference constant expression must refer to an object.
1000 if (!Base) {
1001 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001002 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001003 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001004 }
1005
Richard Smithc1c5f272011-12-13 06:39:58 +00001006 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001007 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001008 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001009 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001010 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001011 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001012 }
1013
Richard Smith9a17a682011-11-07 05:07:52 +00001014 return true;
1015}
1016
Richard Smith51201882011-12-30 21:15:51 +00001017/// Check that this core constant expression is of literal type, and if not,
1018/// produce an appropriate diagnostic.
1019static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1020 if (!E->isRValue() || E->getType()->isLiteralType())
1021 return true;
1022
1023 // Prvalue constant expressions must be of literal types.
1024 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001025 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001026 << E->getType();
1027 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001028 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001029 return false;
1030}
1031
Richard Smith47a1eed2011-10-29 20:57:55 +00001032/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001033/// constant expression. If not, report an appropriate diagnostic. Does not
1034/// check that the expression is of literal type.
1035static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1036 QualType Type, const APValue &Value) {
1037 // Core issue 1454: For a literal constant expression of array or class type,
1038 // each subobject of its value shall have been initialized by a constant
1039 // expression.
1040 if (Value.isArray()) {
1041 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1042 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1043 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1044 Value.getArrayInitializedElt(I)))
1045 return false;
1046 }
1047 if (!Value.hasArrayFiller())
1048 return true;
1049 return CheckConstantExpression(Info, DiagLoc, EltTy,
1050 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001051 }
Richard Smith83587db2012-02-15 02:18:13 +00001052 if (Value.isUnion() && Value.getUnionField()) {
1053 return CheckConstantExpression(Info, DiagLoc,
1054 Value.getUnionField()->getType(),
1055 Value.getUnionValue());
1056 }
1057 if (Value.isStruct()) {
1058 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1059 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1060 unsigned BaseIndex = 0;
1061 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1062 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1063 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1064 Value.getStructBase(BaseIndex)))
1065 return false;
1066 }
1067 }
1068 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1069 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001070 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1071 Value.getStructField(I->getFieldIndex())))
Richard Smith83587db2012-02-15 02:18:13 +00001072 return false;
1073 }
1074 }
1075
1076 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001077 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001078 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001079 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1080 }
1081
1082 // Everything else is fine.
1083 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001084}
1085
Richard Smith9e36b532011-10-31 05:11:32 +00001086const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001087 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001088}
1089
1090static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001091 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001092}
1093
Richard Smith65ac5982011-11-01 21:06:14 +00001094static bool IsWeakLValue(const LValue &Value) {
1095 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001096 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001097}
1098
Richard Smith1aa0be82012-03-03 22:46:17 +00001099static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001100 // A null base expression indicates a null pointer. These are always
1101 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001102 if (!Value.getLValueBase()) {
1103 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001104 return true;
1105 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001106
Richard Smithe24f5fc2011-11-17 22:56:20 +00001107 // We have a non-null base. These are generally known to be true, but if it's
1108 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001109 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001110 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001111 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001112}
1113
Richard Smith1aa0be82012-03-03 22:46:17 +00001114static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001115 switch (Val.getKind()) {
1116 case APValue::Uninitialized:
1117 return false;
1118 case APValue::Int:
1119 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001120 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001121 case APValue::Float:
1122 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001123 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001124 case APValue::ComplexInt:
1125 Result = Val.getComplexIntReal().getBoolValue() ||
1126 Val.getComplexIntImag().getBoolValue();
1127 return true;
1128 case APValue::ComplexFloat:
1129 Result = !Val.getComplexFloatReal().isZero() ||
1130 !Val.getComplexFloatImag().isZero();
1131 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001132 case APValue::LValue:
1133 return EvalPointerValueAsBool(Val, Result);
1134 case APValue::MemberPointer:
1135 Result = Val.getMemberPointerDecl();
1136 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001137 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001138 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001139 case APValue::Struct:
1140 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001141 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001142 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001143 }
1144
Richard Smithc49bd112011-10-28 17:51:58 +00001145 llvm_unreachable("unknown APValue kind");
1146}
1147
1148static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1149 EvalInfo &Info) {
1150 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001151 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001152 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001153 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001154 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001155}
1156
Richard Smithc1c5f272011-12-13 06:39:58 +00001157template<typename T>
1158static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1159 const T &SrcValue, QualType DestType) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001160 Info.Diag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001161 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001162 return false;
1163}
1164
1165static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1166 QualType SrcType, const APFloat &Value,
1167 QualType DestType, APSInt &Result) {
1168 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001169 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001170 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001171
Richard Smithc1c5f272011-12-13 06:39:58 +00001172 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001173 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001174 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1175 & APFloat::opInvalidOp)
1176 return HandleOverflow(Info, E, Value, DestType);
1177 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001178}
1179
Richard Smithc1c5f272011-12-13 06:39:58 +00001180static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1181 QualType SrcType, QualType DestType,
1182 APFloat &Result) {
1183 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001184 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001185 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1186 APFloat::rmNearestTiesToEven, &ignored)
1187 & APFloat::opOverflow)
1188 return HandleOverflow(Info, E, Value, DestType);
1189 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001190}
1191
Richard Smithf72fccf2012-01-30 22:27:01 +00001192static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1193 QualType DestType, QualType SrcType,
1194 APSInt &Value) {
1195 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001196 APSInt Result = Value;
1197 // Figure out if this is a truncate, extend or noop cast.
1198 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001199 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001200 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001201 return Result;
1202}
1203
Richard Smithc1c5f272011-12-13 06:39:58 +00001204static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1205 QualType SrcType, const APSInt &Value,
1206 QualType DestType, APFloat &Result) {
1207 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1208 if (Result.convertFromAPInt(Value, Value.isSigned(),
1209 APFloat::rmNearestTiesToEven)
1210 & APFloat::opOverflow)
1211 return HandleOverflow(Info, E, Value, DestType);
1212 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001213}
1214
Eli Friedmane6a24e82011-12-22 03:51:45 +00001215static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1216 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001217 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001218 if (!Evaluate(SVal, Info, E))
1219 return false;
1220 if (SVal.isInt()) {
1221 Res = SVal.getInt();
1222 return true;
1223 }
1224 if (SVal.isFloat()) {
1225 Res = SVal.getFloat().bitcastToAPInt();
1226 return true;
1227 }
1228 if (SVal.isVector()) {
1229 QualType VecTy = E->getType();
1230 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1231 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1232 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1233 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1234 Res = llvm::APInt::getNullValue(VecSize);
1235 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1236 APValue &Elt = SVal.getVectorElt(i);
1237 llvm::APInt EltAsInt;
1238 if (Elt.isInt()) {
1239 EltAsInt = Elt.getInt();
1240 } else if (Elt.isFloat()) {
1241 EltAsInt = Elt.getFloat().bitcastToAPInt();
1242 } else {
1243 // Don't try to handle vectors of anything other than int or float
1244 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001245 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001246 return false;
1247 }
1248 unsigned BaseEltSize = EltAsInt.getBitWidth();
1249 if (BigEndian)
1250 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1251 else
1252 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1253 }
1254 return true;
1255 }
1256 // Give up if the input isn't an int, float, or vector. For example, we
1257 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001258 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001259 return false;
1260}
1261
Richard Smithb4e85ed2012-01-06 16:39:00 +00001262/// Cast an lvalue referring to a base subobject to a derived class, by
1263/// truncating the lvalue's path to the given length.
1264static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1265 const RecordDecl *TruncatedType,
1266 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001267 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001268
1269 // Check we actually point to a derived class object.
1270 if (TruncatedElements == D.Entries.size())
1271 return true;
1272 assert(TruncatedElements >= D.MostDerivedPathLength &&
1273 "not casting to a derived class");
1274 if (!Result.checkSubobject(Info, E, CSK_Derived))
1275 return false;
1276
1277 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001278 const RecordDecl *RD = TruncatedType;
1279 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCall8d59dee2012-05-01 00:38:49 +00001280 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001281 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1282 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001283 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001284 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001285 else
Richard Smith180f4792011-11-10 06:34:14 +00001286 Result.Offset -= Layout.getBaseClassOffset(Base);
1287 RD = Base;
1288 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001289 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001290 return true;
1291}
1292
John McCall8d59dee2012-05-01 00:38:49 +00001293static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001294 const CXXRecordDecl *Derived,
1295 const CXXRecordDecl *Base,
1296 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001297 if (!RL) {
1298 if (Derived->isInvalidDecl()) return false;
1299 RL = &Info.Ctx.getASTRecordLayout(Derived);
1300 }
1301
Richard Smith180f4792011-11-10 06:34:14 +00001302 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001303 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCall8d59dee2012-05-01 00:38:49 +00001304 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001305}
1306
Richard Smithb4e85ed2012-01-06 16:39:00 +00001307static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001308 const CXXRecordDecl *DerivedDecl,
1309 const CXXBaseSpecifier *Base) {
1310 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1311
John McCall8d59dee2012-05-01 00:38:49 +00001312 if (!Base->isVirtual())
1313 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001314
Richard Smithb4e85ed2012-01-06 16:39:00 +00001315 SubobjectDesignator &D = Obj.Designator;
1316 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001317 return false;
1318
Richard Smithb4e85ed2012-01-06 16:39:00 +00001319 // Extract most-derived object and corresponding type.
1320 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1321 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1322 return false;
1323
1324 // Find the virtual base class.
John McCall8d59dee2012-05-01 00:38:49 +00001325 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001326 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1327 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001328 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001329 return true;
1330}
1331
1332/// Update LVal to refer to the given field, which must be a member of the type
1333/// currently described by LVal.
John McCall8d59dee2012-05-01 00:38:49 +00001334static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001335 const FieldDecl *FD,
1336 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001337 if (!RL) {
1338 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001339 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCall8d59dee2012-05-01 00:38:49 +00001340 }
Richard Smith180f4792011-11-10 06:34:14 +00001341
1342 unsigned I = FD->getFieldIndex();
1343 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001344 LVal.addDecl(Info, E, FD);
John McCall8d59dee2012-05-01 00:38:49 +00001345 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001346}
1347
Richard Smithd9b02e72012-01-25 22:15:11 +00001348/// Update LVal to refer to the given indirect field.
John McCall8d59dee2012-05-01 00:38:49 +00001349static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smithd9b02e72012-01-25 22:15:11 +00001350 LValue &LVal,
1351 const IndirectFieldDecl *IFD) {
1352 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1353 CE = IFD->chain_end(); C != CE; ++C)
John McCall8d59dee2012-05-01 00:38:49 +00001354 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1355 return false;
1356 return true;
Richard Smithd9b02e72012-01-25 22:15:11 +00001357}
1358
Richard Smith180f4792011-11-10 06:34:14 +00001359/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001360static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1361 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001362 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1363 // extension.
1364 if (Type->isVoidType() || Type->isFunctionType()) {
1365 Size = CharUnits::One();
1366 return true;
1367 }
1368
1369 if (!Type->isConstantSizeType()) {
1370 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001371 // FIXME: Better diagnostic.
1372 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001373 return false;
1374 }
1375
1376 Size = Info.Ctx.getTypeSizeInChars(Type);
1377 return true;
1378}
1379
1380/// Update a pointer value to model pointer arithmetic.
1381/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001382/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001383/// \param LVal - The pointer value to be updated.
1384/// \param EltTy - The pointee type represented by LVal.
1385/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001386static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1387 LValue &LVal, QualType EltTy,
1388 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001389 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001390 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001391 return false;
1392
1393 // Compute the new offset in the appropriate width.
1394 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001395 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001396 return true;
1397}
1398
Richard Smith86024012012-02-18 22:04:06 +00001399/// Update an lvalue to refer to a component of a complex number.
1400/// \param Info - Information about the ongoing evaluation.
1401/// \param LVal - The lvalue to be updated.
1402/// \param EltTy - The complex number's component type.
1403/// \param Imag - False for the real component, true for the imaginary.
1404static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1405 LValue &LVal, QualType EltTy,
1406 bool Imag) {
1407 if (Imag) {
1408 CharUnits SizeOfComponent;
1409 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1410 return false;
1411 LVal.Offset += SizeOfComponent;
1412 }
1413 LVal.addComplex(Info, E, EltTy, Imag);
1414 return true;
1415}
1416
Richard Smith03f96112011-10-24 17:54:18 +00001417/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001418static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1419 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001420 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001421 // If this is a parameter to an active constexpr function call, perform
1422 // argument substitution.
1423 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001424 // Assume arguments of a potential constant expression are unknown
1425 // constant expressions.
1426 if (Info.CheckingPotentialConstantExpression)
1427 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001428 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001429 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001430 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001431 }
Richard Smith177dce72011-11-01 16:57:24 +00001432 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1433 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001434 }
Richard Smith03f96112011-10-24 17:54:18 +00001435
Richard Smith099e7f62011-12-19 06:19:21 +00001436 // Dig out the initializer, and use the declaration which it's attached to.
1437 const Expr *Init = VD->getAnyInitializer(VD);
1438 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001439 // If we're checking a potential constant expression, the variable could be
1440 // initialized later.
1441 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001442 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001443 return false;
1444 }
1445
Richard Smith180f4792011-11-10 06:34:14 +00001446 // If we're currently evaluating the initializer of this declaration, use that
1447 // in-flight value.
1448 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001449 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001450 return !Result.isUninit();
1451 }
1452
Richard Smith65ac5982011-11-01 21:06:14 +00001453 // Never evaluate the initializer of a weak variable. We can't be sure that
1454 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001455 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001456 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001457 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001458 }
Richard Smith65ac5982011-11-01 21:06:14 +00001459
Richard Smith099e7f62011-12-19 06:19:21 +00001460 // Check that we can fold the initializer. In C++, we will have already done
1461 // this in the cases where it matters for conformance.
1462 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1463 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001464 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001465 Notes.size() + 1) << VD;
1466 Info.Note(VD->getLocation(), diag::note_declared_at);
1467 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001468 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001469 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001470 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001471 Notes.size() + 1) << VD;
1472 Info.Note(VD->getLocation(), diag::note_declared_at);
1473 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001474 }
Richard Smith03f96112011-10-24 17:54:18 +00001475
Richard Smith1aa0be82012-03-03 22:46:17 +00001476 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001477 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001478}
1479
Richard Smithc49bd112011-10-28 17:51:58 +00001480static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001481 Qualifiers Quals = T.getQualifiers();
1482 return Quals.hasConst() && !Quals.hasVolatile();
1483}
1484
Richard Smith59efe262011-11-11 04:05:33 +00001485/// Get the base index of the given base class within an APValue representing
1486/// the given derived class.
1487static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1488 const CXXRecordDecl *Base) {
1489 Base = Base->getCanonicalDecl();
1490 unsigned Index = 0;
1491 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1492 E = Derived->bases_end(); I != E; ++I, ++Index) {
1493 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1494 return Index;
1495 }
1496
1497 llvm_unreachable("base class missing from derived class's bases list");
1498}
1499
Richard Smithfe587202012-04-15 02:50:59 +00001500/// Extract the value of a character from a string literal. CharType is used to
1501/// determine the expected signedness of the result -- a string literal used to
1502/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1503/// of the wrong signedness.
Richard Smithf3908f22012-02-17 03:35:37 +00001504static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smithfe587202012-04-15 02:50:59 +00001505 uint64_t Index, QualType CharType) {
Richard Smithf3908f22012-02-17 03:35:37 +00001506 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1507 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1508 assert(S && "unexpected string literal expression kind");
Richard Smithfe587202012-04-15 02:50:59 +00001509 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smithf3908f22012-02-17 03:35:37 +00001510
1511 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smithfe587202012-04-15 02:50:59 +00001512 CharType->isUnsignedIntegerType());
Richard Smithf3908f22012-02-17 03:35:37 +00001513 if (Index < S->getLength())
1514 Value = S->getCodeUnit(Index);
1515 return Value;
1516}
1517
Richard Smithcc5d4f62011-11-07 09:22:26 +00001518/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001519static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001520 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001521 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001522 if (Sub.Invalid)
1523 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001524 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001525 if (Sub.isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001526 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001527 (unsigned)diag::note_constexpr_read_past_end :
1528 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001529 return false;
1530 }
Richard Smithf64699e2011-11-11 08:28:03 +00001531 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001532 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001533 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1534 // This object might be initialized later.
1535 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001536
Richard Smith0069b842012-03-10 00:28:11 +00001537 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001538 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001539 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001540 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001541 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001542 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001543 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001544 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001545 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001546 // Note, it should not be possible to form a pointer with a valid
1547 // designator which points more than one past the end of the array.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001548 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001549 (unsigned)diag::note_constexpr_read_past_end :
1550 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001551 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001552 }
Richard Smithf3908f22012-02-17 03:35:37 +00001553 // An array object is represented as either an Array APValue or as an
1554 // LValue which refers to a string literal.
1555 if (O->isLValue()) {
1556 assert(I == N - 1 && "extracting subobject of character?");
1557 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001558 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithfe587202012-04-15 02:50:59 +00001559 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smithf3908f22012-02-17 03:35:37 +00001560 return true;
1561 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001562 O = &O->getArrayInitializedElt(Index);
1563 else
1564 O = &O->getArrayFiller();
1565 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001566 } else if (ObjType->isAnyComplexType()) {
1567 // Next subobject is a complex number.
1568 uint64_t Index = Sub.Entries[I].ArrayIndex;
1569 if (Index > 1) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001570 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Richard Smith86024012012-02-18 22:04:06 +00001571 (unsigned)diag::note_constexpr_read_past_end :
1572 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1573 return false;
1574 }
1575 assert(I == N - 1 && "extracting subobject of scalar?");
1576 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001577 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001578 : O->getComplexIntReal());
1579 } else {
1580 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001581 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001582 : O->getComplexFloatReal());
1583 }
1584 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001585 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001586 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001587 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001588 << Field;
1589 Info.Note(Field->getLocation(), diag::note_declared_at);
1590 return false;
1591 }
1592
Richard Smith180f4792011-11-10 06:34:14 +00001593 // Next subobject is a class, struct or union field.
1594 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1595 if (RD->isUnion()) {
1596 const FieldDecl *UnionField = O->getUnionField();
1597 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001598 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001599 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001600 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001601 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001602 }
Richard Smith180f4792011-11-10 06:34:14 +00001603 O = &O->getUnionValue();
1604 } else
1605 O = &O->getStructField(Field->getFieldIndex());
1606 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001607
1608 if (ObjType.isVolatileQualified()) {
1609 if (Info.getLangOpts().CPlusPlus) {
1610 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001611 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001612 << 2 << Field;
1613 Info.Note(Field->getLocation(), diag::note_declared_at);
1614 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001615 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001616 }
1617 return false;
1618 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001619 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001620 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001621 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1622 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1623 O = &O->getStructBase(getBaseIndex(Derived, Base));
1624 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001625 }
Richard Smith180f4792011-11-10 06:34:14 +00001626
Richard Smithf48fdb02011-12-09 22:58:01 +00001627 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001628 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001629 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001630 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001631 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001632 }
1633
Richard Smith0069b842012-03-10 00:28:11 +00001634 // This may look super-stupid, but it serves an important purpose: if we just
1635 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1636 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1637 // object, which is destroyed by Tmp's destructor.
1638 APValue Tmp;
1639 O->swap(Tmp);
1640 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001641 return true;
1642}
1643
Richard Smithf15fda02012-02-02 01:16:57 +00001644/// Find the position where two subobject designators diverge, or equivalently
1645/// the length of the common initial subsequence.
1646static unsigned FindDesignatorMismatch(QualType ObjType,
1647 const SubobjectDesignator &A,
1648 const SubobjectDesignator &B,
1649 bool &WasArrayIndex) {
1650 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1651 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001652 if (!ObjType.isNull() &&
1653 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001654 // Next subobject is an array element.
1655 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1656 WasArrayIndex = true;
1657 return I;
1658 }
Richard Smith86024012012-02-18 22:04:06 +00001659 if (ObjType->isAnyComplexType())
1660 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1661 else
1662 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001663 } else {
1664 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1665 WasArrayIndex = false;
1666 return I;
1667 }
1668 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1669 // Next subobject is a field.
1670 ObjType = FD->getType();
1671 else
1672 // Next subobject is a base class.
1673 ObjType = QualType();
1674 }
1675 }
1676 WasArrayIndex = false;
1677 return I;
1678}
1679
1680/// Determine whether the given subobject designators refer to elements of the
1681/// same array object.
1682static bool AreElementsOfSameArray(QualType ObjType,
1683 const SubobjectDesignator &A,
1684 const SubobjectDesignator &B) {
1685 if (A.Entries.size() != B.Entries.size())
1686 return false;
1687
1688 bool IsArray = A.MostDerivedArraySize != 0;
1689 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1690 // A is a subobject of the array element.
1691 return false;
1692
1693 // If A (and B) designates an array element, the last entry will be the array
1694 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1695 // of length 1' case, and the entire path must match.
1696 bool WasArrayIndex;
1697 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1698 return CommonLength >= A.Entries.size() - IsArray;
1699}
1700
Richard Smith180f4792011-11-10 06:34:14 +00001701/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1702/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1703/// for looking up the glvalue referred to by an entity of reference type.
1704///
1705/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001706/// \param Conv - The expression for which we are performing the conversion.
1707/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001708/// \param Type - The type we expect this conversion to produce, before
1709/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001710/// \param LVal - The glvalue on which we are attempting to perform this action.
1711/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001712static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1713 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001714 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001715 if (LVal.Designator.Invalid)
1716 // A diagnostic will have already been produced.
1717 return false;
1718
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001719 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001720
Richard Smithf48fdb02011-12-09 22:58:01 +00001721 if (!LVal.Base) {
1722 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001723 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001724 return false;
1725 }
1726
Richard Smith83587db2012-02-15 02:18:13 +00001727 CallStackFrame *Frame = 0;
1728 if (LVal.CallIndex) {
1729 Frame = Info.getCallFrame(LVal.CallIndex);
1730 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001731 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001732 NoteLValueLocation(Info, LVal.Base);
1733 return false;
1734 }
1735 }
1736
Richard Smith7098cbd2011-12-21 05:04:46 +00001737 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1738 // is not a constant expression (even if the object is non-volatile). We also
1739 // apply this rule to C++98, in order to conform to the expected 'volatile'
1740 // semantics.
1741 if (Type.isVolatileQualified()) {
1742 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001743 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001744 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001745 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001746 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001747 }
Richard Smithc49bd112011-10-28 17:51:58 +00001748
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001749 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001750 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1751 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001752 // expressions are constant expressions too. Inside constexpr functions,
1753 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001754 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001755 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregord2008e22012-04-06 22:40:38 +00001756 if (VD) {
1757 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1758 VD = VDef;
1759 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001760 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001761 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001762 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001763 }
1764
Richard Smith7098cbd2011-12-21 05:04:46 +00001765 // DR1313: If the object is volatile-qualified but the glvalue was not,
1766 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001767 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001768 if (VT.isVolatileQualified()) {
1769 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001770 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001771 Info.Note(VD->getLocation(), diag::note_declared_at);
1772 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001773 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001774 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001775 return false;
1776 }
1777
1778 if (!isa<ParmVarDecl>(VD)) {
1779 if (VD->isConstexpr()) {
1780 // OK, we can read this variable.
1781 } else if (VT->isIntegralOrEnumerationType()) {
1782 if (!VT.isConstQualified()) {
1783 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001784 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001785 Info.Note(VD->getLocation(), diag::note_declared_at);
1786 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001787 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001788 }
1789 return false;
1790 }
1791 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1792 // We support folding of const floating-point types, in order to make
1793 // static const data members of such types (supported as an extension)
1794 // more useful.
1795 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001796 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001797 Info.Note(VD->getLocation(), diag::note_declared_at);
1798 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001799 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001800 }
1801 } else {
1802 // FIXME: Allow folding of values of any literal type in all languages.
1803 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001804 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001805 Info.Note(VD->getLocation(), diag::note_declared_at);
1806 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001807 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001808 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001809 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001810 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001811 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001812
Richard Smithf48fdb02011-12-09 22:58:01 +00001813 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001814 return false;
1815
Richard Smith47a1eed2011-10-29 20:57:55 +00001816 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001817 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001818
1819 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1820 // conversion. This happens when the declaration and the lvalue should be
1821 // considered synonymous, for instance when initializing an array of char
1822 // from a string literal. Continue as if the initializer lvalue was the
1823 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001824 assert(RVal.getLValueOffset().isZero() &&
1825 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001826 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001827
1828 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1829 Frame = Info.getCallFrame(CallIndex);
1830 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001831 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001832 NoteLValueLocation(Info, RVal.getLValueBase());
1833 return false;
1834 }
1835 } else {
1836 Frame = 0;
1837 }
Richard Smithc49bd112011-10-28 17:51:58 +00001838 }
1839
Richard Smith7098cbd2011-12-21 05:04:46 +00001840 // Volatile temporary objects cannot be read in constant expressions.
1841 if (Base->getType().isVolatileQualified()) {
1842 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001843 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001844 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1845 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001846 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001847 }
1848 return false;
1849 }
1850
Richard Smithcc5d4f62011-11-07 09:22:26 +00001851 if (Frame) {
1852 // If this is a temporary expression with a nontrivial initializer, grab the
1853 // value from the relevant stack frame.
1854 RVal = Frame->Temporaries[Base];
1855 } else if (const CompoundLiteralExpr *CLE
1856 = dyn_cast<CompoundLiteralExpr>(Base)) {
1857 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1858 // initializer until now for such expressions. Such an expression can't be
1859 // an ICE in C, so this only matters for fold.
1860 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1861 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1862 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001863 } else if (isa<StringLiteral>(Base)) {
1864 // We represent a string literal array as an lvalue pointing at the
1865 // corresponding expression, rather than building an array of chars.
1866 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001867 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001868 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001869 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001870 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001871 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001872
Richard Smithf48fdb02011-12-09 22:58:01 +00001873 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1874 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001875}
1876
Richard Smith59efe262011-11-11 04:05:33 +00001877/// Build an lvalue for the object argument of a member function call.
1878static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1879 LValue &This) {
1880 if (Object->getType()->isPointerType())
1881 return EvaluatePointer(Object, This, Info);
1882
1883 if (Object->isGLValue())
1884 return EvaluateLValue(Object, This, Info);
1885
Richard Smithe24f5fc2011-11-17 22:56:20 +00001886 if (Object->getType()->isLiteralType())
1887 return EvaluateTemporary(Object, This, Info);
1888
1889 return false;
1890}
1891
1892/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1893/// lvalue referring to the result.
1894///
1895/// \param Info - Information about the ongoing evaluation.
1896/// \param BO - The member pointer access operation.
1897/// \param LV - Filled in with a reference to the resulting object.
1898/// \param IncludeMember - Specifies whether the member itself is included in
1899/// the resulting LValue subobject designator. This is not possible when
1900/// creating a bound member function.
1901/// \return The field or method declaration to which the member pointer refers,
1902/// or 0 if evaluation fails.
1903static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1904 const BinaryOperator *BO,
1905 LValue &LV,
1906 bool IncludeMember = true) {
1907 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1908
Richard Smith745f5142012-01-27 01:14:48 +00001909 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1910 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001911 return 0;
1912
1913 MemberPtr MemPtr;
1914 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1915 return 0;
1916
1917 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1918 // member value, the behavior is undefined.
1919 if (!MemPtr.getDecl())
1920 return 0;
1921
Richard Smith745f5142012-01-27 01:14:48 +00001922 if (!EvalObjOK)
1923 return 0;
1924
Richard Smithe24f5fc2011-11-17 22:56:20 +00001925 if (MemPtr.isDerivedMember()) {
1926 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001927 // The end of the derived-to-base path for the base object must match the
1928 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001929 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001930 LV.Designator.Entries.size())
1931 return 0;
1932 unsigned PathLengthToMember =
1933 LV.Designator.Entries.size() - MemPtr.Path.size();
1934 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1935 const CXXRecordDecl *LVDecl = getAsBaseClass(
1936 LV.Designator.Entries[PathLengthToMember + I]);
1937 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1938 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1939 return 0;
1940 }
1941
1942 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001943 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1944 PathLengthToMember))
1945 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001946 } else if (!MemPtr.Path.empty()) {
1947 // Extend the LValue path with the member pointer's path.
1948 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1949 MemPtr.Path.size() + IncludeMember);
1950
1951 // Walk down to the appropriate base class.
1952 QualType LVType = BO->getLHS()->getType();
1953 if (const PointerType *PT = LVType->getAs<PointerType>())
1954 LVType = PT->getPointeeType();
1955 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1956 assert(RD && "member pointer access on non-class-type expression");
1957 // The first class in the path is that of the lvalue.
1958 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1959 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCall8d59dee2012-05-01 00:38:49 +00001960 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1961 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001962 RD = Base;
1963 }
1964 // Finally cast to the class containing the member.
John McCall8d59dee2012-05-01 00:38:49 +00001965 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1966 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001967 }
1968
1969 // Add the member. Note that we cannot build bound member functions here.
1970 if (IncludeMember) {
John McCall8d59dee2012-05-01 00:38:49 +00001971 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
1972 if (!HandleLValueMember(Info, BO, LV, FD))
1973 return 0;
1974 } else if (const IndirectFieldDecl *IFD =
1975 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
1976 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
1977 return 0;
1978 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00001979 llvm_unreachable("can't construct reference to bound member function");
John McCall8d59dee2012-05-01 00:38:49 +00001980 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001981 }
1982
1983 return MemPtr.getDecl();
1984}
1985
1986/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1987/// the provided lvalue, which currently refers to the base object.
1988static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1989 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001990 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001991 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001992 return false;
1993
Richard Smithb4e85ed2012-01-06 16:39:00 +00001994 QualType TargetQT = E->getType();
1995 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1996 TargetQT = PT->getPointeeType();
1997
1998 // Check this cast lands within the final derived-to-base subobject path.
1999 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002000 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002001 << D.MostDerivedType << TargetQT;
2002 return false;
2003 }
2004
Richard Smithe24f5fc2011-11-17 22:56:20 +00002005 // Check the type of the final cast. We don't need to check the path,
2006 // since a cast can only be formed if the path is unique.
2007 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002008 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2009 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002010 if (NewEntriesSize == D.MostDerivedPathLength)
2011 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2012 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002013 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002014 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002015 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002016 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002017 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002018 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002019
2020 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002021 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002022}
2023
Mike Stumpc4c90452009-10-27 22:09:17 +00002024namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002025enum EvalStmtResult {
2026 /// Evaluation failed.
2027 ESR_Failed,
2028 /// Hit a 'return' statement.
2029 ESR_Returned,
2030 /// Evaluation succeeded.
2031 ESR_Succeeded
2032};
2033}
2034
2035// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002036static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002037 const Stmt *S) {
2038 switch (S->getStmtClass()) {
2039 default:
2040 return ESR_Failed;
2041
2042 case Stmt::NullStmtClass:
2043 case Stmt::DeclStmtClass:
2044 return ESR_Succeeded;
2045
Richard Smithc1c5f272011-12-13 06:39:58 +00002046 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002047 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002048 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002049 return ESR_Failed;
2050 return ESR_Returned;
2051 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002052
2053 case Stmt::CompoundStmtClass: {
2054 const CompoundStmt *CS = cast<CompoundStmt>(S);
2055 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2056 BE = CS->body_end(); BI != BE; ++BI) {
2057 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2058 if (ESR != ESR_Succeeded)
2059 return ESR;
2060 }
2061 return ESR_Succeeded;
2062 }
2063 }
2064}
2065
Richard Smith61802452011-12-22 02:22:31 +00002066/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2067/// default constructor. If so, we'll fold it whether or not it's marked as
2068/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2069/// so we need special handling.
2070static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002071 const CXXConstructorDecl *CD,
2072 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002073 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2074 return false;
2075
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002076 // Value-initialization does not call a trivial default constructor, so such a
2077 // call is a core constant expression whether or not the constructor is
2078 // constexpr.
2079 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002080 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002081 // FIXME: If DiagDecl is an implicitly-declared special member function,
2082 // we should be much more explicit about why it's not constexpr.
2083 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2084 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2085 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002086 } else {
2087 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2088 }
2089 }
2090 return true;
2091}
2092
Richard Smithc1c5f272011-12-13 06:39:58 +00002093/// CheckConstexprFunction - Check that a function can be called in a constant
2094/// expression.
2095static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2096 const FunctionDecl *Declaration,
2097 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002098 // Potential constant expressions can contain calls to declared, but not yet
2099 // defined, constexpr functions.
2100 if (Info.CheckingPotentialConstantExpression && !Definition &&
2101 Declaration->isConstexpr())
2102 return false;
2103
Richard Smithc1c5f272011-12-13 06:39:58 +00002104 // Can we evaluate this function call?
2105 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2106 return true;
2107
2108 if (Info.getLangOpts().CPlusPlus0x) {
2109 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002110 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2111 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002112 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2113 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2114 << DiagDecl;
2115 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2116 } else {
2117 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2118 }
2119 return false;
2120}
2121
Richard Smith180f4792011-11-10 06:34:14 +00002122namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002123typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002124}
2125
2126/// EvaluateArgs - Evaluate the arguments to a function call.
2127static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2128 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002129 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002130 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002131 I != E; ++I) {
2132 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2133 // If we're checking for a potential constant expression, evaluate all
2134 // initializers even if some of them fail.
2135 if (!Info.keepEvaluatingAfterFailure())
2136 return false;
2137 Success = false;
2138 }
2139 }
2140 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002141}
2142
Richard Smithd0dccea2011-10-28 22:34:42 +00002143/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002144static bool HandleFunctionCall(SourceLocation CallLoc,
2145 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002146 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002147 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002148 ArgVector ArgValues(Args.size());
2149 if (!EvaluateArgs(Args, ArgValues, Info))
2150 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002151
Richard Smith745f5142012-01-27 01:14:48 +00002152 if (!Info.CheckCallLimit(CallLoc))
2153 return false;
2154
2155 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002156 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2157}
2158
Richard Smith180f4792011-11-10 06:34:14 +00002159/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002160static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002161 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002162 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002163 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002164 ArgVector ArgValues(Args.size());
2165 if (!EvaluateArgs(Args, ArgValues, Info))
2166 return false;
2167
Richard Smith745f5142012-01-27 01:14:48 +00002168 if (!Info.CheckCallLimit(CallLoc))
2169 return false;
2170
Richard Smith86c3ae42012-02-13 03:54:03 +00002171 const CXXRecordDecl *RD = Definition->getParent();
2172 if (RD->getNumVBases()) {
2173 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2174 return false;
2175 }
2176
Richard Smith745f5142012-01-27 01:14:48 +00002177 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002178
2179 // If it's a delegating constructor, just delegate.
2180 if (Definition->isDelegatingConstructor()) {
2181 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002182 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002183 }
2184
Richard Smith610a60c2012-01-10 04:32:03 +00002185 // For a trivial copy or move constructor, perform an APValue copy. This is
2186 // essential for unions, where the operations performed by the constructor
2187 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002188 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002189 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2190 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002191 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002192 RHS.setFrom(Info.Ctx, ArgValues[0]);
2193 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2194 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002195 }
2196
2197 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002198 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002199 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2200 std::distance(RD->field_begin(), RD->field_end()));
2201
John McCall8d59dee2012-05-01 00:38:49 +00002202 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00002203 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2204
Richard Smith745f5142012-01-27 01:14:48 +00002205 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002206 unsigned BasesSeen = 0;
2207#ifndef NDEBUG
2208 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2209#endif
2210 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2211 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002212 LValue Subobject = This;
2213 APValue *Value = &Result;
2214
2215 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002216 if ((*I)->isBaseInitializer()) {
2217 QualType BaseType((*I)->getBaseClass(), 0);
2218#ifndef NDEBUG
2219 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002220 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002221 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2222 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2223 "base class initializers not in expected order");
2224 ++BaseIt;
2225#endif
John McCall8d59dee2012-05-01 00:38:49 +00002226 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2227 BaseType->getAsCXXRecordDecl(), &Layout))
2228 return false;
Richard Smith745f5142012-01-27 01:14:48 +00002229 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002230 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCall8d59dee2012-05-01 00:38:49 +00002231 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2232 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002233 if (RD->isUnion()) {
2234 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002235 Value = &Result.getUnionValue();
2236 } else {
2237 Value = &Result.getStructField(FD->getFieldIndex());
2238 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002239 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002240 // Walk the indirect field decl's chain to find the object to initialize,
2241 // and make sure we've initialized every step along it.
2242 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2243 CE = IFD->chain_end();
2244 C != CE; ++C) {
2245 FieldDecl *FD = cast<FieldDecl>(*C);
2246 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2247 // Switch the union field if it differs. This happens if we had
2248 // preceding zero-initialization, and we're now initializing a union
2249 // subobject other than the first.
2250 // FIXME: In this case, the values of the other subobjects are
2251 // specified, since zero-initialization sets all padding bits to zero.
2252 if (Value->isUninit() ||
2253 (Value->isUnion() && Value->getUnionField() != FD)) {
2254 if (CD->isUnion())
2255 *Value = APValue(FD);
2256 else
2257 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2258 std::distance(CD->field_begin(), CD->field_end()));
2259 }
John McCall8d59dee2012-05-01 00:38:49 +00002260 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2261 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002262 if (CD->isUnion())
2263 Value = &Value->getUnionValue();
2264 else
2265 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002266 }
Richard Smith180f4792011-11-10 06:34:14 +00002267 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002268 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002269 }
Richard Smith745f5142012-01-27 01:14:48 +00002270
Richard Smith83587db2012-02-15 02:18:13 +00002271 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2272 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002273 ? CCEK_Constant : CCEK_MemberInit)) {
2274 // If we're checking for a potential constant expression, evaluate all
2275 // initializers even if some of them fail.
2276 if (!Info.keepEvaluatingAfterFailure())
2277 return false;
2278 Success = false;
2279 }
Richard Smith180f4792011-11-10 06:34:14 +00002280 }
2281
Richard Smith745f5142012-01-27 01:14:48 +00002282 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002283}
2284
Richard Smithd0dccea2011-10-28 22:34:42 +00002285namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002286class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002287 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002288 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002289public:
2290
Richard Smith1e12c592011-10-16 21:26:27 +00002291 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002292
2293 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002294 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002295 return true;
2296 }
2297
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002298 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2299 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002300 return Visit(E->getResultExpr());
2301 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002302 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002303 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002304 return true;
2305 return false;
2306 }
John McCallf85e1932011-06-15 23:02:42 +00002307 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002308 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002309 return true;
2310 return false;
2311 }
John McCallf85e1932011-06-15 23:02:42 +00002312
Mike Stumpc4c90452009-10-27 22:09:17 +00002313 // We don't want to evaluate BlockExprs multiple times, as they generate
2314 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002315 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2316 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2317 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002318 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002319 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2320 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2321 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2322 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2323 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2324 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002325 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002326 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002327 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002328 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002329 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002330 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2331 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2332 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2333 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002334 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002335 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2336 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2337 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2338 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2339 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002340 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002341 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002342 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002343 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002344 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002345
2346 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002347 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002348 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2349 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002350 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002351 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002352 return false;
2353 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002354
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002355 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002356};
2357
Mike Stumpc4c90452009-10-27 22:09:17 +00002358} // end anonymous namespace
2359
Eli Friedman4efaa272008-11-12 09:44:48 +00002360//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002361// Generic Evaluation
2362//===----------------------------------------------------------------------===//
2363namespace {
2364
Richard Smithf48fdb02011-12-09 22:58:01 +00002365// FIXME: RetTy is always bool. Remove it.
2366template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002367class ExprEvaluatorBase
2368 : public ConstStmtVisitor<Derived, RetTy> {
2369private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002370 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002371 return static_cast<Derived*>(this)->Success(V, E);
2372 }
Richard Smith51201882011-12-30 21:15:51 +00002373 RetTy DerivedZeroInitialization(const Expr *E) {
2374 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002375 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002376
Richard Smith74e1ad92012-02-16 02:46:34 +00002377 // Check whether a conditional operator with a non-constant condition is a
2378 // potential constant expression. If neither arm is a potential constant
2379 // expression, then the conditional operator is not either.
2380 template<typename ConditionalOperator>
2381 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2382 assert(Info.CheckingPotentialConstantExpression);
2383
2384 // Speculatively evaluate both arms.
2385 {
2386 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2387 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2388
2389 StmtVisitorTy::Visit(E->getFalseExpr());
2390 if (Diag.empty())
2391 return;
2392
2393 Diag.clear();
2394 StmtVisitorTy::Visit(E->getTrueExpr());
2395 if (Diag.empty())
2396 return;
2397 }
2398
2399 Error(E, diag::note_constexpr_conditional_never_const);
2400 }
2401
2402
2403 template<typename ConditionalOperator>
2404 bool HandleConditionalOperator(const ConditionalOperator *E) {
2405 bool BoolResult;
2406 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2407 if (Info.CheckingPotentialConstantExpression)
2408 CheckPotentialConstantConditional(E);
2409 return false;
2410 }
2411
2412 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2413 return StmtVisitorTy::Visit(EvalExpr);
2414 }
2415
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002416protected:
2417 EvalInfo &Info;
2418 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2419 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2420
Richard Smithdd1f29b2011-12-12 09:28:41 +00002421 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002422 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002423 }
2424
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002425 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2426
2427public:
2428 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2429
2430 EvalInfo &getEvalInfo() { return Info; }
2431
Richard Smithf48fdb02011-12-09 22:58:01 +00002432 /// Report an evaluation error. This should only be called when an error is
2433 /// first discovered. When propagating an error, just return false.
2434 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002435 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002436 return false;
2437 }
2438 bool Error(const Expr *E) {
2439 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2440 }
2441
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002442 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002443 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002444 }
2445 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002446 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002447 }
2448
2449 RetTy VisitParenExpr(const ParenExpr *E)
2450 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2451 RetTy VisitUnaryExtension(const UnaryOperator *E)
2452 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2453 RetTy VisitUnaryPlus(const UnaryOperator *E)
2454 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2455 RetTy VisitChooseExpr(const ChooseExpr *E)
2456 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2457 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2458 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002459 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2460 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002461 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2462 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002463 // We cannot create any objects for which cleanups are required, so there is
2464 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2465 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2466 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002467
Richard Smithc216a012011-12-12 12:46:16 +00002468 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2469 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2470 return static_cast<Derived*>(this)->VisitCastExpr(E);
2471 }
2472 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2473 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2474 return static_cast<Derived*>(this)->VisitCastExpr(E);
2475 }
2476
Richard Smithe24f5fc2011-11-17 22:56:20 +00002477 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2478 switch (E->getOpcode()) {
2479 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002480 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002481
2482 case BO_Comma:
2483 VisitIgnoredValue(E->getLHS());
2484 return StmtVisitorTy::Visit(E->getRHS());
2485
2486 case BO_PtrMemD:
2487 case BO_PtrMemI: {
2488 LValue Obj;
2489 if (!HandleMemberPointerAccess(Info, E, Obj))
2490 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002491 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002492 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002493 return false;
2494 return DerivedSuccess(Result, E);
2495 }
2496 }
2497 }
2498
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002499 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002500 // Evaluate and cache the common expression. We treat it as a temporary,
2501 // even though it's not quite the same thing.
2502 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2503 Info, E->getCommon()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002504 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002505
Richard Smith74e1ad92012-02-16 02:46:34 +00002506 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002507 }
2508
2509 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002510 bool IsBcpCall = false;
2511 // If the condition (ignoring parens) is a __builtin_constant_p call,
2512 // the result is a constant expression if it can be folded without
2513 // side-effects. This is an important GNU extension. See GCC PR38377
2514 // for discussion.
2515 if (const CallExpr *CallCE =
2516 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2517 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2518 IsBcpCall = true;
2519
2520 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2521 // constant expression; we can't check whether it's potentially foldable.
2522 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2523 return false;
2524
2525 FoldConstant Fold(Info);
2526
Richard Smith74e1ad92012-02-16 02:46:34 +00002527 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002528 return false;
2529
2530 if (IsBcpCall)
2531 Fold.Fold(Info);
2532
2533 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002534 }
2535
2536 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002537 APValue &Value = Info.CurrentCall->Temporaries[E];
2538 if (Value.isUninit()) {
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002539 const Expr *Source = E->getSourceExpr();
2540 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002541 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002542 if (Source == E) { // sanity checking.
2543 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002544 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002545 }
2546 return StmtVisitorTy::Visit(Source);
2547 }
Richard Smithe92b1f42012-06-26 08:12:11 +00002548 return DerivedSuccess(Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002549 }
Richard Smithf10d9172011-10-11 21:43:33 +00002550
Richard Smithd0dccea2011-10-28 22:34:42 +00002551 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002552 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002553 QualType CalleeType = Callee->getType();
2554
Richard Smithd0dccea2011-10-28 22:34:42 +00002555 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002556 LValue *This = 0, ThisVal;
2557 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002558 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002559
Richard Smith59efe262011-11-11 04:05:33 +00002560 // Extract function decl and 'this' pointer from the callee.
2561 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002562 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002563 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2564 // Explicit bound member calls, such as x.f() or p->g();
2565 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002566 return false;
2567 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002568 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002569 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002570 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2571 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002572 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2573 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002574 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002575 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002576 return Error(Callee);
2577
2578 FD = dyn_cast<FunctionDecl>(Member);
2579 if (!FD)
2580 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002581 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002582 LValue Call;
2583 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002584 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002585
Richard Smithb4e85ed2012-01-06 16:39:00 +00002586 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002587 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002588 FD = dyn_cast_or_null<FunctionDecl>(
2589 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002590 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002591 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002592
2593 // Overloaded operator calls to member functions are represented as normal
2594 // calls with '*this' as the first argument.
2595 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2596 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002597 // FIXME: When selecting an implicit conversion for an overloaded
2598 // operator delete, we sometimes try to evaluate calls to conversion
2599 // operators without a 'this' parameter!
2600 if (Args.empty())
2601 return Error(E);
2602
Richard Smith59efe262011-11-11 04:05:33 +00002603 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2604 return false;
2605 This = &ThisVal;
2606 Args = Args.slice(1);
2607 }
2608
2609 // Don't call function pointers which have been cast to some other type.
2610 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002611 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002612 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002613 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002614
Richard Smithb04035a2012-02-01 02:39:43 +00002615 if (This && !This->checkSubobject(Info, E, CSK_This))
2616 return false;
2617
Richard Smith86c3ae42012-02-13 03:54:03 +00002618 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2619 // calls to such functions in constant expressions.
2620 if (This && !HasQualifier &&
2621 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2622 return Error(E, diag::note_constexpr_virtual_call);
2623
Richard Smithc1c5f272011-12-13 06:39:58 +00002624 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002625 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002626 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002627
Richard Smithc1c5f272011-12-13 06:39:58 +00002628 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002629 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2630 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002631 return false;
2632
Richard Smith83587db2012-02-15 02:18:13 +00002633 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002634 }
2635
Richard Smithc49bd112011-10-28 17:51:58 +00002636 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2637 return StmtVisitorTy::Visit(E->getInitializer());
2638 }
Richard Smithf10d9172011-10-11 21:43:33 +00002639 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002640 if (E->getNumInits() == 0)
2641 return DerivedZeroInitialization(E);
2642 if (E->getNumInits() == 1)
2643 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002644 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002645 }
2646 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002647 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002648 }
2649 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002650 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002651 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002652 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002653 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002654 }
Richard Smithf10d9172011-10-11 21:43:33 +00002655
Richard Smith180f4792011-11-10 06:34:14 +00002656 /// A member expression where the object is a prvalue is itself a prvalue.
2657 RetTy VisitMemberExpr(const MemberExpr *E) {
2658 assert(!E->isArrow() && "missing call to bound member function?");
2659
Richard Smith1aa0be82012-03-03 22:46:17 +00002660 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002661 if (!Evaluate(Val, Info, E->getBase()))
2662 return false;
2663
2664 QualType BaseTy = E->getBase()->getType();
2665
2666 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002667 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002668 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2669 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2670 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2671
Richard Smithb4e85ed2012-01-06 16:39:00 +00002672 SubobjectDesignator Designator(BaseTy);
2673 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002674
Richard Smithf48fdb02011-12-09 22:58:01 +00002675 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002676 DerivedSuccess(Val, E);
2677 }
2678
Richard Smithc49bd112011-10-28 17:51:58 +00002679 RetTy VisitCastExpr(const CastExpr *E) {
2680 switch (E->getCastKind()) {
2681 default:
2682 break;
2683
David Chisnall7a7ee302012-01-16 17:27:18 +00002684 case CK_AtomicToNonAtomic:
2685 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002686 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002687 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002688 return StmtVisitorTy::Visit(E->getSubExpr());
2689
2690 case CK_LValueToRValue: {
2691 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002692 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2693 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002694 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002695 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2696 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2697 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002698 return false;
2699 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002700 }
2701 }
2702
Richard Smithf48fdb02011-12-09 22:58:01 +00002703 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002704 }
2705
Richard Smith8327fad2011-10-24 18:44:57 +00002706 /// Visit a value which is evaluated, but whose value is ignored.
2707 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002708 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002709 if (!Evaluate(Scratch, Info, E))
2710 Info.EvalStatus.HasSideEffects = true;
2711 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002712};
2713
2714}
2715
2716//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002717// Common base class for lvalue and temporary evaluation.
2718//===----------------------------------------------------------------------===//
2719namespace {
2720template<class Derived>
2721class LValueExprEvaluatorBase
2722 : public ExprEvaluatorBase<Derived, bool> {
2723protected:
2724 LValue &Result;
2725 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2726 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2727
2728 bool Success(APValue::LValueBase B) {
2729 Result.set(B);
2730 return true;
2731 }
2732
2733public:
2734 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2735 ExprEvaluatorBaseTy(Info), Result(Result) {}
2736
Richard Smith1aa0be82012-03-03 22:46:17 +00002737 bool Success(const APValue &V, const Expr *E) {
2738 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002739 return true;
2740 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002741
Richard Smithe24f5fc2011-11-17 22:56:20 +00002742 bool VisitMemberExpr(const MemberExpr *E) {
2743 // Handle non-static data members.
2744 QualType BaseTy;
2745 if (E->isArrow()) {
2746 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2747 return false;
2748 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002749 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002750 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002751 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2752 return false;
2753 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002754 } else {
2755 if (!this->Visit(E->getBase()))
2756 return false;
2757 BaseTy = E->getBase()->getType();
2758 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002759
Richard Smithd9b02e72012-01-25 22:15:11 +00002760 const ValueDecl *MD = E->getMemberDecl();
2761 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2762 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2763 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2764 (void)BaseTy;
John McCall8d59dee2012-05-01 00:38:49 +00002765 if (!HandleLValueMember(this->Info, E, Result, FD))
2766 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002767 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCall8d59dee2012-05-01 00:38:49 +00002768 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2769 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002770 } else
2771 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002772
Richard Smithd9b02e72012-01-25 22:15:11 +00002773 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002774 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002775 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002776 RefValue))
2777 return false;
2778 return Success(RefValue, E);
2779 }
2780 return true;
2781 }
2782
2783 bool VisitBinaryOperator(const BinaryOperator *E) {
2784 switch (E->getOpcode()) {
2785 default:
2786 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2787
2788 case BO_PtrMemD:
2789 case BO_PtrMemI:
2790 return HandleMemberPointerAccess(this->Info, E, Result);
2791 }
2792 }
2793
2794 bool VisitCastExpr(const CastExpr *E) {
2795 switch (E->getCastKind()) {
2796 default:
2797 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2798
2799 case CK_DerivedToBase:
2800 case CK_UncheckedDerivedToBase: {
2801 if (!this->Visit(E->getSubExpr()))
2802 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002803
2804 // Now figure out the necessary offset to add to the base LV to get from
2805 // the derived class to the base class.
2806 QualType Type = E->getSubExpr()->getType();
2807
2808 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2809 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002810 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002811 *PathI))
2812 return false;
2813 Type = (*PathI)->getType();
2814 }
2815
2816 return true;
2817 }
2818 }
2819 }
2820};
2821}
2822
2823//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002824// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002825//
2826// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2827// function designators (in C), decl references to void objects (in C), and
2828// temporaries (if building with -Wno-address-of-temporary).
2829//
2830// LValue evaluation produces values comprising a base expression of one of the
2831// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002832// - Declarations
2833// * VarDecl
2834// * FunctionDecl
2835// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002836// * CompoundLiteralExpr in C
2837// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002838// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002839// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002840// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002841// * ObjCEncodeExpr
2842// * AddrLabelExpr
2843// * BlockExpr
2844// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002845// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002846// * Any Expr, with a CallIndex indicating the function in which the temporary
2847// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002848// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002849//===----------------------------------------------------------------------===//
2850namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002851class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002852 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002853public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002854 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2855 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002856
Richard Smithc49bd112011-10-28 17:51:58 +00002857 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2858
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002859 bool VisitDeclRefExpr(const DeclRefExpr *E);
2860 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002861 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002862 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2863 bool VisitMemberExpr(const MemberExpr *E);
2864 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2865 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002866 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichete275a182012-04-16 04:08:35 +00002867 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002868 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2869 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002870 bool VisitUnaryReal(const UnaryOperator *E);
2871 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002872
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002873 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002874 switch (E->getCastKind()) {
2875 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002876 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002877
Eli Friedmandb924222011-10-11 00:13:24 +00002878 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002879 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002880 if (!Visit(E->getSubExpr()))
2881 return false;
2882 Result.Designator.setInvalid();
2883 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002884
Richard Smithe24f5fc2011-11-17 22:56:20 +00002885 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002886 if (!Visit(E->getSubExpr()))
2887 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002888 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002889 }
2890 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002891};
2892} // end anonymous namespace
2893
Richard Smithc49bd112011-10-28 17:51:58 +00002894/// Evaluate an expression as an lvalue. This can be legitimately called on
2895/// expressions which are not glvalues, in a few cases:
2896/// * function designators in C,
2897/// * "extern void" objects,
2898/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002899static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002900 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2901 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2902 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002903 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002904}
2905
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002906bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002907 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2908 return Success(FD);
2909 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002910 return VisitVarDecl(E, VD);
2911 return Error(E);
2912}
Richard Smith436c8892011-10-24 23:14:33 +00002913
Richard Smithc49bd112011-10-28 17:51:58 +00002914bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002915 if (!VD->getType()->isReferenceType()) {
2916 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002917 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002918 return true;
2919 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002920 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002921 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002922
Richard Smith1aa0be82012-03-03 22:46:17 +00002923 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002924 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2925 return false;
2926 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002927}
2928
Richard Smithbd552ef2011-10-31 05:52:43 +00002929bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2930 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002931 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002932 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002933 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2934
Richard Smith83587db2012-02-15 02:18:13 +00002935 Result.set(E, Info.CurrentCall->Index);
2936 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2937 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002938 }
2939
2940 // Materialization of an lvalue temporary occurs when we need to force a copy
2941 // (for instance, if it's a bitfield).
2942 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2943 if (!Visit(E->GetTemporaryExpr()))
2944 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002945 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002946 Info.CurrentCall->Temporaries[E]))
2947 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002948 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002949 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002950}
2951
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002952bool
2953LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002954 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2955 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2956 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002957 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002958}
2959
Richard Smith47d21452011-12-27 12:18:28 +00002960bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2961 if (E->isTypeOperand())
2962 return Success(E);
2963 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2964 if (RD && RD->isPolymorphic()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002965 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith47d21452011-12-27 12:18:28 +00002966 << E->getExprOperand()->getType()
2967 << E->getExprOperand()->getSourceRange();
2968 return false;
2969 }
2970 return Success(E);
2971}
2972
Francois Pichete275a182012-04-16 04:08:35 +00002973bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2974 return Success(E);
2975}
2976
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002977bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002978 // Handle static data members.
2979 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2980 VisitIgnoredValue(E->getBase());
2981 return VisitVarDecl(E, VD);
2982 }
2983
Richard Smithd0dccea2011-10-28 22:34:42 +00002984 // Handle static member functions.
2985 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2986 if (MD->isStatic()) {
2987 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002988 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002989 }
2990 }
2991
Richard Smith180f4792011-11-10 06:34:14 +00002992 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002993 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002994}
2995
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002996bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002997 // FIXME: Deal with vectors as array subscript bases.
2998 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002999 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003000
Anders Carlsson3068d112008-11-16 19:01:22 +00003001 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003002 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003003
Anders Carlsson3068d112008-11-16 19:01:22 +00003004 APSInt Index;
3005 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003006 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003007 int64_t IndexValue
3008 = Index.isSigned() ? Index.getSExtValue()
3009 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003010
Richard Smithb4e85ed2012-01-06 16:39:00 +00003011 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003012}
Eli Friedman4efaa272008-11-12 09:44:48 +00003013
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003014bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003015 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003016}
3017
Richard Smith86024012012-02-18 22:04:06 +00003018bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3019 if (!Visit(E->getSubExpr()))
3020 return false;
3021 // __real is a no-op on scalar lvalues.
3022 if (E->getSubExpr()->getType()->isAnyComplexType())
3023 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3024 return true;
3025}
3026
3027bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3028 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3029 "lvalue __imag__ on scalar?");
3030 if (!Visit(E->getSubExpr()))
3031 return false;
3032 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3033 return true;
3034}
3035
Eli Friedman4efaa272008-11-12 09:44:48 +00003036//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003037// Pointer Evaluation
3038//===----------------------------------------------------------------------===//
3039
Anders Carlssonc754aa62008-07-08 05:13:58 +00003040namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003041class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003042 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003043 LValue &Result;
3044
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003045 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003046 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003047 return true;
3048 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003049public:
Mike Stump1eb44332009-09-09 15:08:12 +00003050
John McCallefdb83e2010-05-07 21:00:08 +00003051 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003052 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003053
Richard Smith1aa0be82012-03-03 22:46:17 +00003054 bool Success(const APValue &V, const Expr *E) {
3055 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003056 return true;
3057 }
Richard Smith51201882011-12-30 21:15:51 +00003058 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003059 return Success((Expr*)0);
3060 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003061
John McCallefdb83e2010-05-07 21:00:08 +00003062 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003063 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003064 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003065 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003066 { return Success(E); }
Patrick Beardeb382ec2012-04-19 00:25:12 +00003067 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003068 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003069 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003070 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003071 bool VisitCallExpr(const CallExpr *E);
3072 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003073 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003074 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003075 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003076 }
Richard Smith180f4792011-11-10 06:34:14 +00003077 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3078 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003079 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003080 Result = *Info.CurrentCall->This;
3081 return true;
3082 }
John McCall56ca35d2011-02-17 10:25:35 +00003083
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003084 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003085};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003086} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003087
John McCallefdb83e2010-05-07 21:00:08 +00003088static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003089 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003090 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003091}
3092
John McCallefdb83e2010-05-07 21:00:08 +00003093bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003094 if (E->getOpcode() != BO_Add &&
3095 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003096 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003097
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003098 const Expr *PExp = E->getLHS();
3099 const Expr *IExp = E->getRHS();
3100 if (IExp->getType()->isPointerType())
3101 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003102
Richard Smith745f5142012-01-27 01:14:48 +00003103 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3104 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003105 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003106
John McCallefdb83e2010-05-07 21:00:08 +00003107 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003108 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003109 return false;
3110 int64_t AdditionalOffset
3111 = Offset.isSigned() ? Offset.getSExtValue()
3112 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003113 if (E->getOpcode() == BO_Sub)
3114 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003115
Richard Smith180f4792011-11-10 06:34:14 +00003116 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003117 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3118 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003119}
Eli Friedman4efaa272008-11-12 09:44:48 +00003120
John McCallefdb83e2010-05-07 21:00:08 +00003121bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3122 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003123}
Mike Stump1eb44332009-09-09 15:08:12 +00003124
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003125bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3126 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003127
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003128 switch (E->getCastKind()) {
3129 default:
3130 break;
3131
John McCall2de56d12010-08-25 11:45:40 +00003132 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003133 case CK_CPointerToObjCPointerCast:
3134 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003135 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003136 if (!Visit(SubExpr))
3137 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003138 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3139 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3140 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003141 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003142 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003143 if (SubExpr->getType()->isVoidPointerType())
3144 CCEDiag(E, diag::note_constexpr_invalid_cast)
3145 << 3 << SubExpr->getType();
3146 else
3147 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3148 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003149 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003150
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003151 case CK_DerivedToBase:
3152 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003153 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003154 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003155 if (!Result.Base && Result.Offset.isZero())
3156 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003157
Richard Smith180f4792011-11-10 06:34:14 +00003158 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003159 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003160 QualType Type =
3161 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003162
Richard Smith180f4792011-11-10 06:34:14 +00003163 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003164 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003165 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3166 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003167 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003168 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003169 }
3170
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003171 return true;
3172 }
3173
Richard Smithe24f5fc2011-11-17 22:56:20 +00003174 case CK_BaseToDerived:
3175 if (!Visit(E->getSubExpr()))
3176 return false;
3177 if (!Result.Base && Result.Offset.isZero())
3178 return true;
3179 return HandleBaseToDerivedCast(Info, E, Result);
3180
Richard Smith47a1eed2011-10-29 20:57:55 +00003181 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003182 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003183 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003184
John McCall2de56d12010-08-25 11:45:40 +00003185 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003186 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3187
Richard Smith1aa0be82012-03-03 22:46:17 +00003188 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003189 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003190 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003191
John McCallefdb83e2010-05-07 21:00:08 +00003192 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003193 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3194 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003195 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003196 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003197 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003198 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003199 return true;
3200 } else {
3201 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003202 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003203 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003204 }
3205 }
John McCall2de56d12010-08-25 11:45:40 +00003206 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003207 if (SubExpr->isGLValue()) {
3208 if (!EvaluateLValue(SubExpr, Result, Info))
3209 return false;
3210 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003211 Result.set(SubExpr, Info.CurrentCall->Index);
3212 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3213 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003214 return false;
3215 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003216 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003217 if (const ConstantArrayType *CAT
3218 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3219 Result.addArray(Info, E, CAT);
3220 else
3221 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003222 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003223
John McCall2de56d12010-08-25 11:45:40 +00003224 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003225 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003226 }
3227
Richard Smithc49bd112011-10-28 17:51:58 +00003228 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003229}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003230
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003231bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003232 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003233 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003234
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003235 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003236}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003237
3238//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003239// Member Pointer Evaluation
3240//===----------------------------------------------------------------------===//
3241
3242namespace {
3243class MemberPointerExprEvaluator
3244 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3245 MemberPtr &Result;
3246
3247 bool Success(const ValueDecl *D) {
3248 Result = MemberPtr(D);
3249 return true;
3250 }
3251public:
3252
3253 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3254 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3255
Richard Smith1aa0be82012-03-03 22:46:17 +00003256 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003257 Result.setFrom(V);
3258 return true;
3259 }
Richard Smith51201882011-12-30 21:15:51 +00003260 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003261 return Success((const ValueDecl*)0);
3262 }
3263
3264 bool VisitCastExpr(const CastExpr *E);
3265 bool VisitUnaryAddrOf(const UnaryOperator *E);
3266};
3267} // end anonymous namespace
3268
3269static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3270 EvalInfo &Info) {
3271 assert(E->isRValue() && E->getType()->isMemberPointerType());
3272 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3273}
3274
3275bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3276 switch (E->getCastKind()) {
3277 default:
3278 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3279
3280 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003281 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003282 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003283
3284 case CK_BaseToDerivedMemberPointer: {
3285 if (!Visit(E->getSubExpr()))
3286 return false;
3287 if (E->path_empty())
3288 return true;
3289 // Base-to-derived member pointer casts store the path in derived-to-base
3290 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3291 // the wrong end of the derived->base arc, so stagger the path by one class.
3292 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3293 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3294 PathI != PathE; ++PathI) {
3295 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3296 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3297 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003298 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003299 }
3300 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3301 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003302 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003303 return true;
3304 }
3305
3306 case CK_DerivedToBaseMemberPointer:
3307 if (!Visit(E->getSubExpr()))
3308 return false;
3309 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3310 PathE = E->path_end(); PathI != PathE; ++PathI) {
3311 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3312 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3313 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003314 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003315 }
3316 return true;
3317 }
3318}
3319
3320bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3321 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3322 // member can be formed.
3323 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3324}
3325
3326//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003327// Record Evaluation
3328//===----------------------------------------------------------------------===//
3329
3330namespace {
3331 class RecordExprEvaluator
3332 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3333 const LValue &This;
3334 APValue &Result;
3335 public:
3336
3337 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3338 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3339
Richard Smith1aa0be82012-03-03 22:46:17 +00003340 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003341 Result = V;
3342 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003343 }
Richard Smith51201882011-12-30 21:15:51 +00003344 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003345
Richard Smith59efe262011-11-11 04:05:33 +00003346 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003347 bool VisitInitListExpr(const InitListExpr *E);
3348 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3349 };
3350}
3351
Richard Smith51201882011-12-30 21:15:51 +00003352/// Perform zero-initialization on an object of non-union class type.
3353/// C++11 [dcl.init]p5:
3354/// To zero-initialize an object or reference of type T means:
3355/// [...]
3356/// -- if T is a (possibly cv-qualified) non-union class type,
3357/// each non-static data member and each base-class subobject is
3358/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003359static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3360 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003361 const LValue &This, APValue &Result) {
3362 assert(!RD->isUnion() && "Expected non-union class type");
3363 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3364 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3365 std::distance(RD->field_begin(), RD->field_end()));
3366
John McCall8d59dee2012-05-01 00:38:49 +00003367 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003368 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3369
3370 if (CD) {
3371 unsigned Index = 0;
3372 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003373 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003374 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3375 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003376 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3377 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003378 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003379 Result.getStructBase(Index)))
3380 return false;
3381 }
3382 }
3383
Richard Smithb4e85ed2012-01-06 16:39:00 +00003384 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3385 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003386 // -- if T is a reference type, no initialization is performed.
David Blaikie262bc182012-04-30 02:36:29 +00003387 if (I->getType()->isReferenceType())
Richard Smith51201882011-12-30 21:15:51 +00003388 continue;
3389
3390 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003391 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003392 return false;
Richard Smith51201882011-12-30 21:15:51 +00003393
David Blaikie262bc182012-04-30 02:36:29 +00003394 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003395 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003396 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003397 return false;
3398 }
3399
3400 return true;
3401}
3402
3403bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3404 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003405 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003406 if (RD->isUnion()) {
3407 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3408 // object's first non-static named data member is zero-initialized
3409 RecordDecl::field_iterator I = RD->field_begin();
3410 if (I == RD->field_end()) {
3411 Result = APValue((const FieldDecl*)0);
3412 return true;
3413 }
3414
3415 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003416 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCall8d59dee2012-05-01 00:38:49 +00003417 return false;
David Blaikie581deb32012-06-06 20:45:41 +00003418 Result = APValue(*I);
David Blaikie262bc182012-04-30 02:36:29 +00003419 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003420 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003421 }
3422
Richard Smithce582fe2012-02-17 00:44:16 +00003423 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003424 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003425 return false;
3426 }
3427
Richard Smithb4e85ed2012-01-06 16:39:00 +00003428 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003429}
3430
Richard Smith59efe262011-11-11 04:05:33 +00003431bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3432 switch (E->getCastKind()) {
3433 default:
3434 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3435
3436 case CK_ConstructorConversion:
3437 return Visit(E->getSubExpr());
3438
3439 case CK_DerivedToBase:
3440 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003441 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003442 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003443 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003444 if (!DerivedObject.isStruct())
3445 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003446
3447 // Derived-to-base rvalue conversion: just slice off the derived part.
3448 APValue *Value = &DerivedObject;
3449 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3450 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3451 PathE = E->path_end(); PathI != PathE; ++PathI) {
3452 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3453 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3454 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3455 RD = Base;
3456 }
3457 Result = *Value;
3458 return true;
3459 }
3460 }
3461}
3462
Richard Smith180f4792011-11-10 06:34:14 +00003463bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003464 // Cannot constant-evaluate std::initializer_list inits.
3465 if (E->initializesStdInitializerList())
3466 return false;
3467
Richard Smith180f4792011-11-10 06:34:14 +00003468 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003469 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00003470 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3471
3472 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003473 const FieldDecl *Field = E->getInitializedFieldInUnion();
3474 Result = APValue(Field);
3475 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003476 return true;
Richard Smithec789162012-01-12 18:54:33 +00003477
3478 // If the initializer list for a union does not contain any elements, the
3479 // first element of the union is value-initialized.
3480 ImplicitValueInitExpr VIE(Field->getType());
3481 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3482
Richard Smith180f4792011-11-10 06:34:14 +00003483 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003484 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3485 return false;
Richard Smith83587db2012-02-15 02:18:13 +00003486 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003487 }
3488
3489 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3490 "initializer list for class with base classes");
3491 Result = APValue(APValue::UninitStruct(), 0,
3492 std::distance(RD->field_begin(), RD->field_end()));
3493 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003494 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003495 for (RecordDecl::field_iterator Field = RD->field_begin(),
3496 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3497 // Anonymous bit-fields are not considered members of the class for
3498 // purposes of aggregate initialization.
3499 if (Field->isUnnamedBitfield())
3500 continue;
3501
3502 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003503
Richard Smith745f5142012-01-27 01:14:48 +00003504 bool HaveInit = ElementNo < E->getNumInits();
3505
3506 // FIXME: Diagnostics here should point to the end of the initializer
3507 // list, not the start.
John McCall8d59dee2012-05-01 00:38:49 +00003508 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie581deb32012-06-06 20:45:41 +00003509 Subobject, *Field, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003510 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003511
3512 // Perform an implicit value-initialization for members beyond the end of
3513 // the initializer list.
3514 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3515
Richard Smith83587db2012-02-15 02:18:13 +00003516 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003517 Result.getStructField(Field->getFieldIndex()),
Richard Smith745f5142012-01-27 01:14:48 +00003518 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3519 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003520 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003521 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003522 }
3523 }
3524
Richard Smith745f5142012-01-27 01:14:48 +00003525 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003526}
3527
3528bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3529 const CXXConstructorDecl *FD = E->getConstructor();
John McCall1de9d7d2012-04-26 18:10:01 +00003530 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3531
Richard Smith51201882011-12-30 21:15:51 +00003532 bool ZeroInit = E->requiresZeroInitialization();
3533 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003534 // If we've already performed zero-initialization, we're already done.
3535 if (!Result.isUninit())
3536 return true;
3537
Richard Smith51201882011-12-30 21:15:51 +00003538 if (ZeroInit)
3539 return ZeroInitialization(E);
3540
Richard Smith61802452011-12-22 02:22:31 +00003541 const CXXRecordDecl *RD = FD->getParent();
3542 if (RD->isUnion())
3543 Result = APValue((FieldDecl*)0);
3544 else
3545 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3546 std::distance(RD->field_begin(), RD->field_end()));
3547 return true;
3548 }
3549
Richard Smith180f4792011-11-10 06:34:14 +00003550 const FunctionDecl *Definition = 0;
3551 FD->getBody(Definition);
3552
Richard Smithc1c5f272011-12-13 06:39:58 +00003553 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3554 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003555
Richard Smith610a60c2012-01-10 04:32:03 +00003556 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003557 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003558 if (const MaterializeTemporaryExpr *ME
3559 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3560 return Visit(ME->GetTemporaryExpr());
3561
Richard Smith51201882011-12-30 21:15:51 +00003562 if (ZeroInit && !ZeroInitialization(E))
3563 return false;
3564
Richard Smith180f4792011-11-10 06:34:14 +00003565 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003566 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003567 cast<CXXConstructorDecl>(Definition), Info,
3568 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003569}
3570
3571static bool EvaluateRecord(const Expr *E, const LValue &This,
3572 APValue &Result, EvalInfo &Info) {
3573 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003574 "can't evaluate expression as a record rvalue");
3575 return RecordExprEvaluator(Info, This, Result).Visit(E);
3576}
3577
3578//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003579// Temporary Evaluation
3580//
3581// Temporaries are represented in the AST as rvalues, but generally behave like
3582// lvalues. The full-object of which the temporary is a subobject is implicitly
3583// materialized so that a reference can bind to it.
3584//===----------------------------------------------------------------------===//
3585namespace {
3586class TemporaryExprEvaluator
3587 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3588public:
3589 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3590 LValueExprEvaluatorBaseTy(Info, Result) {}
3591
3592 /// Visit an expression which constructs the value of this temporary.
3593 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003594 Result.set(E, Info.CurrentCall->Index);
3595 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003596 }
3597
3598 bool VisitCastExpr(const CastExpr *E) {
3599 switch (E->getCastKind()) {
3600 default:
3601 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3602
3603 case CK_ConstructorConversion:
3604 return VisitConstructExpr(E->getSubExpr());
3605 }
3606 }
3607 bool VisitInitListExpr(const InitListExpr *E) {
3608 return VisitConstructExpr(E);
3609 }
3610 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3611 return VisitConstructExpr(E);
3612 }
3613 bool VisitCallExpr(const CallExpr *E) {
3614 return VisitConstructExpr(E);
3615 }
3616};
3617} // end anonymous namespace
3618
3619/// Evaluate an expression of record type as a temporary.
3620static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003621 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003622 return TemporaryExprEvaluator(Info, Result).Visit(E);
3623}
3624
3625//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003626// Vector Evaluation
3627//===----------------------------------------------------------------------===//
3628
3629namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003630 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003631 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3632 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003633 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003634
Richard Smith07fc6572011-10-22 21:10:00 +00003635 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3636 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003637
Richard Smith07fc6572011-10-22 21:10:00 +00003638 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3639 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3640 // FIXME: remove this APValue copy.
3641 Result = APValue(V.data(), V.size());
3642 return true;
3643 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003644 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003645 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003646 Result = V;
3647 return true;
3648 }
Richard Smith51201882011-12-30 21:15:51 +00003649 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003650
Richard Smith07fc6572011-10-22 21:10:00 +00003651 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003652 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003653 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003654 bool VisitInitListExpr(const InitListExpr *E);
3655 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003656 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003657 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003658 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003659 };
3660} // end anonymous namespace
3661
3662static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003663 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003664 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003665}
3666
Richard Smith07fc6572011-10-22 21:10:00 +00003667bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3668 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003669 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003670
Richard Smithd62ca372011-12-06 22:44:34 +00003671 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003672 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003673
Eli Friedman46a52322011-03-25 00:43:55 +00003674 switch (E->getCastKind()) {
3675 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003676 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003677 if (SETy->isIntegerType()) {
3678 APSInt IntResult;
3679 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003680 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003681 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003682 } else if (SETy->isRealFloatingType()) {
3683 APFloat F(0.0);
3684 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003685 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003686 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003687 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003688 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003689 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003690
3691 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003692 SmallVector<APValue, 4> Elts(NElts, Val);
3693 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003694 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003695 case CK_BitCast: {
3696 // Evaluate the operand into an APInt we can extract from.
3697 llvm::APInt SValInt;
3698 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3699 return false;
3700 // Extract the elements
3701 QualType EltTy = VTy->getElementType();
3702 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3703 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3704 SmallVector<APValue, 4> Elts;
3705 if (EltTy->isRealFloatingType()) {
3706 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3707 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3708 unsigned FloatEltSize = EltSize;
3709 if (&Sem == &APFloat::x87DoubleExtended)
3710 FloatEltSize = 80;
3711 for (unsigned i = 0; i < NElts; i++) {
3712 llvm::APInt Elt;
3713 if (BigEndian)
3714 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3715 else
3716 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3717 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3718 }
3719 } else if (EltTy->isIntegerType()) {
3720 for (unsigned i = 0; i < NElts; i++) {
3721 llvm::APInt Elt;
3722 if (BigEndian)
3723 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3724 else
3725 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3726 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3727 }
3728 } else {
3729 return Error(E);
3730 }
3731 return Success(Elts, E);
3732 }
Eli Friedman46a52322011-03-25 00:43:55 +00003733 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003734 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003735 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003736}
3737
Richard Smith07fc6572011-10-22 21:10:00 +00003738bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003739VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003740 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003741 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003742 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003743
Nate Begeman59b5da62009-01-18 03:20:47 +00003744 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003745 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003746
Eli Friedman3edd5a92012-01-03 23:24:20 +00003747 // The number of initializers can be less than the number of
3748 // vector elements. For OpenCL, this can be due to nested vector
3749 // initialization. For GCC compatibility, missing trailing elements
3750 // should be initialized with zeroes.
3751 unsigned CountInits = 0, CountElts = 0;
3752 while (CountElts < NumElements) {
3753 // Handle nested vector initialization.
3754 if (CountInits < NumInits
3755 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3756 APValue v;
3757 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3758 return Error(E);
3759 unsigned vlen = v.getVectorLength();
3760 for (unsigned j = 0; j < vlen; j++)
3761 Elements.push_back(v.getVectorElt(j));
3762 CountElts += vlen;
3763 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003764 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003765 if (CountInits < NumInits) {
3766 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003767 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003768 } else // trailing integer zero.
3769 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3770 Elements.push_back(APValue(sInt));
3771 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003772 } else {
3773 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003774 if (CountInits < NumInits) {
3775 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003776 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003777 } else // trailing float zero.
3778 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3779 Elements.push_back(APValue(f));
3780 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003781 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003782 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003783 }
Richard Smith07fc6572011-10-22 21:10:00 +00003784 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003785}
3786
Richard Smith07fc6572011-10-22 21:10:00 +00003787bool
Richard Smith51201882011-12-30 21:15:51 +00003788VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003789 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003790 QualType EltTy = VT->getElementType();
3791 APValue ZeroElement;
3792 if (EltTy->isIntegerType())
3793 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3794 else
3795 ZeroElement =
3796 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3797
Chris Lattner5f9e2722011-07-23 10:55:15 +00003798 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003799 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003800}
3801
Richard Smith07fc6572011-10-22 21:10:00 +00003802bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003803 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003804 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003805}
3806
Nate Begeman59b5da62009-01-18 03:20:47 +00003807//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003808// Array Evaluation
3809//===----------------------------------------------------------------------===//
3810
3811namespace {
3812 class ArrayExprEvaluator
3813 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003814 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003815 APValue &Result;
3816 public:
3817
Richard Smith180f4792011-11-10 06:34:14 +00003818 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3819 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003820
3821 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003822 assert((V.isArray() || V.isLValue()) &&
3823 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003824 Result = V;
3825 return true;
3826 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003827
Richard Smith51201882011-12-30 21:15:51 +00003828 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003829 const ConstantArrayType *CAT =
3830 Info.Ctx.getAsConstantArrayType(E->getType());
3831 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003832 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003833
3834 Result = APValue(APValue::UninitArray(), 0,
3835 CAT->getSize().getZExtValue());
3836 if (!Result.hasArrayFiller()) return true;
3837
Richard Smith51201882011-12-30 21:15:51 +00003838 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003839 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003840 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003841 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003842 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003843 }
3844
Richard Smithcc5d4f62011-11-07 09:22:26 +00003845 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003846 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003847 };
3848} // end anonymous namespace
3849
Richard Smith180f4792011-11-10 06:34:14 +00003850static bool EvaluateArray(const Expr *E, const LValue &This,
3851 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003852 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003853 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003854}
3855
3856bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3857 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3858 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003859 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003860
Richard Smith974c5f92011-12-22 01:07:19 +00003861 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3862 // an appropriately-typed string literal enclosed in braces.
Richard Smithfe587202012-04-15 02:50:59 +00003863 if (E->isStringLiteralInit()) {
Richard Smith974c5f92011-12-22 01:07:19 +00003864 LValue LV;
3865 if (!EvaluateLValue(E->getInit(0), LV, Info))
3866 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003867 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003868 LV.moveInto(Val);
3869 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003870 }
3871
Richard Smith745f5142012-01-27 01:14:48 +00003872 bool Success = true;
3873
Richard Smithcc5d4f62011-11-07 09:22:26 +00003874 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3875 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003876 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003877 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003878 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003879 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003880 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003881 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3882 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003883 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3884 CAT->getElementType(), 1)) {
3885 if (!Info.keepEvaluatingAfterFailure())
3886 return false;
3887 Success = false;
3888 }
Richard Smith180f4792011-11-10 06:34:14 +00003889 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003890
Richard Smith745f5142012-01-27 01:14:48 +00003891 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003892 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003893 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3894 // but sometimes does:
3895 // struct S { constexpr S() : p(&p) {} void *p; };
3896 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003897 return EvaluateInPlace(Result.getArrayFiller(), Info,
3898 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003899}
3900
Richard Smithe24f5fc2011-11-17 22:56:20 +00003901bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3902 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3903 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003904 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003905
Richard Smithec789162012-01-12 18:54:33 +00003906 bool HadZeroInit = !Result.isUninit();
3907 if (!HadZeroInit)
3908 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003909 if (!Result.hasArrayFiller())
3910 return true;
3911
3912 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003913
Richard Smith51201882011-12-30 21:15:51 +00003914 bool ZeroInit = E->requiresZeroInitialization();
3915 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003916 if (HadZeroInit)
3917 return true;
3918
Richard Smith51201882011-12-30 21:15:51 +00003919 if (ZeroInit) {
3920 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003921 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003922 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003923 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003924 }
3925
Richard Smith61802452011-12-22 02:22:31 +00003926 const CXXRecordDecl *RD = FD->getParent();
3927 if (RD->isUnion())
3928 Result.getArrayFiller() = APValue((FieldDecl*)0);
3929 else
3930 Result.getArrayFiller() =
3931 APValue(APValue::UninitStruct(), RD->getNumBases(),
3932 std::distance(RD->field_begin(), RD->field_end()));
3933 return true;
3934 }
3935
Richard Smithe24f5fc2011-11-17 22:56:20 +00003936 const FunctionDecl *Definition = 0;
3937 FD->getBody(Definition);
3938
Richard Smithc1c5f272011-12-13 06:39:58 +00003939 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3940 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003941
3942 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3943 // but sometimes does:
3944 // struct S { constexpr S() : p(&p) {} void *p; };
3945 // S s[10];
3946 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003947 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003948
Richard Smithec789162012-01-12 18:54:33 +00003949 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003950 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003951 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003952 return false;
3953 }
3954
Richard Smithe24f5fc2011-11-17 22:56:20 +00003955 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003956 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003957 cast<CXXConstructorDecl>(Definition),
3958 Info, Result.getArrayFiller());
3959}
3960
Richard Smithcc5d4f62011-11-07 09:22:26 +00003961//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003962// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003963//
3964// As a GNU extension, we support casting pointers to sufficiently-wide integer
3965// types and back in constant folding. Integer values are thus represented
3966// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003967//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003968
3969namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003970class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003971 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003972 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003973public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003974 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003975 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003976
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003977 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003978 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003979 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003980 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003981 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003982 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003983 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003984 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003985 return true;
3986 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003987 bool Success(const llvm::APSInt &SI, const Expr *E) {
3988 return Success(SI, E, Result);
3989 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003990
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003991 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003992 assert(E->getType()->isIntegralOrEnumerationType() &&
3993 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003994 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003995 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003996 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003997 Result.getInt().setIsUnsigned(
3998 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003999 return true;
4000 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004001 bool Success(const llvm::APInt &I, const Expr *E) {
4002 return Success(I, E, Result);
4003 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004004
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004005 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004006 assert(E->getType()->isIntegralOrEnumerationType() &&
4007 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004008 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00004009 return true;
4010 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004011 bool Success(uint64_t Value, const Expr *E) {
4012 return Success(Value, E, Result);
4013 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004014
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004015 bool Success(CharUnits Size, const Expr *E) {
4016 return Success(Size.getQuantity(), E);
4017 }
4018
Richard Smith1aa0be82012-03-03 22:46:17 +00004019 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00004020 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00004021 Result = V;
4022 return true;
4023 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004024 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004025 }
Mike Stump1eb44332009-09-09 15:08:12 +00004026
Richard Smith51201882011-12-30 21:15:51 +00004027 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004028
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004029 //===--------------------------------------------------------------------===//
4030 // Visitor Methods
4031 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004032
Chris Lattner4c4867e2008-07-12 00:38:25 +00004033 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004034 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004035 }
4036 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004037 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004038 }
Eli Friedman04309752009-11-24 05:28:59 +00004039
4040 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4041 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004042 if (CheckReferencedDecl(E, E->getDecl()))
4043 return true;
4044
4045 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004046 }
4047 bool VisitMemberExpr(const MemberExpr *E) {
4048 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004049 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004050 return true;
4051 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004052
4053 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004054 }
4055
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004056 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004057 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004058 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004059 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004060
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004061 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004062 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004063
Anders Carlsson3068d112008-11-16 19:01:22 +00004064 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004065 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004066 }
Mike Stump1eb44332009-09-09 15:08:12 +00004067
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004068 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4069 return Success(E->getValue(), E);
4070 }
4071
Richard Smithf10d9172011-10-11 21:43:33 +00004072 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004073 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004074 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004075 }
4076
Sebastian Redl64b45f72009-01-05 20:52:13 +00004077 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004078 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004079 }
4080
Francois Pichet6ad6f282010-12-07 00:08:36 +00004081 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4082 return Success(E->getValue(), E);
4083 }
4084
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004085 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4086 return Success(E->getValue(), E);
4087 }
4088
John Wiegley21ff2e52011-04-28 00:16:57 +00004089 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4090 return Success(E->getValue(), E);
4091 }
4092
John Wiegley55262202011-04-25 06:54:41 +00004093 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4094 return Success(E->getValue(), E);
4095 }
4096
Eli Friedman722c7172009-02-28 03:59:05 +00004097 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004098 bool VisitUnaryImag(const UnaryOperator *E);
4099
Sebastian Redl295995c2010-09-10 20:55:47 +00004100 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004101 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004102
Chris Lattnerfcee0012008-07-11 21:24:13 +00004103private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004104 CharUnits GetAlignOfExpr(const Expr *E);
4105 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004106 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004107 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004108 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004109};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004110} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004111
Richard Smithc49bd112011-10-28 17:51:58 +00004112/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4113/// produce either the integer value or a pointer.
4114///
4115/// GCC has a heinous extension which folds casts between pointer types and
4116/// pointer-sized integral types. We support this by allowing the evaluation of
4117/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4118/// Some simple arithmetic on such values is supported (they are treated much
4119/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004120static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004121 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004122 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004123 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004124}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004125
Richard Smithf48fdb02011-12-09 22:58:01 +00004126static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004127 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004128 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004129 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004130 if (!Val.isInt()) {
4131 // FIXME: It would be better to produce the diagnostic for casting
4132 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004133 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004134 return false;
4135 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004136 Result = Val.getInt();
4137 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004138}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004139
Richard Smithf48fdb02011-12-09 22:58:01 +00004140/// Check whether the given declaration can be directly converted to an integral
4141/// rvalue. If not, no diagnostic is produced; there are other things we can
4142/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004143bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004144 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004145 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004146 // Check for signedness/width mismatches between E type and ECD value.
4147 bool SameSign = (ECD->getInitVal().isSigned()
4148 == E->getType()->isSignedIntegerOrEnumerationType());
4149 bool SameWidth = (ECD->getInitVal().getBitWidth()
4150 == Info.Ctx.getIntWidth(E->getType()));
4151 if (SameSign && SameWidth)
4152 return Success(ECD->getInitVal(), E);
4153 else {
4154 // Get rid of mismatch (otherwise Success assertions will fail)
4155 // by computing a new value matching the type of E.
4156 llvm::APSInt Val = ECD->getInitVal();
4157 if (!SameSign)
4158 Val.setIsSigned(!ECD->getInitVal().isSigned());
4159 if (!SameWidth)
4160 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4161 return Success(Val, E);
4162 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004163 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004164 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004165}
4166
Chris Lattnera4d55d82008-10-06 06:40:35 +00004167/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4168/// as GCC.
4169static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4170 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004171 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004172 enum gcc_type_class {
4173 no_type_class = -1,
4174 void_type_class, integer_type_class, char_type_class,
4175 enumeral_type_class, boolean_type_class,
4176 pointer_type_class, reference_type_class, offset_type_class,
4177 real_type_class, complex_type_class,
4178 function_type_class, method_type_class,
4179 record_type_class, union_type_class,
4180 array_type_class, string_type_class,
4181 lang_type_class
4182 };
Mike Stump1eb44332009-09-09 15:08:12 +00004183
4184 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004185 // ideal, however it is what gcc does.
4186 if (E->getNumArgs() == 0)
4187 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004188
Chris Lattnera4d55d82008-10-06 06:40:35 +00004189 QualType ArgTy = E->getArg(0)->getType();
4190 if (ArgTy->isVoidType())
4191 return void_type_class;
4192 else if (ArgTy->isEnumeralType())
4193 return enumeral_type_class;
4194 else if (ArgTy->isBooleanType())
4195 return boolean_type_class;
4196 else if (ArgTy->isCharType())
4197 return string_type_class; // gcc doesn't appear to use char_type_class
4198 else if (ArgTy->isIntegerType())
4199 return integer_type_class;
4200 else if (ArgTy->isPointerType())
4201 return pointer_type_class;
4202 else if (ArgTy->isReferenceType())
4203 return reference_type_class;
4204 else if (ArgTy->isRealType())
4205 return real_type_class;
4206 else if (ArgTy->isComplexType())
4207 return complex_type_class;
4208 else if (ArgTy->isFunctionType())
4209 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004210 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004211 return record_type_class;
4212 else if (ArgTy->isUnionType())
4213 return union_type_class;
4214 else if (ArgTy->isArrayType())
4215 return array_type_class;
4216 else if (ArgTy->isUnionType())
4217 return union_type_class;
4218 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004219 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004220}
4221
Richard Smith80d4b552011-12-28 19:48:30 +00004222/// EvaluateBuiltinConstantPForLValue - Determine the result of
4223/// __builtin_constant_p when applied to the given lvalue.
4224///
4225/// An lvalue is only "constant" if it is a pointer or reference to the first
4226/// character of a string literal.
4227template<typename LValue>
4228static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004229 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004230 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4231}
4232
4233/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4234/// GCC as we can manage.
4235static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4236 QualType ArgType = Arg->getType();
4237
4238 // __builtin_constant_p always has one operand. The rules which gcc follows
4239 // are not precisely documented, but are as follows:
4240 //
4241 // - If the operand is of integral, floating, complex or enumeration type,
4242 // and can be folded to a known value of that type, it returns 1.
4243 // - If the operand and can be folded to a pointer to the first character
4244 // of a string literal (or such a pointer cast to an integral type), it
4245 // returns 1.
4246 //
4247 // Otherwise, it returns 0.
4248 //
4249 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4250 // its support for this does not currently work.
4251 if (ArgType->isIntegralOrEnumerationType()) {
4252 Expr::EvalResult Result;
4253 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4254 return false;
4255
4256 APValue &V = Result.Val;
4257 if (V.getKind() == APValue::Int)
4258 return true;
4259
4260 return EvaluateBuiltinConstantPForLValue(V);
4261 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4262 return Arg->isEvaluatable(Ctx);
4263 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4264 LValue LV;
4265 Expr::EvalStatus Status;
4266 EvalInfo Info(Ctx, Status);
4267 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4268 : EvaluatePointer(Arg, LV, Info)) &&
4269 !Status.HasSideEffects)
4270 return EvaluateBuiltinConstantPForLValue(LV);
4271 }
4272
4273 // Anything else isn't considered to be sufficiently constant.
4274 return false;
4275}
4276
John McCall42c8f872010-05-10 23:27:23 +00004277/// Retrieves the "underlying object type" of the given expression,
4278/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004279QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4280 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4281 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004282 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004283 } else if (const Expr *E = B.get<const Expr*>()) {
4284 if (isa<CompoundLiteralExpr>(E))
4285 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004286 }
4287
4288 return QualType();
4289}
4290
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004291bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004292 LValue Base;
Richard Smithc6794852012-05-23 04:13:20 +00004293
4294 {
4295 // The operand of __builtin_object_size is never evaluated for side-effects.
4296 // If there are any, but we can determine the pointed-to object anyway, then
4297 // ignore the side-effects.
4298 SpeculativeEvaluationRAII SpeculativeEval(Info);
4299 if (!EvaluatePointer(E->getArg(0), Base, Info))
4300 return false;
4301 }
John McCall42c8f872010-05-10 23:27:23 +00004302
4303 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004304 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004305
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004306 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004307 if (T.isNull() ||
4308 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004309 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004310 T->isVariablyModifiedType() ||
4311 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004312 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004313
4314 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4315 CharUnits Offset = Base.getLValueOffset();
4316
4317 if (!Offset.isNegative() && Offset <= Size)
4318 Size -= Offset;
4319 else
4320 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004321 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004322}
4323
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004324bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00004325 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004326 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004327 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004328
4329 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004330 if (TryEvaluateBuiltinObjectSize(E))
4331 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004332
Eric Christopherb2aaf512010-01-19 22:58:35 +00004333 // If evaluating the argument has side-effects we can't determine
Richard Smithc6794852012-05-23 04:13:20 +00004334 // the size of the object and lower it to unknown now. CodeGen relies on
4335 // us to handle all cases where the expression has side-effects.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004336 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004337 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004338 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004339 return Success(0, E);
4340 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004341
Richard Smithc6794852012-05-23 04:13:20 +00004342 // Expression had no side effects, but we couldn't statically determine the
4343 // size of the referenced object.
Richard Smithf48fdb02011-12-09 22:58:01 +00004344 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004345 }
4346
Chris Lattner019f4e82008-10-06 05:28:25 +00004347 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004348 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004349
Richard Smith80d4b552011-12-28 19:48:30 +00004350 case Builtin::BI__builtin_constant_p:
4351 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004352
Chris Lattner21fb98e2009-09-23 06:06:36 +00004353 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004354 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004355 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004356 return Success(Operand, E);
4357 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004358
4359 case Builtin::BI__builtin_expect:
4360 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004361
Douglas Gregor5726d402010-09-10 06:27:15 +00004362 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004363 // A call to strlen is not a constant expression.
4364 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004365 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004366 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4367 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004368 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004369 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004370 case Builtin::BI__builtin_strlen:
4371 // As an extension, we support strlen() and __builtin_strlen() as constant
4372 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004373 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004374 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4375 // The string literal may have embedded null characters. Find the first
4376 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004377 StringRef Str = S->getString();
4378 StringRef::size_type Pos = Str.find(0);
4379 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004380 Str = Str.substr(0, Pos);
4381
4382 return Success(Str.size(), E);
4383 }
4384
Richard Smithf48fdb02011-12-09 22:58:01 +00004385 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004386
Richard Smith2c39d712012-04-13 00:45:38 +00004387 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00004388 case Builtin::BI__atomic_is_lock_free:
4389 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00004390 APSInt SizeVal;
4391 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4392 return false;
4393
4394 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4395 // of two less than the maximum inline atomic width, we know it is
4396 // lock-free. If the size isn't a power of two, or greater than the
4397 // maximum alignment where we promote atomics, we know it is not lock-free
4398 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4399 // the answer can only be determined at runtime; for example, 16-byte
4400 // atomics have lock-free implementations on some, but not all,
4401 // x86-64 processors.
4402
4403 // Check power-of-two.
4404 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00004405 if (Size.isPowerOfTwo()) {
4406 // Check against inlining width.
4407 unsigned InlineWidthBits =
4408 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4409 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4410 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4411 Size == CharUnits::One() ||
4412 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4413 Expr::NPC_NeverValueDependent))
4414 // OK, we will inline appropriately-aligned operations of this size,
4415 // and _Atomic(T) is appropriately-aligned.
4416 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004417
Richard Smith2c39d712012-04-13 00:45:38 +00004418 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4419 castAs<PointerType>()->getPointeeType();
4420 if (!PointeeType->isIncompleteType() &&
4421 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4422 // OK, we will inline operations on this object.
4423 return Success(1, E);
4424 }
4425 }
4426 }
Eli Friedman454b57a2011-10-17 21:44:23 +00004427
Richard Smith2c39d712012-04-13 00:45:38 +00004428 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4429 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004430 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004431 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004432}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004433
Richard Smith625b8072011-10-31 01:37:14 +00004434static bool HasSameBase(const LValue &A, const LValue &B) {
4435 if (!A.getLValueBase())
4436 return !B.getLValueBase();
4437 if (!B.getLValueBase())
4438 return false;
4439
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004440 if (A.getLValueBase().getOpaqueValue() !=
4441 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004442 const Decl *ADecl = GetLValueBaseDecl(A);
4443 if (!ADecl)
4444 return false;
4445 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004446 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004447 return false;
4448 }
4449
4450 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004451 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004452}
4453
Richard Smith7b48a292012-02-01 05:53:12 +00004454/// Perform the given integer operation, which is known to need at most BitWidth
4455/// bits, and check for overflow in the original type (if that type was not an
4456/// unsigned type).
4457template<typename Operation>
4458static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4459 const APSInt &LHS, const APSInt &RHS,
4460 unsigned BitWidth, Operation Op) {
4461 if (LHS.isUnsigned())
4462 return Op(LHS, RHS);
4463
4464 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4465 APSInt Result = Value.trunc(LHS.getBitWidth());
4466 if (Result.extend(BitWidth) != Value)
4467 HandleOverflow(Info, E, Value, E->getType());
4468 return Result;
4469}
4470
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004471namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004472
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004473/// \brief Data recursive integer evaluator of certain binary operators.
4474///
4475/// We use a data recursive algorithm for binary operators so that we are able
4476/// to handle extreme cases of chained binary operators without causing stack
4477/// overflow.
4478class DataRecursiveIntBinOpEvaluator {
4479 struct EvalResult {
4480 APValue Val;
4481 bool Failed;
4482
4483 EvalResult() : Failed(false) { }
4484
4485 void swap(EvalResult &RHS) {
4486 Val.swap(RHS.Val);
4487 Failed = RHS.Failed;
4488 RHS.Failed = false;
4489 }
4490 };
4491
4492 struct Job {
4493 const Expr *E;
4494 EvalResult LHSResult; // meaningful only for binary operator expression.
4495 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4496
4497 Job() : StoredInfo(0) { }
4498 void startSpeculativeEval(EvalInfo &Info) {
4499 OldEvalStatus = Info.EvalStatus;
4500 Info.EvalStatus.Diag = 0;
4501 StoredInfo = &Info;
4502 }
4503 ~Job() {
4504 if (StoredInfo) {
4505 StoredInfo->EvalStatus = OldEvalStatus;
4506 }
4507 }
4508 private:
4509 EvalInfo *StoredInfo; // non-null if status changed.
4510 Expr::EvalStatus OldEvalStatus;
4511 };
4512
4513 SmallVector<Job, 16> Queue;
4514
4515 IntExprEvaluator &IntEval;
4516 EvalInfo &Info;
4517 APValue &FinalResult;
4518
4519public:
4520 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4521 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4522
4523 /// \brief True if \param E is a binary operator that we are going to handle
4524 /// data recursively.
4525 /// We handle binary operators that are comma, logical, or that have operands
4526 /// with integral or enumeration type.
4527 static bool shouldEnqueue(const BinaryOperator *E) {
4528 return E->getOpcode() == BO_Comma ||
4529 E->isLogicalOp() ||
4530 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4531 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004532 }
4533
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004534 bool Traverse(const BinaryOperator *E) {
4535 enqueue(E);
4536 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004537 while (!Queue.empty())
4538 process(PrevResult);
4539
4540 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004541
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004542 FinalResult.swap(PrevResult.Val);
4543 return true;
4544 }
4545
4546private:
4547 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4548 return IntEval.Success(Value, E, Result);
4549 }
4550 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4551 return IntEval.Success(Value, E, Result);
4552 }
4553 bool Error(const Expr *E) {
4554 return IntEval.Error(E);
4555 }
4556 bool Error(const Expr *E, diag::kind D) {
4557 return IntEval.Error(E, D);
4558 }
4559
4560 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4561 return Info.CCEDiag(E, D);
4562 }
4563
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004564 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4565 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004566 bool &SuppressRHSDiags);
4567
4568 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4569 const BinaryOperator *E, APValue &Result);
4570
4571 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4572 Result.Failed = !Evaluate(Result.Val, Info, E);
4573 if (Result.Failed)
4574 Result.Val = APValue();
4575 }
4576
Richard Trieub7783052012-03-21 23:30:30 +00004577 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004578
4579 void enqueue(const Expr *E) {
4580 E = E->IgnoreParens();
4581 Queue.resize(Queue.size()+1);
4582 Queue.back().E = E;
4583 Queue.back().Kind = Job::AnyExprKind;
4584 }
4585};
4586
4587}
4588
4589bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004590 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004591 bool &SuppressRHSDiags) {
4592 if (E->getOpcode() == BO_Comma) {
4593 // Ignore LHS but note if we could not evaluate it.
4594 if (LHSResult.Failed)
4595 Info.EvalStatus.HasSideEffects = true;
4596 return true;
4597 }
4598
4599 if (E->isLogicalOp()) {
4600 bool lhsResult;
4601 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004602 // We were able to evaluate the LHS, see if we can get away with not
4603 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004604 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004605 Success(lhsResult, E, LHSResult.Val);
4606 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004607 }
4608 } else {
4609 // Since we weren't able to evaluate the left hand side, it
4610 // must have had side effects.
4611 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004612
4613 // We can't evaluate the LHS; however, sometimes the result
4614 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4615 // Don't ignore RHS and suppress diagnostics from this arm.
4616 SuppressRHSDiags = true;
4617 }
4618
4619 return true;
4620 }
4621
4622 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4623 E->getRHS()->getType()->isIntegralOrEnumerationType());
4624
4625 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004626 return false; // Ignore RHS;
4627
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004628 return true;
4629}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004630
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004631bool DataRecursiveIntBinOpEvaluator::
4632 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4633 const BinaryOperator *E, APValue &Result) {
4634 if (E->getOpcode() == BO_Comma) {
4635 if (RHSResult.Failed)
4636 return false;
4637 Result = RHSResult.Val;
4638 return true;
4639 }
4640
4641 if (E->isLogicalOp()) {
4642 bool lhsResult, rhsResult;
4643 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4644 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4645
4646 if (LHSIsOK) {
4647 if (RHSIsOK) {
4648 if (E->getOpcode() == BO_LOr)
4649 return Success(lhsResult || rhsResult, E, Result);
4650 else
4651 return Success(lhsResult && rhsResult, E, Result);
4652 }
4653 } else {
4654 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004655 // We can't evaluate the LHS; however, sometimes the result
4656 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4657 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004658 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004659 }
4660 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004661
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004662 return false;
4663 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004664
4665 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4666 E->getRHS()->getType()->isIntegralOrEnumerationType());
4667
4668 if (LHSResult.Failed || RHSResult.Failed)
4669 return false;
4670
4671 const APValue &LHSVal = LHSResult.Val;
4672 const APValue &RHSVal = RHSResult.Val;
4673
4674 // Handle cases like (unsigned long)&a + 4.
4675 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4676 Result = LHSVal;
4677 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4678 RHSVal.getInt().getZExtValue());
4679 if (E->getOpcode() == BO_Add)
4680 Result.getLValueOffset() += AdditionalOffset;
4681 else
4682 Result.getLValueOffset() -= AdditionalOffset;
4683 return true;
4684 }
4685
4686 // Handle cases like 4 + (unsigned long)&a
4687 if (E->getOpcode() == BO_Add &&
4688 RHSVal.isLValue() && LHSVal.isInt()) {
4689 Result = RHSVal;
4690 Result.getLValueOffset() += CharUnits::fromQuantity(
4691 LHSVal.getInt().getZExtValue());
4692 return true;
4693 }
4694
4695 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4696 // Handle (intptr_t)&&A - (intptr_t)&&B.
4697 if (!LHSVal.getLValueOffset().isZero() ||
4698 !RHSVal.getLValueOffset().isZero())
4699 return false;
4700 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4701 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4702 if (!LHSExpr || !RHSExpr)
4703 return false;
4704 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4705 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4706 if (!LHSAddrExpr || !RHSAddrExpr)
4707 return false;
4708 // Make sure both labels come from the same function.
4709 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4710 RHSAddrExpr->getLabel()->getDeclContext())
4711 return false;
4712 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4713 return true;
4714 }
4715
4716 // All the following cases expect both operands to be an integer
4717 if (!LHSVal.isInt() || !RHSVal.isInt())
4718 return Error(E);
4719
4720 const APSInt &LHS = LHSVal.getInt();
4721 APSInt RHS = RHSVal.getInt();
4722
4723 switch (E->getOpcode()) {
4724 default:
4725 return Error(E);
4726 case BO_Mul:
4727 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4728 LHS.getBitWidth() * 2,
4729 std::multiplies<APSInt>()), E,
4730 Result);
4731 case BO_Add:
4732 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4733 LHS.getBitWidth() + 1,
4734 std::plus<APSInt>()), E, Result);
4735 case BO_Sub:
4736 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4737 LHS.getBitWidth() + 1,
4738 std::minus<APSInt>()), E, Result);
4739 case BO_And: return Success(LHS & RHS, E, Result);
4740 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4741 case BO_Or: return Success(LHS | RHS, E, Result);
4742 case BO_Div:
4743 case BO_Rem:
4744 if (RHS == 0)
4745 return Error(E, diag::note_expr_divide_by_zero);
4746 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4747 // not actually undefined behavior in C++11 due to a language defect.
4748 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4749 LHS.isSigned() && LHS.isMinSignedValue())
4750 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4751 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4752 Result);
4753 case BO_Shl: {
4754 // During constant-folding, a negative shift is an opposite shift. Such
4755 // a shift is not a constant expression.
4756 if (RHS.isSigned() && RHS.isNegative()) {
4757 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4758 RHS = -RHS;
4759 goto shift_right;
4760 }
4761
4762 shift_left:
4763 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4764 // the shifted type.
4765 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4766 if (SA != RHS) {
4767 CCEDiag(E, diag::note_constexpr_large_shift)
4768 << RHS << E->getType() << LHS.getBitWidth();
4769 } else if (LHS.isSigned()) {
4770 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4771 // operand, and must not overflow the corresponding unsigned type.
4772 if (LHS.isNegative())
4773 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4774 else if (LHS.countLeadingZeros() < SA)
4775 CCEDiag(E, diag::note_constexpr_lshift_discards);
4776 }
4777
4778 return Success(LHS << SA, E, Result);
4779 }
4780 case BO_Shr: {
4781 // During constant-folding, a negative shift is an opposite shift. Such a
4782 // shift is not a constant expression.
4783 if (RHS.isSigned() && RHS.isNegative()) {
4784 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4785 RHS = -RHS;
4786 goto shift_left;
4787 }
4788
4789 shift_right:
4790 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4791 // shifted type.
4792 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4793 if (SA != RHS)
4794 CCEDiag(E, diag::note_constexpr_large_shift)
4795 << RHS << E->getType() << LHS.getBitWidth();
4796
4797 return Success(LHS >> SA, E, Result);
4798 }
4799
4800 case BO_LT: return Success(LHS < RHS, E, Result);
4801 case BO_GT: return Success(LHS > RHS, E, Result);
4802 case BO_LE: return Success(LHS <= RHS, E, Result);
4803 case BO_GE: return Success(LHS >= RHS, E, Result);
4804 case BO_EQ: return Success(LHS == RHS, E, Result);
4805 case BO_NE: return Success(LHS != RHS, E, Result);
4806 }
4807}
4808
Richard Trieub7783052012-03-21 23:30:30 +00004809void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004810 Job &job = Queue.back();
4811
4812 switch (job.Kind) {
4813 case Job::AnyExprKind: {
4814 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4815 if (shouldEnqueue(Bop)) {
4816 job.Kind = Job::BinOpKind;
4817 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004818 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004819 }
4820 }
4821
4822 EvaluateExpr(job.E, Result);
4823 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004824 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004825 }
4826
4827 case Job::BinOpKind: {
4828 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004829 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004830 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004831 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004832 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004833 }
4834 if (SuppressRHSDiags)
4835 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004836 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004837 job.Kind = Job::BinOpVisitedLHSKind;
4838 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004839 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004840 }
4841
4842 case Job::BinOpVisitedLHSKind: {
4843 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4844 EvalResult RHS;
4845 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004846 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004847 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004848 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004849 }
4850 }
4851
4852 llvm_unreachable("Invalid Job::Kind!");
4853}
4854
4855bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4856 if (E->isAssignmentOp())
4857 return Error(E);
4858
4859 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4860 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004861
Anders Carlsson286f85e2008-11-16 07:17:21 +00004862 QualType LHSTy = E->getLHS()->getType();
4863 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004864
4865 if (LHSTy->isAnyComplexType()) {
4866 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004867 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004868
Richard Smith745f5142012-01-27 01:14:48 +00004869 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4870 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004871 return false;
4872
Richard Smith745f5142012-01-27 01:14:48 +00004873 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004874 return false;
4875
4876 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004877 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004878 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004879 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004880 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4881
John McCall2de56d12010-08-25 11:45:40 +00004882 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004883 return Success((CR_r == APFloat::cmpEqual &&
4884 CR_i == APFloat::cmpEqual), E);
4885 else {
John McCall2de56d12010-08-25 11:45:40 +00004886 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004887 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004888 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004889 CR_r == APFloat::cmpLessThan ||
4890 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004891 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004892 CR_i == APFloat::cmpLessThan ||
4893 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004894 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004895 } else {
John McCall2de56d12010-08-25 11:45:40 +00004896 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004897 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4898 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4899 else {
John McCall2de56d12010-08-25 11:45:40 +00004900 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004901 "Invalid compex comparison.");
4902 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4903 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4904 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004905 }
4906 }
Mike Stump1eb44332009-09-09 15:08:12 +00004907
Anders Carlsson286f85e2008-11-16 07:17:21 +00004908 if (LHSTy->isRealFloatingType() &&
4909 RHSTy->isRealFloatingType()) {
4910 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004911
Richard Smith745f5142012-01-27 01:14:48 +00004912 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4913 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004914 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004915
Richard Smith745f5142012-01-27 01:14:48 +00004916 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004917 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004918
Anders Carlsson286f85e2008-11-16 07:17:21 +00004919 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004920
Anders Carlsson286f85e2008-11-16 07:17:21 +00004921 switch (E->getOpcode()) {
4922 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004923 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004924 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004925 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004926 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004927 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004928 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004929 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004930 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004931 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004932 E);
John McCall2de56d12010-08-25 11:45:40 +00004933 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004934 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004935 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004936 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004937 || CR == APFloat::cmpLessThan
4938 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004939 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004940 }
Mike Stump1eb44332009-09-09 15:08:12 +00004941
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004942 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004943 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004944 LValue LHSValue, RHSValue;
4945
4946 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4947 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004948 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004949
Richard Smith745f5142012-01-27 01:14:48 +00004950 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004951 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004952
Richard Smith625b8072011-10-31 01:37:14 +00004953 // Reject differing bases from the normal codepath; we special-case
4954 // comparisons to null.
4955 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004956 if (E->getOpcode() == BO_Sub) {
4957 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004958 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4959 return false;
4960 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4961 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4962 if (!LHSExpr || !RHSExpr)
4963 return false;
4964 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4965 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4966 if (!LHSAddrExpr || !RHSAddrExpr)
4967 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004968 // Make sure both labels come from the same function.
4969 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4970 RHSAddrExpr->getLabel()->getDeclContext())
4971 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004972 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004973 return true;
4974 }
Richard Smith9e36b532011-10-31 05:11:32 +00004975 // Inequalities and subtractions between unrelated pointers have
4976 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004977 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004978 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004979 // A constant address may compare equal to the address of a symbol.
4980 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004981 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004982 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4983 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004984 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004985 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004986 // distinct addresses. In clang, the result of such a comparison is
4987 // unspecified, so it is not a constant expression. However, we do know
4988 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004989 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4990 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004991 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004992 // We can't tell whether weak symbols will end up pointing to the same
4993 // object.
4994 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004995 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004996 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004997 // (Note that clang defaults to -fmerge-all-constants, which can
4998 // lead to inconsistent results for comparisons involving the address
4999 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00005000 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00005001 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005002
Richard Smith15efc4d2012-02-01 08:10:20 +00005003 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5004 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5005
Richard Smithf15fda02012-02-02 01:16:57 +00005006 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5007 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5008
John McCall2de56d12010-08-25 11:45:40 +00005009 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00005010 // C++11 [expr.add]p6:
5011 // Unless both pointers point to elements of the same array object, or
5012 // one past the last element of the array object, the behavior is
5013 // undefined.
5014 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5015 !AreElementsOfSameArray(getType(LHSValue.Base),
5016 LHSDesignator, RHSDesignator))
5017 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5018
Chris Lattner4992bdd2010-04-20 17:13:14 +00005019 QualType Type = E->getLHS()->getType();
5020 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00005021
Richard Smith180f4792011-11-10 06:34:14 +00005022 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00005023 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00005024 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00005025
Richard Smith15efc4d2012-02-01 08:10:20 +00005026 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5027 // and produce incorrect results when it overflows. Such behavior
5028 // appears to be non-conforming, but is common, so perhaps we should
5029 // assume the standard intended for such cases to be undefined behavior
5030 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00005031
Richard Smith15efc4d2012-02-01 08:10:20 +00005032 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5033 // overflow in the final conversion to ptrdiff_t.
5034 APSInt LHS(
5035 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5036 APSInt RHS(
5037 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5038 APSInt ElemSize(
5039 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5040 APSInt TrueResult = (LHS - RHS) / ElemSize;
5041 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5042
5043 if (Result.extend(65) != TrueResult)
5044 HandleOverflow(Info, E, TrueResult, E->getType());
5045 return Success(Result, E);
5046 }
Richard Smith82f28582012-01-31 06:41:30 +00005047
5048 // C++11 [expr.rel]p3:
5049 // Pointers to void (after pointer conversions) can be compared, with a
5050 // result defined as follows: If both pointers represent the same
5051 // address or are both the null pointer value, the result is true if the
5052 // operator is <= or >= and false otherwise; otherwise the result is
5053 // unspecified.
5054 // We interpret this as applying to pointers to *cv* void.
5055 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005056 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005057 CCEDiag(E, diag::note_constexpr_void_comparison);
5058
Richard Smithf15fda02012-02-02 01:16:57 +00005059 // C++11 [expr.rel]p2:
5060 // - If two pointers point to non-static data members of the same object,
5061 // or to subobjects or array elements fo such members, recursively, the
5062 // pointer to the later declared member compares greater provided the
5063 // two members have the same access control and provided their class is
5064 // not a union.
5065 // [...]
5066 // - Otherwise pointer comparisons are unspecified.
5067 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5068 E->isRelationalOp()) {
5069 bool WasArrayIndex;
5070 unsigned Mismatch =
5071 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5072 RHSDesignator, WasArrayIndex);
5073 // At the point where the designators diverge, the comparison has a
5074 // specified value if:
5075 // - we are comparing array indices
5076 // - we are comparing fields of a union, or fields with the same access
5077 // Otherwise, the result is unspecified and thus the comparison is not a
5078 // constant expression.
5079 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5080 Mismatch < RHSDesignator.Entries.size()) {
5081 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5082 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5083 if (!LF && !RF)
5084 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5085 else if (!LF)
5086 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5087 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5088 << RF->getParent() << RF;
5089 else if (!RF)
5090 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5091 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5092 << LF->getParent() << LF;
5093 else if (!LF->getParent()->isUnion() &&
5094 LF->getAccess() != RF->getAccess())
5095 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5096 << LF << LF->getAccess() << RF << RF->getAccess()
5097 << LF->getParent();
5098 }
5099 }
5100
Eli Friedmana3169882012-04-16 04:30:08 +00005101 // The comparison here must be unsigned, and performed with the same
5102 // width as the pointer.
Eli Friedmana3169882012-04-16 04:30:08 +00005103 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5104 uint64_t CompareLHS = LHSOffset.getQuantity();
5105 uint64_t CompareRHS = RHSOffset.getQuantity();
5106 assert(PtrSize <= 64 && "Unexpected pointer width");
5107 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5108 CompareLHS &= Mask;
5109 CompareRHS &= Mask;
5110
Eli Friedman28503762012-04-16 19:23:57 +00005111 // If there is a base and this is a relational operator, we can only
5112 // compare pointers within the object in question; otherwise, the result
5113 // depends on where the object is located in memory.
5114 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5115 QualType BaseTy = getType(LHSValue.Base);
5116 if (BaseTy->isIncompleteType())
5117 return Error(E);
5118 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5119 uint64_t OffsetLimit = Size.getQuantity();
5120 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5121 return Error(E);
5122 }
5123
Richard Smith625b8072011-10-31 01:37:14 +00005124 switch (E->getOpcode()) {
5125 default: llvm_unreachable("missing comparison operator");
Eli Friedmana3169882012-04-16 04:30:08 +00005126 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5127 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5128 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5129 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5130 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5131 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005132 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005133 }
5134 }
Richard Smithb02e4622012-02-01 01:42:44 +00005135
5136 if (LHSTy->isMemberPointerType()) {
5137 assert(E->isEqualityOp() && "unexpected member pointer operation");
5138 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5139
5140 MemberPtr LHSValue, RHSValue;
5141
5142 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5143 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5144 return false;
5145
5146 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5147 return false;
5148
5149 // C++11 [expr.eq]p2:
5150 // If both operands are null, they compare equal. Otherwise if only one is
5151 // null, they compare unequal.
5152 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5153 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5154 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5155 }
5156
5157 // Otherwise if either is a pointer to a virtual member function, the
5158 // result is unspecified.
5159 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5160 if (MD->isVirtual())
5161 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5162 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5163 if (MD->isVirtual())
5164 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5165
5166 // Otherwise they compare equal if and only if they would refer to the
5167 // same member of the same most derived object or the same subobject if
5168 // they were dereferenced with a hypothetical object of the associated
5169 // class type.
5170 bool Equal = LHSValue == RHSValue;
5171 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5172 }
5173
Richard Smith26f2cac2012-02-14 22:35:28 +00005174 if (LHSTy->isNullPtrType()) {
5175 assert(E->isComparisonOp() && "unexpected nullptr operation");
5176 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5177 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5178 // are compared, the result is true of the operator is <=, >= or ==, and
5179 // false otherwise.
5180 BinaryOperator::Opcode Opcode = E->getOpcode();
5181 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5182 }
5183
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005184 assert((!LHSTy->isIntegralOrEnumerationType() ||
5185 !RHSTy->isIntegralOrEnumerationType()) &&
5186 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5187 // We can't continue from here for non-integral types.
5188 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005189}
5190
Ken Dyck8b752f12010-01-27 17:10:57 +00005191CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005192 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5193 // result shall be the alignment of the referenced type."
5194 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5195 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005196
5197 // __alignof is defined to return the preferred alignment.
5198 return Info.Ctx.toCharUnitsFromBits(
5199 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005200}
5201
Ken Dyck8b752f12010-01-27 17:10:57 +00005202CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005203 E = E->IgnoreParens();
5204
5205 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005206 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005207 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005208 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5209 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005210
Chris Lattneraf707ab2009-01-24 21:53:27 +00005211 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005212 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5213 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005214
Chris Lattnere9feb472009-01-24 21:09:06 +00005215 return GetAlignOfType(E->getType());
5216}
5217
5218
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005219/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5220/// a result as the expression's type.
5221bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5222 const UnaryExprOrTypeTraitExpr *E) {
5223 switch(E->getKind()) {
5224 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005225 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005226 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005227 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005228 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005229 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005230
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005231 case UETT_VecStep: {
5232 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005233
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005234 if (Ty->isVectorType()) {
5235 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005236
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005237 // The vec_step built-in functions that take a 3-component
5238 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5239 if (n == 3)
5240 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005241
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005242 return Success(n, E);
5243 } else
5244 return Success(1, E);
5245 }
5246
5247 case UETT_SizeOf: {
5248 QualType SrcTy = E->getTypeOfArgument();
5249 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5250 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005251 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5252 SrcTy = Ref->getPointeeType();
5253
Richard Smith180f4792011-11-10 06:34:14 +00005254 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005255 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005256 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005257 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005258 }
5259 }
5260
5261 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005262}
5263
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005264bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005265 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005266 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005267 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005268 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005269 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005270 for (unsigned i = 0; i != n; ++i) {
5271 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5272 switch (ON.getKind()) {
5273 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005274 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005275 APSInt IdxResult;
5276 if (!EvaluateInteger(Idx, IdxResult, Info))
5277 return false;
5278 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5279 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005280 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005281 CurrentType = AT->getElementType();
5282 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5283 Result += IdxResult.getSExtValue() * ElementSize;
5284 break;
5285 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005286
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005287 case OffsetOfExpr::OffsetOfNode::Field: {
5288 FieldDecl *MemberDecl = ON.getField();
5289 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005290 if (!RT)
5291 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005292 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005293 if (RD->isInvalidDecl()) return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005294 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005295 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005296 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005297 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005298 CurrentType = MemberDecl->getType().getNonReferenceType();
5299 break;
5300 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005301
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005302 case OffsetOfExpr::OffsetOfNode::Identifier:
5303 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005304
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005305 case OffsetOfExpr::OffsetOfNode::Base: {
5306 CXXBaseSpecifier *BaseSpec = ON.getBase();
5307 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005308 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005309
5310 // Find the layout of the class whose base we are looking into.
5311 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005312 if (!RT)
5313 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005314 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005315 if (RD->isInvalidDecl()) return false;
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005316 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5317
5318 // Find the base class itself.
5319 CurrentType = BaseSpec->getType();
5320 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5321 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005322 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005323
5324 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005325 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005326 break;
5327 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005328 }
5329 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005330 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005331}
5332
Chris Lattnerb542afe2008-07-11 19:10:17 +00005333bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005334 switch (E->getOpcode()) {
5335 default:
5336 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5337 // See C99 6.6p3.
5338 return Error(E);
5339 case UO_Extension:
5340 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5341 // If so, we could clear the diagnostic ID.
5342 return Visit(E->getSubExpr());
5343 case UO_Plus:
5344 // The result is just the value.
5345 return Visit(E->getSubExpr());
5346 case UO_Minus: {
5347 if (!Visit(E->getSubExpr()))
5348 return false;
5349 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005350 const APSInt &Value = Result.getInt();
5351 if (Value.isSigned() && Value.isMinSignedValue())
5352 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5353 E->getType());
5354 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005355 }
5356 case UO_Not: {
5357 if (!Visit(E->getSubExpr()))
5358 return false;
5359 if (!Result.isInt()) return Error(E);
5360 return Success(~Result.getInt(), E);
5361 }
5362 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005363 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005364 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005365 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005366 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005367 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005368 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005369}
Mike Stump1eb44332009-09-09 15:08:12 +00005370
Chris Lattner732b2232008-07-12 01:15:53 +00005371/// HandleCast - This is used to evaluate implicit or explicit casts where the
5372/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005373bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5374 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005375 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005376 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005377
Eli Friedman46a52322011-03-25 00:43:55 +00005378 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005379 case CK_BaseToDerived:
5380 case CK_DerivedToBase:
5381 case CK_UncheckedDerivedToBase:
5382 case CK_Dynamic:
5383 case CK_ToUnion:
5384 case CK_ArrayToPointerDecay:
5385 case CK_FunctionToPointerDecay:
5386 case CK_NullToPointer:
5387 case CK_NullToMemberPointer:
5388 case CK_BaseToDerivedMemberPointer:
5389 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005390 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005391 case CK_ConstructorConversion:
5392 case CK_IntegralToPointer:
5393 case CK_ToVoid:
5394 case CK_VectorSplat:
5395 case CK_IntegralToFloating:
5396 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005397 case CK_CPointerToObjCPointerCast:
5398 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005399 case CK_AnyPointerToBlockPointerCast:
5400 case CK_ObjCObjectLValueCast:
5401 case CK_FloatingRealToComplex:
5402 case CK_FloatingComplexToReal:
5403 case CK_FloatingComplexCast:
5404 case CK_FloatingComplexToIntegralComplex:
5405 case CK_IntegralRealToComplex:
5406 case CK_IntegralComplexCast:
5407 case CK_IntegralComplexToFloatingComplex:
5408 llvm_unreachable("invalid cast kind for integral value");
5409
Eli Friedmane50c2972011-03-25 19:07:11 +00005410 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005411 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005412 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005413 case CK_ARCProduceObject:
5414 case CK_ARCConsumeObject:
5415 case CK_ARCReclaimReturnedObject:
5416 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005417 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005418 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005419
Richard Smith7d580a42012-01-17 21:17:26 +00005420 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005421 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005422 case CK_AtomicToNonAtomic:
5423 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005424 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005425 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005426
5427 case CK_MemberPointerToBoolean:
5428 case CK_PointerToBoolean:
5429 case CK_IntegralToBoolean:
5430 case CK_FloatingToBoolean:
5431 case CK_FloatingComplexToBoolean:
5432 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005433 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005434 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005435 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005436 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005437 }
5438
Eli Friedman46a52322011-03-25 00:43:55 +00005439 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005440 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005441 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005442
Eli Friedmanbe265702009-02-20 01:15:07 +00005443 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005444 // Allow casts of address-of-label differences if they are no-ops
5445 // or narrowing. (The narrowing case isn't actually guaranteed to
5446 // be constant-evaluatable except in some narrow cases which are hard
5447 // to detect here. We let it through on the assumption the user knows
5448 // what they are doing.)
5449 if (Result.isAddrLabelDiff())
5450 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005451 // Only allow casts of lvalues if they are lossless.
5452 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5453 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005454
Richard Smithf72fccf2012-01-30 22:27:01 +00005455 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5456 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005457 }
Mike Stump1eb44332009-09-09 15:08:12 +00005458
Eli Friedman46a52322011-03-25 00:43:55 +00005459 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005460 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5461
John McCallefdb83e2010-05-07 21:00:08 +00005462 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005463 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005464 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005465
Daniel Dunbardd211642009-02-19 22:24:01 +00005466 if (LV.getLValueBase()) {
5467 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005468 // FIXME: Allow a larger integer size than the pointer size, and allow
5469 // narrowing back down to pointer width in subsequent integral casts.
5470 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005471 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005472 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005473
Richard Smithb755a9d2011-11-16 07:18:12 +00005474 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005475 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005476 return true;
5477 }
5478
Ken Dycka7305832010-01-15 12:37:54 +00005479 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5480 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005481 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005482 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005483
Eli Friedman46a52322011-03-25 00:43:55 +00005484 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005485 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005486 if (!EvaluateComplex(SubExpr, C, Info))
5487 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005488 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005489 }
Eli Friedman2217c872009-02-22 11:46:18 +00005490
Eli Friedman46a52322011-03-25 00:43:55 +00005491 case CK_FloatingToIntegral: {
5492 APFloat F(0.0);
5493 if (!EvaluateFloat(SubExpr, F, Info))
5494 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005495
Richard Smithc1c5f272011-12-13 06:39:58 +00005496 APSInt Value;
5497 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5498 return false;
5499 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005500 }
5501 }
Mike Stump1eb44332009-09-09 15:08:12 +00005502
Eli Friedman46a52322011-03-25 00:43:55 +00005503 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005504}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005505
Eli Friedman722c7172009-02-28 03:59:05 +00005506bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5507 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005508 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005509 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5510 return false;
5511 if (!LV.isComplexInt())
5512 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005513 return Success(LV.getComplexIntReal(), E);
5514 }
5515
5516 return Visit(E->getSubExpr());
5517}
5518
Eli Friedman664a1042009-02-27 04:45:43 +00005519bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005520 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005521 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005522 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5523 return false;
5524 if (!LV.isComplexInt())
5525 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005526 return Success(LV.getComplexIntImag(), E);
5527 }
5528
Richard Smith8327fad2011-10-24 18:44:57 +00005529 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005530 return Success(0, E);
5531}
5532
Douglas Gregoree8aff02011-01-04 17:33:58 +00005533bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5534 return Success(E->getPackLength(), E);
5535}
5536
Sebastian Redl295995c2010-09-10 20:55:47 +00005537bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5538 return Success(E->getValue(), E);
5539}
5540
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005541//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005542// Float Evaluation
5543//===----------------------------------------------------------------------===//
5544
5545namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005546class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005547 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005548 APFloat &Result;
5549public:
5550 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005551 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005552
Richard Smith1aa0be82012-03-03 22:46:17 +00005553 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005554 Result = V.getFloat();
5555 return true;
5556 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005557
Richard Smith51201882011-12-30 21:15:51 +00005558 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005559 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5560 return true;
5561 }
5562
Chris Lattner019f4e82008-10-06 05:28:25 +00005563 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005564
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005565 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005566 bool VisitBinaryOperator(const BinaryOperator *E);
5567 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005568 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005569
John McCallabd3a852010-05-07 22:08:54 +00005570 bool VisitUnaryReal(const UnaryOperator *E);
5571 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005572
Richard Smith51201882011-12-30 21:15:51 +00005573 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005574};
5575} // end anonymous namespace
5576
5577static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005578 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005579 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005580}
5581
Jay Foad4ba2a172011-01-12 09:06:06 +00005582static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005583 QualType ResultTy,
5584 const Expr *Arg,
5585 bool SNaN,
5586 llvm::APFloat &Result) {
5587 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5588 if (!S) return false;
5589
5590 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5591
5592 llvm::APInt fill;
5593
5594 // Treat empty strings as if they were zero.
5595 if (S->getString().empty())
5596 fill = llvm::APInt(32, 0);
5597 else if (S->getString().getAsInteger(0, fill))
5598 return false;
5599
5600 if (SNaN)
5601 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5602 else
5603 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5604 return true;
5605}
5606
Chris Lattner019f4e82008-10-06 05:28:25 +00005607bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005608 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005609 default:
5610 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5611
Chris Lattner019f4e82008-10-06 05:28:25 +00005612 case Builtin::BI__builtin_huge_val:
5613 case Builtin::BI__builtin_huge_valf:
5614 case Builtin::BI__builtin_huge_vall:
5615 case Builtin::BI__builtin_inf:
5616 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005617 case Builtin::BI__builtin_infl: {
5618 const llvm::fltSemantics &Sem =
5619 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005620 Result = llvm::APFloat::getInf(Sem);
5621 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005622 }
Mike Stump1eb44332009-09-09 15:08:12 +00005623
John McCalldb7b72a2010-02-28 13:00:19 +00005624 case Builtin::BI__builtin_nans:
5625 case Builtin::BI__builtin_nansf:
5626 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005627 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5628 true, Result))
5629 return Error(E);
5630 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005631
Chris Lattner9e621712008-10-06 06:31:58 +00005632 case Builtin::BI__builtin_nan:
5633 case Builtin::BI__builtin_nanf:
5634 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005635 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005636 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005637 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5638 false, Result))
5639 return Error(E);
5640 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005641
5642 case Builtin::BI__builtin_fabs:
5643 case Builtin::BI__builtin_fabsf:
5644 case Builtin::BI__builtin_fabsl:
5645 if (!EvaluateFloat(E->getArg(0), Result, Info))
5646 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005647
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005648 if (Result.isNegative())
5649 Result.changeSign();
5650 return true;
5651
Mike Stump1eb44332009-09-09 15:08:12 +00005652 case Builtin::BI__builtin_copysign:
5653 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005654 case Builtin::BI__builtin_copysignl: {
5655 APFloat RHS(0.);
5656 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5657 !EvaluateFloat(E->getArg(1), RHS, Info))
5658 return false;
5659 Result.copySign(RHS);
5660 return true;
5661 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005662 }
5663}
5664
John McCallabd3a852010-05-07 22:08:54 +00005665bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005666 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5667 ComplexValue CV;
5668 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5669 return false;
5670 Result = CV.FloatReal;
5671 return true;
5672 }
5673
5674 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005675}
5676
5677bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005678 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5679 ComplexValue CV;
5680 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5681 return false;
5682 Result = CV.FloatImag;
5683 return true;
5684 }
5685
Richard Smith8327fad2011-10-24 18:44:57 +00005686 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005687 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5688 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005689 return true;
5690}
5691
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005692bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005693 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005694 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005695 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005696 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005697 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005698 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5699 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005700 Result.changeSign();
5701 return true;
5702 }
5703}
Chris Lattner019f4e82008-10-06 05:28:25 +00005704
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005705bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005706 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5707 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005708
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005709 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005710 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5711 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005712 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005713 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005714 return false;
5715
5716 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005717 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005718 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005719 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005720 break;
John McCall2de56d12010-08-25 11:45:40 +00005721 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005722 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005723 break;
John McCall2de56d12010-08-25 11:45:40 +00005724 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005725 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005726 break;
John McCall2de56d12010-08-25 11:45:40 +00005727 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005728 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005729 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005730 }
Richard Smith7b48a292012-02-01 05:53:12 +00005731
5732 if (Result.isInfinity() || Result.isNaN())
5733 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5734 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005735}
5736
5737bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5738 Result = E->getValue();
5739 return true;
5740}
5741
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005742bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5743 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005744
Eli Friedman2a523ee2011-03-25 00:54:52 +00005745 switch (E->getCastKind()) {
5746 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005747 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005748
5749 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005750 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005751 return EvaluateInteger(SubExpr, IntResult, Info) &&
5752 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5753 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005754 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005755
5756 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005757 if (!Visit(SubExpr))
5758 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005759 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5760 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005761 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005762
Eli Friedman2a523ee2011-03-25 00:54:52 +00005763 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005764 ComplexValue V;
5765 if (!EvaluateComplex(SubExpr, V, Info))
5766 return false;
5767 Result = V.getComplexFloatReal();
5768 return true;
5769 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005770 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005771}
5772
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005773//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005774// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005775//===----------------------------------------------------------------------===//
5776
5777namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005778class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005779 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005780 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005781
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005782public:
John McCallf4cf1a12010-05-07 17:22:02 +00005783 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005784 : ExprEvaluatorBaseTy(info), Result(Result) {}
5785
Richard Smith1aa0be82012-03-03 22:46:17 +00005786 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005787 Result.setFrom(V);
5788 return true;
5789 }
Mike Stump1eb44332009-09-09 15:08:12 +00005790
Eli Friedman7ead5c72012-01-10 04:58:17 +00005791 bool ZeroInitialization(const Expr *E);
5792
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005793 //===--------------------------------------------------------------------===//
5794 // Visitor Methods
5795 //===--------------------------------------------------------------------===//
5796
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005797 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005798 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005799 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005800 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005801 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005802};
5803} // end anonymous namespace
5804
John McCallf4cf1a12010-05-07 17:22:02 +00005805static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5806 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005807 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005808 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005809}
5810
Eli Friedman7ead5c72012-01-10 04:58:17 +00005811bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005812 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005813 if (ElemTy->isRealFloatingType()) {
5814 Result.makeComplexFloat();
5815 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5816 Result.FloatReal = Zero;
5817 Result.FloatImag = Zero;
5818 } else {
5819 Result.makeComplexInt();
5820 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5821 Result.IntReal = Zero;
5822 Result.IntImag = Zero;
5823 }
5824 return true;
5825}
5826
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005827bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5828 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005829
5830 if (SubExpr->getType()->isRealFloatingType()) {
5831 Result.makeComplexFloat();
5832 APFloat &Imag = Result.FloatImag;
5833 if (!EvaluateFloat(SubExpr, Imag, Info))
5834 return false;
5835
5836 Result.FloatReal = APFloat(Imag.getSemantics());
5837 return true;
5838 } else {
5839 assert(SubExpr->getType()->isIntegerType() &&
5840 "Unexpected imaginary literal.");
5841
5842 Result.makeComplexInt();
5843 APSInt &Imag = Result.IntImag;
5844 if (!EvaluateInteger(SubExpr, Imag, Info))
5845 return false;
5846
5847 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5848 return true;
5849 }
5850}
5851
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005852bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005853
John McCall8786da72010-12-14 17:51:41 +00005854 switch (E->getCastKind()) {
5855 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005856 case CK_BaseToDerived:
5857 case CK_DerivedToBase:
5858 case CK_UncheckedDerivedToBase:
5859 case CK_Dynamic:
5860 case CK_ToUnion:
5861 case CK_ArrayToPointerDecay:
5862 case CK_FunctionToPointerDecay:
5863 case CK_NullToPointer:
5864 case CK_NullToMemberPointer:
5865 case CK_BaseToDerivedMemberPointer:
5866 case CK_DerivedToBaseMemberPointer:
5867 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005868 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005869 case CK_ConstructorConversion:
5870 case CK_IntegralToPointer:
5871 case CK_PointerToIntegral:
5872 case CK_PointerToBoolean:
5873 case CK_ToVoid:
5874 case CK_VectorSplat:
5875 case CK_IntegralCast:
5876 case CK_IntegralToBoolean:
5877 case CK_IntegralToFloating:
5878 case CK_FloatingToIntegral:
5879 case CK_FloatingToBoolean:
5880 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005881 case CK_CPointerToObjCPointerCast:
5882 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005883 case CK_AnyPointerToBlockPointerCast:
5884 case CK_ObjCObjectLValueCast:
5885 case CK_FloatingComplexToReal:
5886 case CK_FloatingComplexToBoolean:
5887 case CK_IntegralComplexToReal:
5888 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005889 case CK_ARCProduceObject:
5890 case CK_ARCConsumeObject:
5891 case CK_ARCReclaimReturnedObject:
5892 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005893 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005894 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005895
John McCall8786da72010-12-14 17:51:41 +00005896 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005897 case CK_AtomicToNonAtomic:
5898 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005899 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005900 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005901
5902 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005903 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005904 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005905 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005906
5907 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005908 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005909 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005910 return false;
5911
John McCall8786da72010-12-14 17:51:41 +00005912 Result.makeComplexFloat();
5913 Result.FloatImag = APFloat(Real.getSemantics());
5914 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005915 }
5916
John McCall8786da72010-12-14 17:51:41 +00005917 case CK_FloatingComplexCast: {
5918 if (!Visit(E->getSubExpr()))
5919 return false;
5920
5921 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5922 QualType From
5923 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5924
Richard Smithc1c5f272011-12-13 06:39:58 +00005925 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5926 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005927 }
5928
5929 case CK_FloatingComplexToIntegralComplex: {
5930 if (!Visit(E->getSubExpr()))
5931 return false;
5932
5933 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5934 QualType From
5935 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5936 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005937 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5938 To, Result.IntReal) &&
5939 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5940 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005941 }
5942
5943 case CK_IntegralRealToComplex: {
5944 APSInt &Real = Result.IntReal;
5945 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5946 return false;
5947
5948 Result.makeComplexInt();
5949 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5950 return true;
5951 }
5952
5953 case CK_IntegralComplexCast: {
5954 if (!Visit(E->getSubExpr()))
5955 return false;
5956
5957 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5958 QualType From
5959 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5960
Richard Smithf72fccf2012-01-30 22:27:01 +00005961 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5962 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005963 return true;
5964 }
5965
5966 case CK_IntegralComplexToFloatingComplex: {
5967 if (!Visit(E->getSubExpr()))
5968 return false;
5969
5970 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5971 QualType From
5972 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5973 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005974 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5975 To, Result.FloatReal) &&
5976 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5977 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005978 }
5979 }
5980
5981 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005982}
5983
John McCallf4cf1a12010-05-07 17:22:02 +00005984bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005985 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005986 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5987
Richard Smith745f5142012-01-27 01:14:48 +00005988 bool LHSOK = Visit(E->getLHS());
5989 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005990 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005991
John McCallf4cf1a12010-05-07 17:22:02 +00005992 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005993 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005994 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005995
Daniel Dunbar3f279872009-01-29 01:32:56 +00005996 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5997 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005998 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005999 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00006000 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006001 if (Result.isComplexFloat()) {
6002 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6003 APFloat::rmNearestTiesToEven);
6004 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6005 APFloat::rmNearestTiesToEven);
6006 } else {
6007 Result.getComplexIntReal() += RHS.getComplexIntReal();
6008 Result.getComplexIntImag() += RHS.getComplexIntImag();
6009 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00006010 break;
John McCall2de56d12010-08-25 11:45:40 +00006011 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006012 if (Result.isComplexFloat()) {
6013 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6014 APFloat::rmNearestTiesToEven);
6015 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6016 APFloat::rmNearestTiesToEven);
6017 } else {
6018 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6019 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6020 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00006021 break;
John McCall2de56d12010-08-25 11:45:40 +00006022 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00006023 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00006024 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00006025 APFloat &LHS_r = LHS.getComplexFloatReal();
6026 APFloat &LHS_i = LHS.getComplexFloatImag();
6027 APFloat &RHS_r = RHS.getComplexFloatReal();
6028 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00006029
Daniel Dunbar3f279872009-01-29 01:32:56 +00006030 APFloat Tmp = LHS_r;
6031 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6032 Result.getComplexFloatReal() = Tmp;
6033 Tmp = LHS_i;
6034 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6035 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6036
6037 Tmp = LHS_r;
6038 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6039 Result.getComplexFloatImag() = Tmp;
6040 Tmp = LHS_i;
6041 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6042 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6043 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00006044 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00006045 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006046 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6047 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00006048 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006049 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6050 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6051 }
6052 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006053 case BO_Div:
6054 if (Result.isComplexFloat()) {
6055 ComplexValue LHS = Result;
6056 APFloat &LHS_r = LHS.getComplexFloatReal();
6057 APFloat &LHS_i = LHS.getComplexFloatImag();
6058 APFloat &RHS_r = RHS.getComplexFloatReal();
6059 APFloat &RHS_i = RHS.getComplexFloatImag();
6060 APFloat &Res_r = Result.getComplexFloatReal();
6061 APFloat &Res_i = Result.getComplexFloatImag();
6062
6063 APFloat Den = RHS_r;
6064 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6065 APFloat Tmp = RHS_i;
6066 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6067 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6068
6069 Res_r = LHS_r;
6070 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6071 Tmp = LHS_i;
6072 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6073 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6074 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6075
6076 Res_i = LHS_i;
6077 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6078 Tmp = LHS_r;
6079 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6080 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6081 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6082 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006083 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6084 return Error(E, diag::note_expr_divide_by_zero);
6085
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006086 ComplexValue LHS = Result;
6087 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6088 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6089 Result.getComplexIntReal() =
6090 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6091 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6092 Result.getComplexIntImag() =
6093 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6094 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6095 }
6096 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006097 }
6098
John McCallf4cf1a12010-05-07 17:22:02 +00006099 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006100}
6101
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006102bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6103 // Get the operand value into 'Result'.
6104 if (!Visit(E->getSubExpr()))
6105 return false;
6106
6107 switch (E->getOpcode()) {
6108 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006109 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006110 case UO_Extension:
6111 return true;
6112 case UO_Plus:
6113 // The result is always just the subexpr.
6114 return true;
6115 case UO_Minus:
6116 if (Result.isComplexFloat()) {
6117 Result.getComplexFloatReal().changeSign();
6118 Result.getComplexFloatImag().changeSign();
6119 }
6120 else {
6121 Result.getComplexIntReal() = -Result.getComplexIntReal();
6122 Result.getComplexIntImag() = -Result.getComplexIntImag();
6123 }
6124 return true;
6125 case UO_Not:
6126 if (Result.isComplexFloat())
6127 Result.getComplexFloatImag().changeSign();
6128 else
6129 Result.getComplexIntImag() = -Result.getComplexIntImag();
6130 return true;
6131 }
6132}
6133
Eli Friedman7ead5c72012-01-10 04:58:17 +00006134bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6135 if (E->getNumInits() == 2) {
6136 if (E->getType()->isComplexType()) {
6137 Result.makeComplexFloat();
6138 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6139 return false;
6140 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6141 return false;
6142 } else {
6143 Result.makeComplexInt();
6144 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6145 return false;
6146 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6147 return false;
6148 }
6149 return true;
6150 }
6151 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6152}
6153
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006154//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006155// Void expression evaluation, primarily for a cast to void on the LHS of a
6156// comma operator
6157//===----------------------------------------------------------------------===//
6158
6159namespace {
6160class VoidExprEvaluator
6161 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6162public:
6163 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6164
Richard Smith1aa0be82012-03-03 22:46:17 +00006165 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006166
6167 bool VisitCastExpr(const CastExpr *E) {
6168 switch (E->getCastKind()) {
6169 default:
6170 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6171 case CK_ToVoid:
6172 VisitIgnoredValue(E->getSubExpr());
6173 return true;
6174 }
6175 }
6176};
6177} // end anonymous namespace
6178
6179static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6180 assert(E->isRValue() && E->getType()->isVoidType());
6181 return VoidExprEvaluator(Info).Visit(E);
6182}
6183
6184//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006185// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006186//===----------------------------------------------------------------------===//
6187
Richard Smith1aa0be82012-03-03 22:46:17 +00006188static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006189 // In C, function designators are not lvalues, but we evaluate them as if they
6190 // are.
6191 if (E->isGLValue() || E->getType()->isFunctionType()) {
6192 LValue LV;
6193 if (!EvaluateLValue(E, LV, Info))
6194 return false;
6195 LV.moveInto(Result);
6196 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006197 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006198 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006199 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006200 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006201 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006202 } else if (E->getType()->hasPointerRepresentation()) {
6203 LValue LV;
6204 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006205 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006206 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006207 } else if (E->getType()->isRealFloatingType()) {
6208 llvm::APFloat F(0.0);
6209 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006210 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006211 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006212 } else if (E->getType()->isAnyComplexType()) {
6213 ComplexValue C;
6214 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006215 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006216 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006217 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006218 MemberPtr P;
6219 if (!EvaluateMemberPointer(E, P, Info))
6220 return false;
6221 P.moveInto(Result);
6222 return true;
Richard Smith51201882011-12-30 21:15:51 +00006223 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006224 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006225 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006226 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006227 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006228 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006229 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006230 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006231 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006232 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6233 return false;
6234 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006235 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006236 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006237 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006238 << E->getType();
6239 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00006240 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006241 if (!EvaluateVoid(E, Info))
6242 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006243 } else if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006244 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006245 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006246 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006247 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006248 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006249 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006250
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006251 return true;
6252}
6253
Richard Smith83587db2012-02-15 02:18:13 +00006254/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6255/// cases, the in-place evaluation is essential, since later initializers for
6256/// an object can indirectly refer to subobjects which were initialized earlier.
6257static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6258 const Expr *E, CheckConstantExpressionKind CCEK,
6259 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006260 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006261 return false;
6262
6263 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006264 // Evaluate arrays and record types in-place, so that later initializers can
6265 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006266 if (E->getType()->isArrayType())
6267 return EvaluateArray(E, This, Result, Info);
6268 else if (E->getType()->isRecordType())
6269 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006270 }
6271
6272 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006273 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006274}
6275
Richard Smithf48fdb02011-12-09 22:58:01 +00006276/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6277/// lvalue-to-rvalue cast if it is an lvalue.
6278static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006279 if (!CheckLiteralType(Info, E))
6280 return false;
6281
Richard Smith1aa0be82012-03-03 22:46:17 +00006282 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006283 return false;
6284
6285 if (E->isGLValue()) {
6286 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006287 LV.setFrom(Info.Ctx, Result);
6288 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006289 return false;
6290 }
6291
Richard Smith1aa0be82012-03-03 22:46:17 +00006292 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006293 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006294}
Richard Smithc49bd112011-10-28 17:51:58 +00006295
Richard Smith51f47082011-10-29 00:50:52 +00006296/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006297/// any crazy technique (that has nothing to do with language standards) that
6298/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006299/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6300/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006301bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006302 // Fast-path evaluations of integer literals, since we sometimes see files
6303 // containing vast quantities of these.
6304 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6305 Result.Val = APValue(APSInt(L->getValue(),
6306 L->getType()->isUnsignedIntegerType()));
6307 return true;
6308 }
6309
Richard Smith2d6a5672012-01-14 04:30:29 +00006310 // FIXME: Evaluating values of large array and record types can cause
6311 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006312 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006313 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006314 return false;
6315
Richard Smithf48fdb02011-12-09 22:58:01 +00006316 EvalInfo Info(Ctx, Result);
6317 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006318}
6319
Jay Foad4ba2a172011-01-12 09:06:06 +00006320bool Expr::EvaluateAsBooleanCondition(bool &Result,
6321 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006322 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006323 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006324 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006325}
6326
Richard Smith80d4b552011-12-28 19:48:30 +00006327bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6328 SideEffectsKind AllowSideEffects) const {
6329 if (!getType()->isIntegralOrEnumerationType())
6330 return false;
6331
Richard Smithc49bd112011-10-28 17:51:58 +00006332 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006333 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6334 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006335 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006336
Richard Smithc49bd112011-10-28 17:51:58 +00006337 Result = ExprResult.Val.getInt();
6338 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006339}
6340
Jay Foad4ba2a172011-01-12 09:06:06 +00006341bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006342 EvalInfo Info(Ctx, Result);
6343
John McCallefdb83e2010-05-07 21:00:08 +00006344 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006345 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6346 !CheckLValueConstantExpression(Info, getExprLoc(),
6347 Ctx.getLValueReferenceType(getType()), LV))
6348 return false;
6349
Richard Smith1aa0be82012-03-03 22:46:17 +00006350 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006351 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006352}
6353
Richard Smith099e7f62011-12-19 06:19:21 +00006354bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6355 const VarDecl *VD,
6356 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006357 // FIXME: Evaluating initializers for large array and record types can cause
6358 // performance problems. Only do so in C++11 for now.
6359 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006360 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith2d6a5672012-01-14 04:30:29 +00006361 return false;
6362
Richard Smith099e7f62011-12-19 06:19:21 +00006363 Expr::EvalStatus EStatus;
6364 EStatus.Diag = &Notes;
6365
6366 EvalInfo InitInfo(Ctx, EStatus);
6367 InitInfo.setEvaluatingDecl(VD, Value);
6368
6369 LValue LVal;
6370 LVal.set(VD);
6371
Richard Smith51201882011-12-30 21:15:51 +00006372 // C++11 [basic.start.init]p2:
6373 // Variables with static storage duration or thread storage duration shall be
6374 // zero-initialized before any other initialization takes place.
6375 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006376 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006377 !VD->getType()->isReferenceType()) {
6378 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006379 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6380 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006381 return false;
6382 }
6383
Richard Smith83587db2012-02-15 02:18:13 +00006384 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6385 /*AllowNonLiteralTypes=*/true) ||
6386 EStatus.HasSideEffects)
6387 return false;
6388
6389 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6390 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006391}
6392
Richard Smith51f47082011-10-29 00:50:52 +00006393/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6394/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006395bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006396 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006397 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006398}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006399
Jay Foad4ba2a172011-01-12 09:06:06 +00006400bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006401 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006402}
6403
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006404APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006405 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006406 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006407 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006408 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006409 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006410
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006411 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006412}
John McCalld905f5a2010-05-07 05:32:02 +00006413
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006414 bool Expr::EvalResult::isGlobalLValue() const {
6415 assert(Val.isLValue());
6416 return IsGlobalLValue(Val.getLValueBase());
6417 }
6418
6419
John McCalld905f5a2010-05-07 05:32:02 +00006420/// isIntegerConstantExpr - this recursive routine will test if an expression is
6421/// an integer constant expression.
6422
6423/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6424/// comma, etc
6425///
6426/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6427/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6428/// cast+dereference.
6429
6430// CheckICE - This function does the fundamental ICE checking: the returned
6431// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6432// Note that to reduce code duplication, this helper does no evaluation
6433// itself; the caller checks whether the expression is evaluatable, and
6434// in the rare cases where CheckICE actually cares about the evaluated
6435// value, it calls into Evalute.
6436//
6437// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006438// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006439// 1: This expression is not an ICE, but if it isn't evaluated, it's
6440// a legal subexpression for an ICE. This return value is used to handle
6441// the comma operator in C99 mode.
6442// 2: This expression is not an ICE, and is not a legal subexpression for one.
6443
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006444namespace {
6445
John McCalld905f5a2010-05-07 05:32:02 +00006446struct ICEDiag {
6447 unsigned Val;
6448 SourceLocation Loc;
6449
6450 public:
6451 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6452 ICEDiag() : Val(0) {}
6453};
6454
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006455}
6456
6457static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006458
6459static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6460 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006461 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006462 !EVResult.Val.isInt()) {
6463 return ICEDiag(2, E->getLocStart());
6464 }
6465 return NoDiag();
6466}
6467
6468static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6469 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006470 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006471 return ICEDiag(2, E->getLocStart());
6472 }
6473
6474 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006475#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006476#define STMT(Node, Base) case Expr::Node##Class:
6477#define EXPR(Node, Base)
6478#include "clang/AST/StmtNodes.inc"
6479 case Expr::PredefinedExprClass:
6480 case Expr::FloatingLiteralClass:
6481 case Expr::ImaginaryLiteralClass:
6482 case Expr::StringLiteralClass:
6483 case Expr::ArraySubscriptExprClass:
6484 case Expr::MemberExprClass:
6485 case Expr::CompoundAssignOperatorClass:
6486 case Expr::CompoundLiteralExprClass:
6487 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006488 case Expr::DesignatedInitExprClass:
6489 case Expr::ImplicitValueInitExprClass:
6490 case Expr::ParenListExprClass:
6491 case Expr::VAArgExprClass:
6492 case Expr::AddrLabelExprClass:
6493 case Expr::StmtExprClass:
6494 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006495 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006496 case Expr::CXXDynamicCastExprClass:
6497 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006498 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006499 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006500 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006501 case Expr::CXXThisExprClass:
6502 case Expr::CXXThrowExprClass:
6503 case Expr::CXXNewExprClass:
6504 case Expr::CXXDeleteExprClass:
6505 case Expr::CXXPseudoDestructorExprClass:
6506 case Expr::UnresolvedLookupExprClass:
6507 case Expr::DependentScopeDeclRefExprClass:
6508 case Expr::CXXConstructExprClass:
6509 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006510 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006511 case Expr::CXXTemporaryObjectExprClass:
6512 case Expr::CXXUnresolvedConstructExprClass:
6513 case Expr::CXXDependentScopeMemberExprClass:
6514 case Expr::UnresolvedMemberExprClass:
6515 case Expr::ObjCStringLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00006516 case Expr::ObjCBoxedExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006517 case Expr::ObjCArrayLiteralClass:
6518 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006519 case Expr::ObjCEncodeExprClass:
6520 case Expr::ObjCMessageExprClass:
6521 case Expr::ObjCSelectorExprClass:
6522 case Expr::ObjCProtocolExprClass:
6523 case Expr::ObjCIvarRefExprClass:
6524 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006525 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006526 case Expr::ObjCIsaExprClass:
6527 case Expr::ShuffleVectorExprClass:
6528 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006529 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006530 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006531 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006532 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006533 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006534 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006535 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006536 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006537 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006538 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006539 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006540 return ICEDiag(2, E->getLocStart());
6541
Douglas Gregoree8aff02011-01-04 17:33:58 +00006542 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006543 case Expr::GNUNullExprClass:
6544 // GCC considers the GNU __null value to be an integral constant expression.
6545 return NoDiag();
6546
John McCall91a57552011-07-15 05:09:51 +00006547 case Expr::SubstNonTypeTemplateParmExprClass:
6548 return
6549 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6550
John McCalld905f5a2010-05-07 05:32:02 +00006551 case Expr::ParenExprClass:
6552 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006553 case Expr::GenericSelectionExprClass:
6554 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006555 case Expr::IntegerLiteralClass:
6556 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006557 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006558 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006559 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006560 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006561 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006562 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006563 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006564 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006565 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006566 return NoDiag();
6567 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006568 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006569 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6570 // constant expressions, but they can never be ICEs because an ICE cannot
6571 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006572 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006573 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006574 return CheckEvalInICE(E, Ctx);
6575 return ICEDiag(2, E->getLocStart());
6576 }
Richard Smith359c89d2012-02-24 22:12:32 +00006577 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006578 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6579 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006580 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006581 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006582 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006583 // Parameter variables are never constants. Without this check,
6584 // getAnyInitializer() can find a default argument, which leads
6585 // to chaos.
6586 if (isa<ParmVarDecl>(D))
6587 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6588
6589 // C++ 7.1.5.1p2
6590 // A variable of non-volatile const-qualified integral or enumeration
6591 // type initialized by an ICE can be used in ICEs.
6592 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006593 if (!Dcl->getType()->isIntegralOrEnumerationType())
6594 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6595
Richard Smith099e7f62011-12-19 06:19:21 +00006596 const VarDecl *VD;
6597 // Look for a declaration of this variable that has an initializer, and
6598 // check whether it is an ICE.
6599 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6600 return NoDiag();
6601 else
6602 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006603 }
6604 }
6605 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006606 }
John McCalld905f5a2010-05-07 05:32:02 +00006607 case Expr::UnaryOperatorClass: {
6608 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6609 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006610 case UO_PostInc:
6611 case UO_PostDec:
6612 case UO_PreInc:
6613 case UO_PreDec:
6614 case UO_AddrOf:
6615 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006616 // C99 6.6/3 allows increment and decrement within unevaluated
6617 // subexpressions of constant expressions, but they can never be ICEs
6618 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006619 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006620 case UO_Extension:
6621 case UO_LNot:
6622 case UO_Plus:
6623 case UO_Minus:
6624 case UO_Not:
6625 case UO_Real:
6626 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006627 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006628 }
6629
6630 // OffsetOf falls through here.
6631 }
6632 case Expr::OffsetOfExprClass: {
6633 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006634 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006635 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006636 // compliance: we should warn earlier for offsetof expressions with
6637 // array subscripts that aren't ICEs, and if the array subscripts
6638 // are ICEs, the value of the offsetof must be an integer constant.
6639 return CheckEvalInICE(E, Ctx);
6640 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006641 case Expr::UnaryExprOrTypeTraitExprClass: {
6642 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6643 if ((Exp->getKind() == UETT_SizeOf) &&
6644 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006645 return ICEDiag(2, E->getLocStart());
6646 return NoDiag();
6647 }
6648 case Expr::BinaryOperatorClass: {
6649 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6650 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006651 case BO_PtrMemD:
6652 case BO_PtrMemI:
6653 case BO_Assign:
6654 case BO_MulAssign:
6655 case BO_DivAssign:
6656 case BO_RemAssign:
6657 case BO_AddAssign:
6658 case BO_SubAssign:
6659 case BO_ShlAssign:
6660 case BO_ShrAssign:
6661 case BO_AndAssign:
6662 case BO_XorAssign:
6663 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006664 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6665 // constant expressions, but they can never be ICEs because an ICE cannot
6666 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006667 return ICEDiag(2, E->getLocStart());
6668
John McCall2de56d12010-08-25 11:45:40 +00006669 case BO_Mul:
6670 case BO_Div:
6671 case BO_Rem:
6672 case BO_Add:
6673 case BO_Sub:
6674 case BO_Shl:
6675 case BO_Shr:
6676 case BO_LT:
6677 case BO_GT:
6678 case BO_LE:
6679 case BO_GE:
6680 case BO_EQ:
6681 case BO_NE:
6682 case BO_And:
6683 case BO_Xor:
6684 case BO_Or:
6685 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006686 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6687 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006688 if (Exp->getOpcode() == BO_Div ||
6689 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006690 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006691 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006692 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006693 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006694 if (REval == 0)
6695 return ICEDiag(1, E->getLocStart());
6696 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006697 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006698 if (LEval.isMinSignedValue())
6699 return ICEDiag(1, E->getLocStart());
6700 }
6701 }
6702 }
John McCall2de56d12010-08-25 11:45:40 +00006703 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006704 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006705 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6706 // if it isn't evaluated.
6707 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6708 return ICEDiag(1, E->getLocStart());
6709 } else {
6710 // In both C89 and C++, commas in ICEs are illegal.
6711 return ICEDiag(2, E->getLocStart());
6712 }
6713 }
6714 if (LHSResult.Val >= RHSResult.Val)
6715 return LHSResult;
6716 return RHSResult;
6717 }
John McCall2de56d12010-08-25 11:45:40 +00006718 case BO_LAnd:
6719 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006720 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6721 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6722 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6723 // Rare case where the RHS has a comma "side-effect"; we need
6724 // to actually check the condition to see whether the side
6725 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006726 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006727 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006728 return RHSResult;
6729 return NoDiag();
6730 }
6731
6732 if (LHSResult.Val >= RHSResult.Val)
6733 return LHSResult;
6734 return RHSResult;
6735 }
6736 }
6737 }
6738 case Expr::ImplicitCastExprClass:
6739 case Expr::CStyleCastExprClass:
6740 case Expr::CXXFunctionalCastExprClass:
6741 case Expr::CXXStaticCastExprClass:
6742 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006743 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006744 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006745 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006746 if (isa<ExplicitCastExpr>(E)) {
6747 if (const FloatingLiteral *FL
6748 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6749 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6750 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6751 APSInt IgnoredVal(DestWidth, !DestSigned);
6752 bool Ignored;
6753 // If the value does not fit in the destination type, the behavior is
6754 // undefined, so we are not required to treat it as a constant
6755 // expression.
6756 if (FL->getValue().convertToInteger(IgnoredVal,
6757 llvm::APFloat::rmTowardZero,
6758 &Ignored) & APFloat::opInvalidOp)
6759 return ICEDiag(2, E->getLocStart());
6760 return NoDiag();
6761 }
6762 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006763 switch (cast<CastExpr>(E)->getCastKind()) {
6764 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006765 case CK_AtomicToNonAtomic:
6766 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006767 case CK_NoOp:
6768 case CK_IntegralToBoolean:
6769 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006770 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006771 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006772 return ICEDiag(2, E->getLocStart());
6773 }
John McCalld905f5a2010-05-07 05:32:02 +00006774 }
John McCall56ca35d2011-02-17 10:25:35 +00006775 case Expr::BinaryConditionalOperatorClass: {
6776 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6777 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6778 if (CommonResult.Val == 2) return CommonResult;
6779 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6780 if (FalseResult.Val == 2) return FalseResult;
6781 if (CommonResult.Val == 1) return CommonResult;
6782 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006783 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006784 return FalseResult;
6785 }
John McCalld905f5a2010-05-07 05:32:02 +00006786 case Expr::ConditionalOperatorClass: {
6787 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6788 // If the condition (ignoring parens) is a __builtin_constant_p call,
6789 // then only the true side is actually considered in an integer constant
6790 // expression, and it is fully evaluated. This is an important GNU
6791 // extension. See GCC PR38377 for discussion.
6792 if (const CallExpr *CallCE
6793 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006794 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6795 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006796 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006797 if (CondResult.Val == 2)
6798 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006799
Richard Smithf48fdb02011-12-09 22:58:01 +00006800 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6801 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006802
John McCalld905f5a2010-05-07 05:32:02 +00006803 if (TrueResult.Val == 2)
6804 return TrueResult;
6805 if (FalseResult.Val == 2)
6806 return FalseResult;
6807 if (CondResult.Val == 1)
6808 return CondResult;
6809 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6810 return NoDiag();
6811 // Rare case where the diagnostics depend on which side is evaluated
6812 // Note that if we get here, CondResult is 0, and at least one of
6813 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006814 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006815 return FalseResult;
6816 }
6817 return TrueResult;
6818 }
6819 case Expr::CXXDefaultArgExprClass:
6820 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6821 case Expr::ChooseExprClass: {
6822 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6823 }
6824 }
6825
David Blaikie30263482012-01-20 21:50:17 +00006826 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006827}
6828
Richard Smithf48fdb02011-12-09 22:58:01 +00006829/// Evaluate an expression as a C++11 integral constant expression.
6830static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6831 const Expr *E,
6832 llvm::APSInt *Value,
6833 SourceLocation *Loc) {
6834 if (!E->getType()->isIntegralOrEnumerationType()) {
6835 if (Loc) *Loc = E->getExprLoc();
6836 return false;
6837 }
6838
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006839 APValue Result;
6840 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006841 return false;
6842
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006843 assert(Result.isInt() && "pointer cast to int is not an ICE");
6844 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006845 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006846}
6847
Richard Smithdd1f29b2011-12-12 09:28:41 +00006848bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006849 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006850 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6851
John McCalld905f5a2010-05-07 05:32:02 +00006852 ICEDiag d = CheckICE(this, Ctx);
6853 if (d.Val != 0) {
6854 if (Loc) *Loc = d.Loc;
6855 return false;
6856 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006857 return true;
6858}
6859
6860bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6861 SourceLocation *Loc, bool isEvaluated) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006862 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006863 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6864
6865 if (!isIntegerConstantExpr(Ctx, Loc))
6866 return false;
6867 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006868 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006869 return true;
6870}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006871
Richard Smith70488e22012-02-14 21:38:30 +00006872bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6873 return CheckICE(this, Ctx).Val == 0;
6874}
6875
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006876bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6877 SourceLocation *Loc) const {
6878 // We support this checking in C++98 mode in order to diagnose compatibility
6879 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006880 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006881
Richard Smith70488e22012-02-14 21:38:30 +00006882 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006883 Expr::EvalStatus Status;
6884 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6885 Status.Diag = &Diags;
6886 EvalInfo Info(Ctx, Status);
6887
6888 APValue Scratch;
6889 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6890
6891 if (!Diags.empty()) {
6892 IsConstExpr = false;
6893 if (Loc) *Loc = Diags[0].first;
6894 } else if (!IsConstExpr) {
6895 // FIXME: This shouldn't happen.
6896 if (Loc) *Loc = getExprLoc();
6897 }
6898
6899 return IsConstExpr;
6900}
Richard Smith745f5142012-01-27 01:14:48 +00006901
6902bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6903 llvm::SmallVectorImpl<
6904 PartialDiagnosticAt> &Diags) {
6905 // FIXME: It would be useful to check constexpr function templates, but at the
6906 // moment the constant expression evaluator cannot cope with the non-rigorous
6907 // ASTs which we build for dependent expressions.
6908 if (FD->isDependentContext())
6909 return true;
6910
6911 Expr::EvalStatus Status;
6912 Status.Diag = &Diags;
6913
6914 EvalInfo Info(FD->getASTContext(), Status);
6915 Info.CheckingPotentialConstantExpression = true;
6916
6917 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6918 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6919
6920 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6921 // is a temporary being used as the 'this' pointer.
6922 LValue This;
6923 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006924 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006925
Richard Smith745f5142012-01-27 01:14:48 +00006926 ArrayRef<const Expr*> Args;
6927
6928 SourceLocation Loc = FD->getLocation();
6929
Richard Smith1aa0be82012-03-03 22:46:17 +00006930 APValue Scratch;
6931 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006932 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006933 else
Richard Smith745f5142012-01-27 01:14:48 +00006934 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6935 Args, FD->getBody(), Info, Scratch);
6936
6937 return Diags.empty();
6938}