blob: 8f3f84d07d7a5dca3a2e2d355b755510e2bbbe8d [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
Richard Smithbd552ef2011-10-31 05:52:43 +0000366 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000367 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000368 CallStackFrame BottomFrame;
369
Richard Smith180f4792011-11-10 06:34:14 +0000370 /// EvaluatingDecl - This is the declaration whose initializer is being
371 /// evaluated, if any.
372 const VarDecl *EvaluatingDecl;
373
374 /// EvaluatingDeclValue - This is the value being constructed for the
375 /// declaration whose initializer is being evaluated, if any.
376 APValue *EvaluatingDeclValue;
377
Richard Smithc1c5f272011-12-13 06:39:58 +0000378 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
379 /// notes attached to it will also be stored, otherwise they will not be.
380 bool HasActiveDiagnostic;
381
Richard Smith745f5142012-01-27 01:14:48 +0000382 /// CheckingPotentialConstantExpression - Are we checking whether the
383 /// expression is a potential constant expression? If so, some diagnostics
384 /// are suppressed.
385 bool CheckingPotentialConstantExpression;
386
Richard Smithbd552ef2011-10-31 05:52:43 +0000387 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000388 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000389 CallStackDepth(0), NextCallIndex(1),
390 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000391 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Argyrios Kyrtzidis649dfbc2012-03-15 18:07:13 +0000392 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000393
Richard Smith180f4792011-11-10 06:34:14 +0000394 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
395 EvaluatingDecl = VD;
396 EvaluatingDeclValue = &Value;
397 }
398
David Blaikie4e4d0842012-03-11 07:00:24 +0000399 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000400
Richard Smithc1c5f272011-12-13 06:39:58 +0000401 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000402 // Don't perform any constexpr calls (other than the call we're checking)
403 // when checking a potential constant expression.
404 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
405 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000406 if (NextCallIndex == 0) {
407 // NextCallIndex has wrapped around.
408 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
409 return false;
410 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000411 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
412 return true;
413 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
414 << getLangOpts().ConstexprCallDepth;
415 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000416 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000417
Richard Smith83587db2012-02-15 02:18:13 +0000418 CallStackFrame *getCallFrame(unsigned CallIndex) {
419 assert(CallIndex && "no call index in getCallFrame");
420 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
421 // be null in this loop.
422 CallStackFrame *Frame = CurrentCall;
423 while (Frame->Index > CallIndex)
424 Frame = Frame->Caller;
425 return (Frame->Index == CallIndex) ? Frame : 0;
426 }
427
Richard Smithc1c5f272011-12-13 06:39:58 +0000428 private:
429 /// Add a diagnostic to the diagnostics list.
430 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
431 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
432 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
433 return EvalStatus.Diag->back().second;
434 }
435
Richard Smith08d6e032011-12-16 19:06:07 +0000436 /// Add notes containing a call stack to the current point of evaluation.
437 void addCallStack(unsigned Limit);
438
Richard Smithc1c5f272011-12-13 06:39:58 +0000439 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000440 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000441 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
442 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000443 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000444 // If we have a prior diagnostic, it will be noting that the expression
445 // isn't a constant expression. This diagnostic is more important.
446 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000447 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000448 unsigned CallStackNotes = CallStackDepth - 1;
449 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
450 if (Limit)
451 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000452 if (CheckingPotentialConstantExpression)
453 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000454
Richard Smithc1c5f272011-12-13 06:39:58 +0000455 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000456 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000457 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
458 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000459 if (!CheckingPotentialConstantExpression)
460 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000461 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000462 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000463 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000464 return OptionalDiagnostic();
465 }
466
Richard Smith5cfc7d82012-03-15 04:53:45 +0000467 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
468 = diag::note_invalid_subexpr_in_const_expr,
469 unsigned ExtraNotes = 0) {
470 if (EvalStatus.Diag)
471 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
472 HasActiveDiagnostic = false;
473 return OptionalDiagnostic();
474 }
475
Richard Smithdd1f29b2011-12-12 09:28:41 +0000476 /// Diagnose that the evaluation does not produce a C++11 core constant
477 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000478 template<typename LocArg>
479 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000480 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000481 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000482 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000483 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
484 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000485 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000486 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000487 return Diag(Loc, DiagId, ExtraNotes);
488 }
489
490 /// Add a note to a prior diagnostic.
491 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
492 if (!HasActiveDiagnostic)
493 return OptionalDiagnostic();
494 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000495 }
Richard Smith099e7f62011-12-19 06:19:21 +0000496
497 /// Add a stack of notes to a prior diagnostic.
498 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
499 if (HasActiveDiagnostic) {
500 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
501 Diags.begin(), Diags.end());
502 }
503 }
Richard Smith745f5142012-01-27 01:14:48 +0000504
505 /// Should we continue evaluation as much as possible after encountering a
506 /// construct which can't be folded?
507 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000508 return CheckingPotentialConstantExpression &&
509 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000510 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000511 };
Richard Smithf15fda02012-02-02 01:16:57 +0000512
513 /// Object used to treat all foldable expressions as constant expressions.
514 struct FoldConstant {
515 bool Enabled;
516
517 explicit FoldConstant(EvalInfo &Info)
518 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
519 !Info.EvalStatus.HasSideEffects) {
520 }
521 // Treat the value we've computed since this object was created as constant.
522 void Fold(EvalInfo &Info) {
523 if (Enabled && !Info.EvalStatus.Diag->empty() &&
524 !Info.EvalStatus.HasSideEffects)
525 Info.EvalStatus.Diag->clear();
526 }
527 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000528
529 /// RAII object used to suppress diagnostics and side-effects from a
530 /// speculative evaluation.
531 class SpeculativeEvaluationRAII {
532 EvalInfo &Info;
533 Expr::EvalStatus Old;
534
535 public:
536 SpeculativeEvaluationRAII(EvalInfo &Info,
537 llvm::SmallVectorImpl<PartialDiagnosticAt>
538 *NewDiag = 0)
539 : Info(Info), Old(Info.EvalStatus) {
540 Info.EvalStatus.Diag = NewDiag;
541 }
542 ~SpeculativeEvaluationRAII() {
543 Info.EvalStatus = Old;
544 }
545 };
Richard Smith08d6e032011-12-16 19:06:07 +0000546}
Richard Smithbd552ef2011-10-31 05:52:43 +0000547
Richard Smithb4e85ed2012-01-06 16:39:00 +0000548bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
549 CheckSubobjectKind CSK) {
550 if (Invalid)
551 return false;
552 if (isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000553 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000554 << CSK;
555 setInvalid();
556 return false;
557 }
558 return true;
559}
560
561void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
562 const Expr *E, uint64_t N) {
563 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000564 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000565 << static_cast<int>(N) << /*array*/ 0
566 << static_cast<unsigned>(MostDerivedArraySize);
567 else
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) << /*non-array*/ 1;
570 setInvalid();
571}
572
Richard Smith08d6e032011-12-16 19:06:07 +0000573CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
574 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000575 const APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000576 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000577 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000578 Info.CurrentCall = this;
579 ++Info.CallStackDepth;
580}
581
582CallStackFrame::~CallStackFrame() {
583 assert(Info.CurrentCall == this && "calls retired out of order");
584 --Info.CallStackDepth;
585 Info.CurrentCall = Caller;
586}
587
588/// Produce a string describing the given constexpr call.
589static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
590 unsigned ArgIndex = 0;
591 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000592 !isa<CXXConstructorDecl>(Frame->Callee) &&
593 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000594
595 if (!IsMemberCall)
596 Out << *Frame->Callee << '(';
597
598 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
599 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000600 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000601 Out << ", ";
602
603 const ParmVarDecl *Param = *I;
Richard Smith1aa0be82012-03-03 22:46:17 +0000604 const APValue &Arg = Frame->Arguments[ArgIndex];
605 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smith08d6e032011-12-16 19:06:07 +0000606
607 if (ArgIndex == 0 && IsMemberCall)
608 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000609 }
610
Richard Smith08d6e032011-12-16 19:06:07 +0000611 Out << ')';
612}
613
614void EvalInfo::addCallStack(unsigned Limit) {
615 // Determine which calls to skip, if any.
616 unsigned ActiveCalls = CallStackDepth - 1;
617 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
618 if (Limit && Limit < ActiveCalls) {
619 SkipStart = Limit / 2 + Limit % 2;
620 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000621 }
622
Richard Smith08d6e032011-12-16 19:06:07 +0000623 // Walk the call stack and add the diagnostics.
624 unsigned CallIdx = 0;
625 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
626 Frame = Frame->Caller, ++CallIdx) {
627 // Skip this call?
628 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
629 if (CallIdx == SkipStart) {
630 // Note that we're skipping calls.
631 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
632 << unsigned(ActiveCalls - Limit);
633 }
634 continue;
635 }
636
637 llvm::SmallVector<char, 128> Buffer;
638 llvm::raw_svector_ostream Out(Buffer);
639 describeCall(Frame, Out);
640 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
641 }
642}
643
644namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000645 struct ComplexValue {
646 private:
647 bool IsInt;
648
649 public:
650 APSInt IntReal, IntImag;
651 APFloat FloatReal, FloatImag;
652
653 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
654
655 void makeComplexFloat() { IsInt = false; }
656 bool isComplexFloat() const { return !IsInt; }
657 APFloat &getComplexFloatReal() { return FloatReal; }
658 APFloat &getComplexFloatImag() { return FloatImag; }
659
660 void makeComplexInt() { IsInt = true; }
661 bool isComplexInt() const { return IsInt; }
662 APSInt &getComplexIntReal() { return IntReal; }
663 APSInt &getComplexIntImag() { return IntImag; }
664
Richard Smith1aa0be82012-03-03 22:46:17 +0000665 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000666 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000667 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000668 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000669 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000670 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000671 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000672 assert(v.isComplexFloat() || v.isComplexInt());
673 if (v.isComplexFloat()) {
674 makeComplexFloat();
675 FloatReal = v.getComplexFloatReal();
676 FloatImag = v.getComplexFloatImag();
677 } else {
678 makeComplexInt();
679 IntReal = v.getComplexIntReal();
680 IntImag = v.getComplexIntImag();
681 }
682 }
John McCallf4cf1a12010-05-07 17:22:02 +0000683 };
John McCallefdb83e2010-05-07 21:00:08 +0000684
685 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000686 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000687 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000688 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000689 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000690
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000691 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000692 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000693 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000694 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000695 SubobjectDesignator &getLValueDesignator() { return Designator; }
696 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000697
Richard Smith1aa0be82012-03-03 22:46:17 +0000698 void moveInto(APValue &V) const {
699 if (Designator.Invalid)
700 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
701 else
702 V = APValue(Base, Offset, Designator.Entries,
703 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000704 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000705 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000706 assert(V.isLValue());
707 Base = V.getLValueBase();
708 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000709 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000710 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000711 }
712
Richard Smith83587db2012-02-15 02:18:13 +0000713 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000714 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000715 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000716 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000717 Designator = SubobjectDesignator(getType(B));
718 }
719
720 // Check that this LValue is not based on a null pointer. If it is, produce
721 // a diagnostic and mark the designator as invalid.
722 bool checkNullPointer(EvalInfo &Info, const Expr *E,
723 CheckSubobjectKind CSK) {
724 if (Designator.Invalid)
725 return false;
726 if (!Base) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000727 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000728 << CSK;
729 Designator.setInvalid();
730 return false;
731 }
732 return true;
733 }
734
735 // Check this LValue refers to an object. If not, set the designator to be
736 // invalid and emit a diagnostic.
737 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000738 // Outside C++11, do not build a designator referring to a subobject of
739 // any object: we won't use such a designator for anything.
740 if (!Info.getLangOpts().CPlusPlus0x)
741 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000742 return checkNullPointer(Info, E, CSK) &&
743 Designator.checkSubobject(Info, E, CSK);
744 }
745
746 void addDecl(EvalInfo &Info, const Expr *E,
747 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000748 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
749 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000750 }
751 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000752 if (checkSubobject(Info, E, CSK_ArrayToPointer))
753 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000754 }
Richard Smith86024012012-02-18 22:04:06 +0000755 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000756 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
757 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000758 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000759 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000760 if (checkNullPointer(Info, E, CSK_ArrayIndex))
761 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000762 }
John McCallefdb83e2010-05-07 21:00:08 +0000763 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000764
765 struct MemberPtr {
766 MemberPtr() {}
767 explicit MemberPtr(const ValueDecl *Decl) :
768 DeclAndIsDerivedMember(Decl, false), Path() {}
769
770 /// The member or (direct or indirect) field referred to by this member
771 /// pointer, or 0 if this is a null member pointer.
772 const ValueDecl *getDecl() const {
773 return DeclAndIsDerivedMember.getPointer();
774 }
775 /// Is this actually a member of some type derived from the relevant class?
776 bool isDerivedMember() const {
777 return DeclAndIsDerivedMember.getInt();
778 }
779 /// Get the class which the declaration actually lives in.
780 const CXXRecordDecl *getContainingRecord() const {
781 return cast<CXXRecordDecl>(
782 DeclAndIsDerivedMember.getPointer()->getDeclContext());
783 }
784
Richard Smith1aa0be82012-03-03 22:46:17 +0000785 void moveInto(APValue &V) const {
786 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000787 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000788 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000789 assert(V.isMemberPointer());
790 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
791 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
792 Path.clear();
793 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
794 Path.insert(Path.end(), P.begin(), P.end());
795 }
796
797 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
798 /// whether the member is a member of some class derived from the class type
799 /// of the member pointer.
800 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
801 /// Path - The path of base/derived classes from the member declaration's
802 /// class (exclusive) to the class type of the member pointer (inclusive).
803 SmallVector<const CXXRecordDecl*, 4> Path;
804
805 /// Perform a cast towards the class of the Decl (either up or down the
806 /// hierarchy).
807 bool castBack(const CXXRecordDecl *Class) {
808 assert(!Path.empty());
809 const CXXRecordDecl *Expected;
810 if (Path.size() >= 2)
811 Expected = Path[Path.size() - 2];
812 else
813 Expected = getContainingRecord();
814 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
815 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
816 // if B does not contain the original member and is not a base or
817 // derived class of the class containing the original member, the result
818 // of the cast is undefined.
819 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
820 // (D::*). We consider that to be a language defect.
821 return false;
822 }
823 Path.pop_back();
824 return true;
825 }
826 /// Perform a base-to-derived member pointer cast.
827 bool castToDerived(const CXXRecordDecl *Derived) {
828 if (!getDecl())
829 return true;
830 if (!isDerivedMember()) {
831 Path.push_back(Derived);
832 return true;
833 }
834 if (!castBack(Derived))
835 return false;
836 if (Path.empty())
837 DeclAndIsDerivedMember.setInt(false);
838 return true;
839 }
840 /// Perform a derived-to-base member pointer cast.
841 bool castToBase(const CXXRecordDecl *Base) {
842 if (!getDecl())
843 return true;
844 if (Path.empty())
845 DeclAndIsDerivedMember.setInt(true);
846 if (isDerivedMember()) {
847 Path.push_back(Base);
848 return true;
849 }
850 return castBack(Base);
851 }
852 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000853
Richard Smithb02e4622012-02-01 01:42:44 +0000854 /// Compare two member pointers, which are assumed to be of the same type.
855 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
856 if (!LHS.getDecl() || !RHS.getDecl())
857 return !LHS.getDecl() && !RHS.getDecl();
858 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
859 return false;
860 return LHS.Path == RHS.Path;
861 }
862
Richard Smithc1c5f272011-12-13 06:39:58 +0000863 /// Kinds of constant expression checking, for diagnostics.
864 enum CheckConstantExpressionKind {
865 CCEK_Constant, ///< A normal constant.
866 CCEK_ReturnValue, ///< A constexpr function return value.
867 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
868 };
John McCallf4cf1a12010-05-07 17:22:02 +0000869}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000870
Richard Smith1aa0be82012-03-03 22:46:17 +0000871static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000872static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
873 const LValue &This, const Expr *E,
874 CheckConstantExpressionKind CCEK = CCEK_Constant,
875 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000876static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
877static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000878static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
879 EvalInfo &Info);
880static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000881static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000882static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000883 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000884static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000885static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000886
887//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000888// Misc utilities
889//===----------------------------------------------------------------------===//
890
Richard Smith180f4792011-11-10 06:34:14 +0000891/// Should this call expression be treated as a string literal?
892static bool IsStringLiteralCall(const CallExpr *E) {
893 unsigned Builtin = E->isBuiltinCall();
894 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
895 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
896}
897
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000898static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000899 // C++11 [expr.const]p3 An address constant expression is a prvalue core
900 // constant expression of pointer type that evaluates to...
901
902 // ... a null pointer value, or a prvalue core constant expression of type
903 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000904 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000905
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000906 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
907 // ... the address of an object with static storage duration,
908 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
909 return VD->hasGlobalStorage();
910 // ... the address of a function,
911 return isa<FunctionDecl>(D);
912 }
913
914 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000915 switch (E->getStmtClass()) {
916 default:
917 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000918 case Expr::CompoundLiteralExprClass: {
919 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
920 return CLE->isFileScope() && CLE->isLValue();
921 }
Richard Smith180f4792011-11-10 06:34:14 +0000922 // A string literal has static storage duration.
923 case Expr::StringLiteralClass:
924 case Expr::PredefinedExprClass:
925 case Expr::ObjCStringLiteralClass:
926 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000927 case Expr::CXXTypeidExprClass:
Francois Pichete275a182012-04-16 04:08:35 +0000928 case Expr::CXXUuidofExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000929 return true;
930 case Expr::CallExprClass:
931 return IsStringLiteralCall(cast<CallExpr>(E));
932 // For GCC compatibility, &&label has static storage duration.
933 case Expr::AddrLabelExprClass:
934 return true;
935 // A Block literal expression may be used as the initialization value for
936 // Block variables at global or local static scope.
937 case Expr::BlockExprClass:
938 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000939 case Expr::ImplicitValueInitExprClass:
940 // FIXME:
941 // We can never form an lvalue with an implicit value initialization as its
942 // base through expression evaluation, so these only appear in one case: the
943 // implicit variable declaration we invent when checking whether a constexpr
944 // constructor can produce a constant expression. We must assume that such
945 // an expression might be a global lvalue.
946 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000947 }
John McCall42c8f872010-05-10 23:27:23 +0000948}
949
Richard Smith83587db2012-02-15 02:18:13 +0000950static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
951 assert(Base && "no location for a null lvalue");
952 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
953 if (VD)
954 Info.Note(VD->getLocation(), diag::note_declared_at);
955 else
Ted Kremenek890f0f12012-08-23 20:46:57 +0000956 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smith83587db2012-02-15 02:18:13 +0000957 diag::note_constexpr_temporary_here);
958}
959
Richard Smith9a17a682011-11-07 05:07:52 +0000960/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000961/// value for an address or reference constant expression. Return true if we
962/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000963static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
964 QualType Type, const LValue &LVal) {
965 bool IsReferenceType = Type->isReferenceType();
966
Richard Smithc1c5f272011-12-13 06:39:58 +0000967 APValue::LValueBase Base = LVal.getLValueBase();
968 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
969
Richard Smithb78ae972012-02-18 04:58:18 +0000970 // Check that the object is a global. Note that the fake 'this' object we
971 // manufacture when checking potential constant expressions is conservatively
972 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000973 if (!IsGlobalLValue(Base)) {
974 if (Info.getLangOpts().CPlusPlus0x) {
975 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000976 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
977 << IsReferenceType << !Designator.Entries.empty()
978 << !!VD << VD;
979 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000980 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000981 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000982 }
Richard Smith61e61622012-01-12 06:08:57 +0000983 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000984 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000985 }
Richard Smith83587db2012-02-15 02:18:13 +0000986 assert((Info.CheckingPotentialConstantExpression ||
987 LVal.getLValueCallIndex() == 0) &&
988 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +0000989
Hans Wennborg48def652012-08-29 18:27:29 +0000990 // Check if this is a thread-local variable.
991 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
992 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
993 if (Var->isThreadSpecified())
994 return false;
995 }
996 }
997
Richard Smithb4e85ed2012-01-06 16:39:00 +0000998 // Allow address constant expressions to be past-the-end pointers. This is
999 // an extension: the standard requires them to point to an object.
1000 if (!IsReferenceType)
1001 return true;
1002
1003 // A reference constant expression must refer to an object.
1004 if (!Base) {
1005 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001006 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001007 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001008 }
1009
Richard Smithc1c5f272011-12-13 06:39:58 +00001010 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001011 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001012 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001013 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001014 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001015 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001016 }
1017
Richard Smith9a17a682011-11-07 05:07:52 +00001018 return true;
1019}
1020
Richard Smith51201882011-12-30 21:15:51 +00001021/// Check that this core constant expression is of literal type, and if not,
1022/// produce an appropriate diagnostic.
1023static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1024 if (!E->isRValue() || E->getType()->isLiteralType())
1025 return true;
1026
1027 // Prvalue constant expressions must be of literal types.
1028 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001029 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001030 << E->getType();
1031 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001032 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001033 return false;
1034}
1035
Richard Smith47a1eed2011-10-29 20:57:55 +00001036/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001037/// constant expression. If not, report an appropriate diagnostic. Does not
1038/// check that the expression is of literal type.
1039static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1040 QualType Type, const APValue &Value) {
1041 // Core issue 1454: For a literal constant expression of array or class type,
1042 // each subobject of its value shall have been initialized by a constant
1043 // expression.
1044 if (Value.isArray()) {
1045 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1046 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1047 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1048 Value.getArrayInitializedElt(I)))
1049 return false;
1050 }
1051 if (!Value.hasArrayFiller())
1052 return true;
1053 return CheckConstantExpression(Info, DiagLoc, EltTy,
1054 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001055 }
Richard Smith83587db2012-02-15 02:18:13 +00001056 if (Value.isUnion() && Value.getUnionField()) {
1057 return CheckConstantExpression(Info, DiagLoc,
1058 Value.getUnionField()->getType(),
1059 Value.getUnionValue());
1060 }
1061 if (Value.isStruct()) {
1062 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1063 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1064 unsigned BaseIndex = 0;
1065 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1066 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1067 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1068 Value.getStructBase(BaseIndex)))
1069 return false;
1070 }
1071 }
1072 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1073 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001074 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1075 Value.getStructField(I->getFieldIndex())))
Richard Smith83587db2012-02-15 02:18:13 +00001076 return false;
1077 }
1078 }
1079
1080 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001081 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001082 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001083 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1084 }
1085
1086 // Everything else is fine.
1087 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001088}
1089
Richard Smith9e36b532011-10-31 05:11:32 +00001090const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001091 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001092}
1093
1094static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001095 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001096}
1097
Richard Smith65ac5982011-11-01 21:06:14 +00001098static bool IsWeakLValue(const LValue &Value) {
1099 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001100 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001101}
1102
Richard Smith1aa0be82012-03-03 22:46:17 +00001103static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001104 // A null base expression indicates a null pointer. These are always
1105 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001106 if (!Value.getLValueBase()) {
1107 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001108 return true;
1109 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001110
Richard Smithe24f5fc2011-11-17 22:56:20 +00001111 // We have a non-null base. These are generally known to be true, but if it's
1112 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001113 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001114 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001115 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001116}
1117
Richard Smith1aa0be82012-03-03 22:46:17 +00001118static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001119 switch (Val.getKind()) {
1120 case APValue::Uninitialized:
1121 return false;
1122 case APValue::Int:
1123 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001124 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001125 case APValue::Float:
1126 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001127 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001128 case APValue::ComplexInt:
1129 Result = Val.getComplexIntReal().getBoolValue() ||
1130 Val.getComplexIntImag().getBoolValue();
1131 return true;
1132 case APValue::ComplexFloat:
1133 Result = !Val.getComplexFloatReal().isZero() ||
1134 !Val.getComplexFloatImag().isZero();
1135 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001136 case APValue::LValue:
1137 return EvalPointerValueAsBool(Val, Result);
1138 case APValue::MemberPointer:
1139 Result = Val.getMemberPointerDecl();
1140 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001141 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001142 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001143 case APValue::Struct:
1144 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001145 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001146 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001147 }
1148
Richard Smithc49bd112011-10-28 17:51:58 +00001149 llvm_unreachable("unknown APValue kind");
1150}
1151
1152static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1153 EvalInfo &Info) {
1154 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001155 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001156 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001157 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001158 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001159}
1160
Richard Smithc1c5f272011-12-13 06:39:58 +00001161template<typename T>
Eli Friedman26dc97c2012-07-17 21:03:05 +00001162static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +00001163 const T &SrcValue, QualType DestType) {
Eli Friedman26dc97c2012-07-17 21:03:05 +00001164 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001165 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001166}
1167
1168static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1169 QualType SrcType, const APFloat &Value,
1170 QualType DestType, APSInt &Result) {
1171 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001172 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001173 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Richard Smithc1c5f272011-12-13 06:39:58 +00001175 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001176 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001177 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1178 & APFloat::opInvalidOp)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001179 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001180 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001181}
1182
Richard Smithc1c5f272011-12-13 06:39:58 +00001183static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1184 QualType SrcType, QualType DestType,
1185 APFloat &Result) {
1186 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001187 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001188 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1189 APFloat::rmNearestTiesToEven, &ignored)
1190 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001191 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001192 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001193}
1194
Richard Smithf72fccf2012-01-30 22:27:01 +00001195static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1196 QualType DestType, QualType SrcType,
1197 APSInt &Value) {
1198 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001199 APSInt Result = Value;
1200 // Figure out if this is a truncate, extend or noop cast.
1201 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001202 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001203 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001204 return Result;
1205}
1206
Richard Smithc1c5f272011-12-13 06:39:58 +00001207static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1208 QualType SrcType, const APSInt &Value,
1209 QualType DestType, APFloat &Result) {
1210 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1211 if (Result.convertFromAPInt(Value, Value.isSigned(),
1212 APFloat::rmNearestTiesToEven)
1213 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001214 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001215 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001216}
1217
Eli Friedmane6a24e82011-12-22 03:51:45 +00001218static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1219 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001220 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001221 if (!Evaluate(SVal, Info, E))
1222 return false;
1223 if (SVal.isInt()) {
1224 Res = SVal.getInt();
1225 return true;
1226 }
1227 if (SVal.isFloat()) {
1228 Res = SVal.getFloat().bitcastToAPInt();
1229 return true;
1230 }
1231 if (SVal.isVector()) {
1232 QualType VecTy = E->getType();
1233 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1234 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1235 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1236 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1237 Res = llvm::APInt::getNullValue(VecSize);
1238 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1239 APValue &Elt = SVal.getVectorElt(i);
1240 llvm::APInt EltAsInt;
1241 if (Elt.isInt()) {
1242 EltAsInt = Elt.getInt();
1243 } else if (Elt.isFloat()) {
1244 EltAsInt = Elt.getFloat().bitcastToAPInt();
1245 } else {
1246 // Don't try to handle vectors of anything other than int or float
1247 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001248 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001249 return false;
1250 }
1251 unsigned BaseEltSize = EltAsInt.getBitWidth();
1252 if (BigEndian)
1253 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1254 else
1255 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1256 }
1257 return true;
1258 }
1259 // Give up if the input isn't an int, float, or vector. For example, we
1260 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001261 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001262 return false;
1263}
1264
Richard Smithb4e85ed2012-01-06 16:39:00 +00001265/// Cast an lvalue referring to a base subobject to a derived class, by
1266/// truncating the lvalue's path to the given length.
1267static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1268 const RecordDecl *TruncatedType,
1269 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001270 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001271
1272 // Check we actually point to a derived class object.
1273 if (TruncatedElements == D.Entries.size())
1274 return true;
1275 assert(TruncatedElements >= D.MostDerivedPathLength &&
1276 "not casting to a derived class");
1277 if (!Result.checkSubobject(Info, E, CSK_Derived))
1278 return false;
1279
1280 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001281 const RecordDecl *RD = TruncatedType;
1282 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCall8d59dee2012-05-01 00:38:49 +00001283 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001284 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1285 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001286 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001287 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001288 else
Richard Smith180f4792011-11-10 06:34:14 +00001289 Result.Offset -= Layout.getBaseClassOffset(Base);
1290 RD = Base;
1291 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001292 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001293 return true;
1294}
1295
John McCall8d59dee2012-05-01 00:38:49 +00001296static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001297 const CXXRecordDecl *Derived,
1298 const CXXRecordDecl *Base,
1299 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001300 if (!RL) {
1301 if (Derived->isInvalidDecl()) return false;
1302 RL = &Info.Ctx.getASTRecordLayout(Derived);
1303 }
1304
Richard Smith180f4792011-11-10 06:34:14 +00001305 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001306 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCall8d59dee2012-05-01 00:38:49 +00001307 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001308}
1309
Richard Smithb4e85ed2012-01-06 16:39:00 +00001310static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001311 const CXXRecordDecl *DerivedDecl,
1312 const CXXBaseSpecifier *Base) {
1313 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1314
John McCall8d59dee2012-05-01 00:38:49 +00001315 if (!Base->isVirtual())
1316 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001317
Richard Smithb4e85ed2012-01-06 16:39:00 +00001318 SubobjectDesignator &D = Obj.Designator;
1319 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001320 return false;
1321
Richard Smithb4e85ed2012-01-06 16:39:00 +00001322 // Extract most-derived object and corresponding type.
1323 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1324 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1325 return false;
1326
1327 // Find the virtual base class.
John McCall8d59dee2012-05-01 00:38:49 +00001328 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001329 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1330 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001331 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001332 return true;
1333}
1334
1335/// Update LVal to refer to the given field, which must be a member of the type
1336/// currently described by LVal.
John McCall8d59dee2012-05-01 00:38:49 +00001337static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001338 const FieldDecl *FD,
1339 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001340 if (!RL) {
1341 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001342 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCall8d59dee2012-05-01 00:38:49 +00001343 }
Richard Smith180f4792011-11-10 06:34:14 +00001344
1345 unsigned I = FD->getFieldIndex();
1346 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001347 LVal.addDecl(Info, E, FD);
John McCall8d59dee2012-05-01 00:38:49 +00001348 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001349}
1350
Richard Smithd9b02e72012-01-25 22:15:11 +00001351/// Update LVal to refer to the given indirect field.
John McCall8d59dee2012-05-01 00:38:49 +00001352static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smithd9b02e72012-01-25 22:15:11 +00001353 LValue &LVal,
1354 const IndirectFieldDecl *IFD) {
1355 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1356 CE = IFD->chain_end(); C != CE; ++C)
John McCall8d59dee2012-05-01 00:38:49 +00001357 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1358 return false;
1359 return true;
Richard Smithd9b02e72012-01-25 22:15:11 +00001360}
1361
Richard Smith180f4792011-11-10 06:34:14 +00001362/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001363static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1364 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001365 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1366 // extension.
1367 if (Type->isVoidType() || Type->isFunctionType()) {
1368 Size = CharUnits::One();
1369 return true;
1370 }
1371
1372 if (!Type->isConstantSizeType()) {
1373 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001374 // FIXME: Better diagnostic.
1375 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001376 return false;
1377 }
1378
1379 Size = Info.Ctx.getTypeSizeInChars(Type);
1380 return true;
1381}
1382
1383/// Update a pointer value to model pointer arithmetic.
1384/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001385/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001386/// \param LVal - The pointer value to be updated.
1387/// \param EltTy - The pointee type represented by LVal.
1388/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001389static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1390 LValue &LVal, QualType EltTy,
1391 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001392 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001393 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001394 return false;
1395
1396 // Compute the new offset in the appropriate width.
1397 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001398 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001399 return true;
1400}
1401
Richard Smith86024012012-02-18 22:04:06 +00001402/// Update an lvalue to refer to a component of a complex number.
1403/// \param Info - Information about the ongoing evaluation.
1404/// \param LVal - The lvalue to be updated.
1405/// \param EltTy - The complex number's component type.
1406/// \param Imag - False for the real component, true for the imaginary.
1407static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1408 LValue &LVal, QualType EltTy,
1409 bool Imag) {
1410 if (Imag) {
1411 CharUnits SizeOfComponent;
1412 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1413 return false;
1414 LVal.Offset += SizeOfComponent;
1415 }
1416 LVal.addComplex(Info, E, EltTy, Imag);
1417 return true;
1418}
1419
Richard Smith03f96112011-10-24 17:54:18 +00001420/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001421static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1422 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001423 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001424 // If this is a parameter to an active constexpr function call, perform
1425 // argument substitution.
1426 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001427 // Assume arguments of a potential constant expression are unknown
1428 // constant expressions.
1429 if (Info.CheckingPotentialConstantExpression)
1430 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001431 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001432 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001433 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001434 }
Richard Smith177dce72011-11-01 16:57:24 +00001435 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1436 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001437 }
Richard Smith03f96112011-10-24 17:54:18 +00001438
Richard Smith099e7f62011-12-19 06:19:21 +00001439 // Dig out the initializer, and use the declaration which it's attached to.
1440 const Expr *Init = VD->getAnyInitializer(VD);
1441 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001442 // If we're checking a potential constant expression, the variable could be
1443 // initialized later.
1444 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001445 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001446 return false;
1447 }
1448
Richard Smith180f4792011-11-10 06:34:14 +00001449 // If we're currently evaluating the initializer of this declaration, use that
1450 // in-flight value.
1451 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001452 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001453 return !Result.isUninit();
1454 }
1455
Richard Smith65ac5982011-11-01 21:06:14 +00001456 // Never evaluate the initializer of a weak variable. We can't be sure that
1457 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001458 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001459 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001460 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001461 }
Richard Smith65ac5982011-11-01 21:06:14 +00001462
Richard Smith099e7f62011-12-19 06:19:21 +00001463 // Check that we can fold the initializer. In C++, we will have already done
1464 // this in the cases where it matters for conformance.
1465 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1466 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001467 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001468 Notes.size() + 1) << VD;
1469 Info.Note(VD->getLocation(), diag::note_declared_at);
1470 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001471 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001472 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001473 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001474 Notes.size() + 1) << VD;
1475 Info.Note(VD->getLocation(), diag::note_declared_at);
1476 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001477 }
Richard Smith03f96112011-10-24 17:54:18 +00001478
Richard Smith1aa0be82012-03-03 22:46:17 +00001479 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001480 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001481}
1482
Richard Smithc49bd112011-10-28 17:51:58 +00001483static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001484 Qualifiers Quals = T.getQualifiers();
1485 return Quals.hasConst() && !Quals.hasVolatile();
1486}
1487
Richard Smith59efe262011-11-11 04:05:33 +00001488/// Get the base index of the given base class within an APValue representing
1489/// the given derived class.
1490static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1491 const CXXRecordDecl *Base) {
1492 Base = Base->getCanonicalDecl();
1493 unsigned Index = 0;
1494 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1495 E = Derived->bases_end(); I != E; ++I, ++Index) {
1496 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1497 return Index;
1498 }
1499
1500 llvm_unreachable("base class missing from derived class's bases list");
1501}
1502
Richard Smithfe587202012-04-15 02:50:59 +00001503/// Extract the value of a character from a string literal. CharType is used to
1504/// determine the expected signedness of the result -- a string literal used to
1505/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1506/// of the wrong signedness.
Richard Smithf3908f22012-02-17 03:35:37 +00001507static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smithfe587202012-04-15 02:50:59 +00001508 uint64_t Index, QualType CharType) {
Richard Smithf3908f22012-02-17 03:35:37 +00001509 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1510 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1511 assert(S && "unexpected string literal expression kind");
Richard Smithfe587202012-04-15 02:50:59 +00001512 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smithf3908f22012-02-17 03:35:37 +00001513
1514 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smithfe587202012-04-15 02:50:59 +00001515 CharType->isUnsignedIntegerType());
Richard Smithf3908f22012-02-17 03:35:37 +00001516 if (Index < S->getLength())
1517 Value = S->getCodeUnit(Index);
1518 return Value;
1519}
1520
Richard Smithcc5d4f62011-11-07 09:22:26 +00001521/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001522static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001523 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001524 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001525 if (Sub.Invalid)
1526 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001527 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001528 if (Sub.isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001529 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001530 (unsigned)diag::note_constexpr_read_past_end :
1531 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001532 return false;
1533 }
Richard Smithf64699e2011-11-11 08:28:03 +00001534 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001535 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001536 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1537 // This object might be initialized later.
1538 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001539
Richard Smith0069b842012-03-10 00:28:11 +00001540 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001541 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001542 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001543 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001544 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001545 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001546 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001547 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001548 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001549 // Note, it should not be possible to form a pointer with a valid
1550 // designator which points more than one past the end of the array.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001551 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001552 (unsigned)diag::note_constexpr_read_past_end :
1553 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001554 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001555 }
Richard Smithf3908f22012-02-17 03:35:37 +00001556 // An array object is represented as either an Array APValue or as an
1557 // LValue which refers to a string literal.
1558 if (O->isLValue()) {
1559 assert(I == N - 1 && "extracting subobject of character?");
1560 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001561 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithfe587202012-04-15 02:50:59 +00001562 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smithf3908f22012-02-17 03:35:37 +00001563 return true;
1564 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001565 O = &O->getArrayInitializedElt(Index);
1566 else
1567 O = &O->getArrayFiller();
1568 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001569 } else if (ObjType->isAnyComplexType()) {
1570 // Next subobject is a complex number.
1571 uint64_t Index = Sub.Entries[I].ArrayIndex;
1572 if (Index > 1) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001573 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Richard Smith86024012012-02-18 22:04:06 +00001574 (unsigned)diag::note_constexpr_read_past_end :
1575 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1576 return false;
1577 }
1578 assert(I == N - 1 && "extracting subobject of scalar?");
1579 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001580 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001581 : O->getComplexIntReal());
1582 } else {
1583 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001584 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001585 : O->getComplexFloatReal());
1586 }
1587 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001588 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001589 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001590 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001591 << Field;
1592 Info.Note(Field->getLocation(), diag::note_declared_at);
1593 return false;
1594 }
1595
Richard Smith180f4792011-11-10 06:34:14 +00001596 // Next subobject is a class, struct or union field.
1597 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1598 if (RD->isUnion()) {
1599 const FieldDecl *UnionField = O->getUnionField();
1600 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001601 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001602 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001603 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001604 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001605 }
Richard Smith180f4792011-11-10 06:34:14 +00001606 O = &O->getUnionValue();
1607 } else
1608 O = &O->getStructField(Field->getFieldIndex());
1609 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001610
1611 if (ObjType.isVolatileQualified()) {
1612 if (Info.getLangOpts().CPlusPlus) {
1613 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001614 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001615 << 2 << Field;
1616 Info.Note(Field->getLocation(), diag::note_declared_at);
1617 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001618 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001619 }
1620 return false;
1621 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001622 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001623 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001624 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1625 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1626 O = &O->getStructBase(getBaseIndex(Derived, Base));
1627 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001628 }
Richard Smith180f4792011-11-10 06:34:14 +00001629
Richard Smithf48fdb02011-12-09 22:58:01 +00001630 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001631 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001632 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001633 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001634 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001635 }
1636
Richard Smith0069b842012-03-10 00:28:11 +00001637 // This may look super-stupid, but it serves an important purpose: if we just
1638 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1639 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1640 // object, which is destroyed by Tmp's destructor.
1641 APValue Tmp;
1642 O->swap(Tmp);
1643 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001644 return true;
1645}
1646
Richard Smithf15fda02012-02-02 01:16:57 +00001647/// Find the position where two subobject designators diverge, or equivalently
1648/// the length of the common initial subsequence.
1649static unsigned FindDesignatorMismatch(QualType ObjType,
1650 const SubobjectDesignator &A,
1651 const SubobjectDesignator &B,
1652 bool &WasArrayIndex) {
1653 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1654 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001655 if (!ObjType.isNull() &&
1656 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001657 // Next subobject is an array element.
1658 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1659 WasArrayIndex = true;
1660 return I;
1661 }
Richard Smith86024012012-02-18 22:04:06 +00001662 if (ObjType->isAnyComplexType())
1663 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1664 else
1665 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001666 } else {
1667 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1668 WasArrayIndex = false;
1669 return I;
1670 }
1671 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1672 // Next subobject is a field.
1673 ObjType = FD->getType();
1674 else
1675 // Next subobject is a base class.
1676 ObjType = QualType();
1677 }
1678 }
1679 WasArrayIndex = false;
1680 return I;
1681}
1682
1683/// Determine whether the given subobject designators refer to elements of the
1684/// same array object.
1685static bool AreElementsOfSameArray(QualType ObjType,
1686 const SubobjectDesignator &A,
1687 const SubobjectDesignator &B) {
1688 if (A.Entries.size() != B.Entries.size())
1689 return false;
1690
1691 bool IsArray = A.MostDerivedArraySize != 0;
1692 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1693 // A is a subobject of the array element.
1694 return false;
1695
1696 // If A (and B) designates an array element, the last entry will be the array
1697 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1698 // of length 1' case, and the entire path must match.
1699 bool WasArrayIndex;
1700 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1701 return CommonLength >= A.Entries.size() - IsArray;
1702}
1703
Richard Smith180f4792011-11-10 06:34:14 +00001704/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1705/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1706/// for looking up the glvalue referred to by an entity of reference type.
1707///
1708/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001709/// \param Conv - The expression for which we are performing the conversion.
1710/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001711/// \param Type - The type we expect this conversion to produce, before
1712/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001713/// \param LVal - The glvalue on which we are attempting to perform this action.
1714/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001715static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1716 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001717 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001718 if (LVal.Designator.Invalid)
1719 // A diagnostic will have already been produced.
1720 return false;
1721
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001722 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001723
Richard Smithf48fdb02011-12-09 22:58:01 +00001724 if (!LVal.Base) {
1725 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001726 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001727 return false;
1728 }
1729
Richard Smith83587db2012-02-15 02:18:13 +00001730 CallStackFrame *Frame = 0;
1731 if (LVal.CallIndex) {
1732 Frame = Info.getCallFrame(LVal.CallIndex);
1733 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001734 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001735 NoteLValueLocation(Info, LVal.Base);
1736 return false;
1737 }
1738 }
1739
Richard Smith7098cbd2011-12-21 05:04:46 +00001740 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1741 // is not a constant expression (even if the object is non-volatile). We also
1742 // apply this rule to C++98, in order to conform to the expected 'volatile'
1743 // semantics.
1744 if (Type.isVolatileQualified()) {
1745 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001746 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001747 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001748 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001749 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001750 }
Richard Smithc49bd112011-10-28 17:51:58 +00001751
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001752 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001753 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1754 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001755 // expressions are constant expressions too. Inside constexpr functions,
1756 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001757 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001758 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregord2008e22012-04-06 22:40:38 +00001759 if (VD) {
1760 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1761 VD = VDef;
1762 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001763 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001764 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001765 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001766 }
1767
Richard Smith7098cbd2011-12-21 05:04:46 +00001768 // DR1313: If the object is volatile-qualified but the glvalue was not,
1769 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001770 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001771 if (VT.isVolatileQualified()) {
1772 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001773 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001774 Info.Note(VD->getLocation(), diag::note_declared_at);
1775 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001776 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001777 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001778 return false;
1779 }
1780
1781 if (!isa<ParmVarDecl>(VD)) {
1782 if (VD->isConstexpr()) {
1783 // OK, we can read this variable.
1784 } else if (VT->isIntegralOrEnumerationType()) {
1785 if (!VT.isConstQualified()) {
1786 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001787 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001788 Info.Note(VD->getLocation(), diag::note_declared_at);
1789 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001790 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001791 }
1792 return false;
1793 }
1794 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1795 // We support folding of const floating-point types, in order to make
1796 // static const data members of such types (supported as an extension)
1797 // more useful.
1798 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001799 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001800 Info.Note(VD->getLocation(), diag::note_declared_at);
1801 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001802 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001803 }
1804 } else {
1805 // FIXME: Allow folding of values of any literal type in all languages.
1806 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001807 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001808 Info.Note(VD->getLocation(), diag::note_declared_at);
1809 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001810 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001811 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001812 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001813 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001814 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001815
Richard Smithf48fdb02011-12-09 22:58:01 +00001816 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001817 return false;
1818
Richard Smith47a1eed2011-10-29 20:57:55 +00001819 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001820 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001821
1822 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1823 // conversion. This happens when the declaration and the lvalue should be
1824 // considered synonymous, for instance when initializing an array of char
1825 // from a string literal. Continue as if the initializer lvalue was the
1826 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001827 assert(RVal.getLValueOffset().isZero() &&
1828 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001829 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001830
1831 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1832 Frame = Info.getCallFrame(CallIndex);
1833 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001834 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001835 NoteLValueLocation(Info, RVal.getLValueBase());
1836 return false;
1837 }
1838 } else {
1839 Frame = 0;
1840 }
Richard Smithc49bd112011-10-28 17:51:58 +00001841 }
1842
Richard Smith7098cbd2011-12-21 05:04:46 +00001843 // Volatile temporary objects cannot be read in constant expressions.
1844 if (Base->getType().isVolatileQualified()) {
1845 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001846 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001847 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1848 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001849 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001850 }
1851 return false;
1852 }
1853
Richard Smithcc5d4f62011-11-07 09:22:26 +00001854 if (Frame) {
1855 // If this is a temporary expression with a nontrivial initializer, grab the
1856 // value from the relevant stack frame.
1857 RVal = Frame->Temporaries[Base];
1858 } else if (const CompoundLiteralExpr *CLE
1859 = dyn_cast<CompoundLiteralExpr>(Base)) {
1860 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1861 // initializer until now for such expressions. Such an expression can't be
1862 // an ICE in C, so this only matters for fold.
1863 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1864 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1865 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001866 } else if (isa<StringLiteral>(Base)) {
1867 // We represent a string literal array as an lvalue pointing at the
1868 // corresponding expression, rather than building an array of chars.
1869 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001870 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001871 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001872 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001873 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001874 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001875
Richard Smithf48fdb02011-12-09 22:58:01 +00001876 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1877 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001878}
1879
Richard Smith59efe262011-11-11 04:05:33 +00001880/// Build an lvalue for the object argument of a member function call.
1881static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1882 LValue &This) {
1883 if (Object->getType()->isPointerType())
1884 return EvaluatePointer(Object, This, Info);
1885
1886 if (Object->isGLValue())
1887 return EvaluateLValue(Object, This, Info);
1888
Richard Smithe24f5fc2011-11-17 22:56:20 +00001889 if (Object->getType()->isLiteralType())
1890 return EvaluateTemporary(Object, This, Info);
1891
1892 return false;
1893}
1894
1895/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1896/// lvalue referring to the result.
1897///
1898/// \param Info - Information about the ongoing evaluation.
1899/// \param BO - The member pointer access operation.
1900/// \param LV - Filled in with a reference to the resulting object.
1901/// \param IncludeMember - Specifies whether the member itself is included in
1902/// the resulting LValue subobject designator. This is not possible when
1903/// creating a bound member function.
1904/// \return The field or method declaration to which the member pointer refers,
1905/// or 0 if evaluation fails.
1906static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1907 const BinaryOperator *BO,
1908 LValue &LV,
1909 bool IncludeMember = true) {
1910 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1911
Richard Smith745f5142012-01-27 01:14:48 +00001912 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1913 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001914 return 0;
1915
1916 MemberPtr MemPtr;
1917 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1918 return 0;
1919
1920 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1921 // member value, the behavior is undefined.
1922 if (!MemPtr.getDecl())
1923 return 0;
1924
Richard Smith745f5142012-01-27 01:14:48 +00001925 if (!EvalObjOK)
1926 return 0;
1927
Richard Smithe24f5fc2011-11-17 22:56:20 +00001928 if (MemPtr.isDerivedMember()) {
1929 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001930 // The end of the derived-to-base path for the base object must match the
1931 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001932 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001933 LV.Designator.Entries.size())
1934 return 0;
1935 unsigned PathLengthToMember =
1936 LV.Designator.Entries.size() - MemPtr.Path.size();
1937 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1938 const CXXRecordDecl *LVDecl = getAsBaseClass(
1939 LV.Designator.Entries[PathLengthToMember + I]);
1940 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1941 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1942 return 0;
1943 }
1944
1945 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001946 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1947 PathLengthToMember))
1948 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001949 } else if (!MemPtr.Path.empty()) {
1950 // Extend the LValue path with the member pointer's path.
1951 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1952 MemPtr.Path.size() + IncludeMember);
1953
1954 // Walk down to the appropriate base class.
1955 QualType LVType = BO->getLHS()->getType();
1956 if (const PointerType *PT = LVType->getAs<PointerType>())
1957 LVType = PT->getPointeeType();
1958 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1959 assert(RD && "member pointer access on non-class-type expression");
1960 // The first class in the path is that of the lvalue.
1961 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1962 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCall8d59dee2012-05-01 00:38:49 +00001963 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1964 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001965 RD = Base;
1966 }
1967 // Finally cast to the class containing the member.
John McCall8d59dee2012-05-01 00:38:49 +00001968 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1969 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001970 }
1971
1972 // Add the member. Note that we cannot build bound member functions here.
1973 if (IncludeMember) {
John McCall8d59dee2012-05-01 00:38:49 +00001974 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
1975 if (!HandleLValueMember(Info, BO, LV, FD))
1976 return 0;
1977 } else if (const IndirectFieldDecl *IFD =
1978 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
1979 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
1980 return 0;
1981 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00001982 llvm_unreachable("can't construct reference to bound member function");
John McCall8d59dee2012-05-01 00:38:49 +00001983 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001984 }
1985
1986 return MemPtr.getDecl();
1987}
1988
1989/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1990/// the provided lvalue, which currently refers to the base object.
1991static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1992 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001993 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001994 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001995 return false;
1996
Richard Smithb4e85ed2012-01-06 16:39:00 +00001997 QualType TargetQT = E->getType();
1998 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1999 TargetQT = PT->getPointeeType();
2000
2001 // Check this cast lands within the final derived-to-base subobject path.
2002 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002003 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002004 << D.MostDerivedType << TargetQT;
2005 return false;
2006 }
2007
Richard Smithe24f5fc2011-11-17 22:56:20 +00002008 // Check the type of the final cast. We don't need to check the path,
2009 // since a cast can only be formed if the path is unique.
2010 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002011 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2012 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002013 if (NewEntriesSize == D.MostDerivedPathLength)
2014 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2015 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002016 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002017 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002018 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002019 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002020 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002021 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002022
2023 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002024 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002025}
2026
Mike Stumpc4c90452009-10-27 22:09:17 +00002027namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002028enum EvalStmtResult {
2029 /// Evaluation failed.
2030 ESR_Failed,
2031 /// Hit a 'return' statement.
2032 ESR_Returned,
2033 /// Evaluation succeeded.
2034 ESR_Succeeded
2035};
2036}
2037
2038// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002039static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002040 const Stmt *S) {
2041 switch (S->getStmtClass()) {
2042 default:
2043 return ESR_Failed;
2044
2045 case Stmt::NullStmtClass:
2046 case Stmt::DeclStmtClass:
2047 return ESR_Succeeded;
2048
Richard Smithc1c5f272011-12-13 06:39:58 +00002049 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002050 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002051 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002052 return ESR_Failed;
2053 return ESR_Returned;
2054 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002055
2056 case Stmt::CompoundStmtClass: {
2057 const CompoundStmt *CS = cast<CompoundStmt>(S);
2058 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2059 BE = CS->body_end(); BI != BE; ++BI) {
2060 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2061 if (ESR != ESR_Succeeded)
2062 return ESR;
2063 }
2064 return ESR_Succeeded;
2065 }
2066 }
2067}
2068
Richard Smith61802452011-12-22 02:22:31 +00002069/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2070/// default constructor. If so, we'll fold it whether or not it's marked as
2071/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2072/// so we need special handling.
2073static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002074 const CXXConstructorDecl *CD,
2075 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002076 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2077 return false;
2078
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002079 // Value-initialization does not call a trivial default constructor, so such a
2080 // call is a core constant expression whether or not the constructor is
2081 // constexpr.
2082 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002083 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002084 // FIXME: If DiagDecl is an implicitly-declared special member function,
2085 // we should be much more explicit about why it's not constexpr.
2086 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2087 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2088 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002089 } else {
2090 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2091 }
2092 }
2093 return true;
2094}
2095
Richard Smithc1c5f272011-12-13 06:39:58 +00002096/// CheckConstexprFunction - Check that a function can be called in a constant
2097/// expression.
2098static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2099 const FunctionDecl *Declaration,
2100 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002101 // Potential constant expressions can contain calls to declared, but not yet
2102 // defined, constexpr functions.
2103 if (Info.CheckingPotentialConstantExpression && !Definition &&
2104 Declaration->isConstexpr())
2105 return false;
2106
Richard Smithc1c5f272011-12-13 06:39:58 +00002107 // Can we evaluate this function call?
2108 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2109 return true;
2110
2111 if (Info.getLangOpts().CPlusPlus0x) {
2112 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002113 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2114 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002115 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2116 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2117 << DiagDecl;
2118 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2119 } else {
2120 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2121 }
2122 return false;
2123}
2124
Richard Smith180f4792011-11-10 06:34:14 +00002125namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002126typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002127}
2128
2129/// EvaluateArgs - Evaluate the arguments to a function call.
2130static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2131 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002132 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002133 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002134 I != E; ++I) {
2135 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2136 // If we're checking for a potential constant expression, evaluate all
2137 // initializers even if some of them fail.
2138 if (!Info.keepEvaluatingAfterFailure())
2139 return false;
2140 Success = false;
2141 }
2142 }
2143 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002144}
2145
Richard Smithd0dccea2011-10-28 22:34:42 +00002146/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002147static bool HandleFunctionCall(SourceLocation CallLoc,
2148 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002149 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002150 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002151 ArgVector ArgValues(Args.size());
2152 if (!EvaluateArgs(Args, ArgValues, Info))
2153 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002154
Richard Smith745f5142012-01-27 01:14:48 +00002155 if (!Info.CheckCallLimit(CallLoc))
2156 return false;
2157
2158 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002159 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2160}
2161
Richard Smith180f4792011-11-10 06:34:14 +00002162/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002163static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002164 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002165 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002166 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002167 ArgVector ArgValues(Args.size());
2168 if (!EvaluateArgs(Args, ArgValues, Info))
2169 return false;
2170
Richard Smith745f5142012-01-27 01:14:48 +00002171 if (!Info.CheckCallLimit(CallLoc))
2172 return false;
2173
Richard Smith86c3ae42012-02-13 03:54:03 +00002174 const CXXRecordDecl *RD = Definition->getParent();
2175 if (RD->getNumVBases()) {
2176 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2177 return false;
2178 }
2179
Richard Smith745f5142012-01-27 01:14:48 +00002180 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002181
2182 // If it's a delegating constructor, just delegate.
2183 if (Definition->isDelegatingConstructor()) {
2184 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002185 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002186 }
2187
Richard Smith610a60c2012-01-10 04:32:03 +00002188 // For a trivial copy or move constructor, perform an APValue copy. This is
2189 // essential for unions, where the operations performed by the constructor
2190 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002191 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002192 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2193 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002194 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002195 RHS.setFrom(Info.Ctx, ArgValues[0]);
2196 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2197 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002198 }
2199
2200 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002201 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002202 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2203 std::distance(RD->field_begin(), RD->field_end()));
2204
John McCall8d59dee2012-05-01 00:38:49 +00002205 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00002206 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2207
Richard Smith745f5142012-01-27 01:14:48 +00002208 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002209 unsigned BasesSeen = 0;
2210#ifndef NDEBUG
2211 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2212#endif
2213 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2214 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002215 LValue Subobject = This;
2216 APValue *Value = &Result;
2217
2218 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002219 if ((*I)->isBaseInitializer()) {
2220 QualType BaseType((*I)->getBaseClass(), 0);
2221#ifndef NDEBUG
2222 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002223 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002224 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2225 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2226 "base class initializers not in expected order");
2227 ++BaseIt;
2228#endif
John McCall8d59dee2012-05-01 00:38:49 +00002229 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2230 BaseType->getAsCXXRecordDecl(), &Layout))
2231 return false;
Richard Smith745f5142012-01-27 01:14:48 +00002232 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002233 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCall8d59dee2012-05-01 00:38:49 +00002234 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2235 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002236 if (RD->isUnion()) {
2237 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002238 Value = &Result.getUnionValue();
2239 } else {
2240 Value = &Result.getStructField(FD->getFieldIndex());
2241 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002242 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002243 // Walk the indirect field decl's chain to find the object to initialize,
2244 // and make sure we've initialized every step along it.
2245 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2246 CE = IFD->chain_end();
2247 C != CE; ++C) {
2248 FieldDecl *FD = cast<FieldDecl>(*C);
2249 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2250 // Switch the union field if it differs. This happens if we had
2251 // preceding zero-initialization, and we're now initializing a union
2252 // subobject other than the first.
2253 // FIXME: In this case, the values of the other subobjects are
2254 // specified, since zero-initialization sets all padding bits to zero.
2255 if (Value->isUninit() ||
2256 (Value->isUnion() && Value->getUnionField() != FD)) {
2257 if (CD->isUnion())
2258 *Value = APValue(FD);
2259 else
2260 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2261 std::distance(CD->field_begin(), CD->field_end()));
2262 }
John McCall8d59dee2012-05-01 00:38:49 +00002263 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2264 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002265 if (CD->isUnion())
2266 Value = &Value->getUnionValue();
2267 else
2268 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002269 }
Richard Smith180f4792011-11-10 06:34:14 +00002270 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002271 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002272 }
Richard Smith745f5142012-01-27 01:14:48 +00002273
Richard Smith83587db2012-02-15 02:18:13 +00002274 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2275 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002276 ? CCEK_Constant : CCEK_MemberInit)) {
2277 // If we're checking for a potential constant expression, evaluate all
2278 // initializers even if some of them fail.
2279 if (!Info.keepEvaluatingAfterFailure())
2280 return false;
2281 Success = false;
2282 }
Richard Smith180f4792011-11-10 06:34:14 +00002283 }
2284
Richard Smith745f5142012-01-27 01:14:48 +00002285 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002286}
2287
Eli Friedman4efaa272008-11-12 09:44:48 +00002288//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002289// Generic Evaluation
2290//===----------------------------------------------------------------------===//
2291namespace {
2292
Richard Smithf48fdb02011-12-09 22:58:01 +00002293// FIXME: RetTy is always bool. Remove it.
2294template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002295class ExprEvaluatorBase
2296 : public ConstStmtVisitor<Derived, RetTy> {
2297private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002298 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002299 return static_cast<Derived*>(this)->Success(V, E);
2300 }
Richard Smith51201882011-12-30 21:15:51 +00002301 RetTy DerivedZeroInitialization(const Expr *E) {
2302 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002303 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002304
Richard Smith74e1ad92012-02-16 02:46:34 +00002305 // Check whether a conditional operator with a non-constant condition is a
2306 // potential constant expression. If neither arm is a potential constant
2307 // expression, then the conditional operator is not either.
2308 template<typename ConditionalOperator>
2309 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2310 assert(Info.CheckingPotentialConstantExpression);
2311
2312 // Speculatively evaluate both arms.
2313 {
2314 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2315 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2316
2317 StmtVisitorTy::Visit(E->getFalseExpr());
2318 if (Diag.empty())
2319 return;
2320
2321 Diag.clear();
2322 StmtVisitorTy::Visit(E->getTrueExpr());
2323 if (Diag.empty())
2324 return;
2325 }
2326
2327 Error(E, diag::note_constexpr_conditional_never_const);
2328 }
2329
2330
2331 template<typename ConditionalOperator>
2332 bool HandleConditionalOperator(const ConditionalOperator *E) {
2333 bool BoolResult;
2334 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2335 if (Info.CheckingPotentialConstantExpression)
2336 CheckPotentialConstantConditional(E);
2337 return false;
2338 }
2339
2340 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2341 return StmtVisitorTy::Visit(EvalExpr);
2342 }
2343
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002344protected:
2345 EvalInfo &Info;
2346 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2347 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2348
Richard Smithdd1f29b2011-12-12 09:28:41 +00002349 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002350 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002351 }
2352
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002353 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2354
2355public:
2356 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2357
2358 EvalInfo &getEvalInfo() { return Info; }
2359
Richard Smithf48fdb02011-12-09 22:58:01 +00002360 /// Report an evaluation error. This should only be called when an error is
2361 /// first discovered. When propagating an error, just return false.
2362 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002363 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002364 return false;
2365 }
2366 bool Error(const Expr *E) {
2367 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2368 }
2369
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002370 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002371 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002372 }
2373 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002374 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002375 }
2376
2377 RetTy VisitParenExpr(const ParenExpr *E)
2378 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2379 RetTy VisitUnaryExtension(const UnaryOperator *E)
2380 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2381 RetTy VisitUnaryPlus(const UnaryOperator *E)
2382 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2383 RetTy VisitChooseExpr(const ChooseExpr *E)
2384 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2385 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2386 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002387 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2388 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002389 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2390 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002391 // We cannot create any objects for which cleanups are required, so there is
2392 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2393 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2394 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002395
Richard Smithc216a012011-12-12 12:46:16 +00002396 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2397 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2398 return static_cast<Derived*>(this)->VisitCastExpr(E);
2399 }
2400 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2401 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2402 return static_cast<Derived*>(this)->VisitCastExpr(E);
2403 }
2404
Richard Smithe24f5fc2011-11-17 22:56:20 +00002405 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2406 switch (E->getOpcode()) {
2407 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002408 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002409
2410 case BO_Comma:
2411 VisitIgnoredValue(E->getLHS());
2412 return StmtVisitorTy::Visit(E->getRHS());
2413
2414 case BO_PtrMemD:
2415 case BO_PtrMemI: {
2416 LValue Obj;
2417 if (!HandleMemberPointerAccess(Info, E, Obj))
2418 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002419 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002420 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002421 return false;
2422 return DerivedSuccess(Result, E);
2423 }
2424 }
2425 }
2426
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002427 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002428 // Evaluate and cache the common expression. We treat it as a temporary,
2429 // even though it's not quite the same thing.
2430 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2431 Info, E->getCommon()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002432 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002433
Richard Smith74e1ad92012-02-16 02:46:34 +00002434 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002435 }
2436
2437 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002438 bool IsBcpCall = false;
2439 // If the condition (ignoring parens) is a __builtin_constant_p call,
2440 // the result is a constant expression if it can be folded without
2441 // side-effects. This is an important GNU extension. See GCC PR38377
2442 // for discussion.
2443 if (const CallExpr *CallCE =
2444 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2445 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2446 IsBcpCall = true;
2447
2448 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2449 // constant expression; we can't check whether it's potentially foldable.
2450 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2451 return false;
2452
2453 FoldConstant Fold(Info);
2454
Richard Smith74e1ad92012-02-16 02:46:34 +00002455 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002456 return false;
2457
2458 if (IsBcpCall)
2459 Fold.Fold(Info);
2460
2461 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002462 }
2463
2464 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002465 APValue &Value = Info.CurrentCall->Temporaries[E];
2466 if (Value.isUninit()) {
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002467 const Expr *Source = E->getSourceExpr();
2468 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002469 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002470 if (Source == E) { // sanity checking.
2471 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002472 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002473 }
2474 return StmtVisitorTy::Visit(Source);
2475 }
Richard Smithe92b1f42012-06-26 08:12:11 +00002476 return DerivedSuccess(Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002477 }
Richard Smithf10d9172011-10-11 21:43:33 +00002478
Richard Smithd0dccea2011-10-28 22:34:42 +00002479 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002480 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002481 QualType CalleeType = Callee->getType();
2482
Richard Smithd0dccea2011-10-28 22:34:42 +00002483 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002484 LValue *This = 0, ThisVal;
2485 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002486 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002487
Richard Smith59efe262011-11-11 04:05:33 +00002488 // Extract function decl and 'this' pointer from the callee.
2489 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002490 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002491 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2492 // Explicit bound member calls, such as x.f() or p->g();
2493 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002494 return false;
2495 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002496 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002497 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002498 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2499 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002500 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2501 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002502 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002503 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002504 return Error(Callee);
2505
2506 FD = dyn_cast<FunctionDecl>(Member);
2507 if (!FD)
2508 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002509 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002510 LValue Call;
2511 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002512 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002513
Richard Smithb4e85ed2012-01-06 16:39:00 +00002514 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002515 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002516 FD = dyn_cast_or_null<FunctionDecl>(
2517 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002518 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002519 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002520
2521 // Overloaded operator calls to member functions are represented as normal
2522 // calls with '*this' as the first argument.
2523 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2524 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002525 // FIXME: When selecting an implicit conversion for an overloaded
2526 // operator delete, we sometimes try to evaluate calls to conversion
2527 // operators without a 'this' parameter!
2528 if (Args.empty())
2529 return Error(E);
2530
Richard Smith59efe262011-11-11 04:05:33 +00002531 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2532 return false;
2533 This = &ThisVal;
2534 Args = Args.slice(1);
2535 }
2536
2537 // Don't call function pointers which have been cast to some other type.
2538 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002539 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002540 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002541 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002542
Richard Smithb04035a2012-02-01 02:39:43 +00002543 if (This && !This->checkSubobject(Info, E, CSK_This))
2544 return false;
2545
Richard Smith86c3ae42012-02-13 03:54:03 +00002546 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2547 // calls to such functions in constant expressions.
2548 if (This && !HasQualifier &&
2549 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2550 return Error(E, diag::note_constexpr_virtual_call);
2551
Richard Smithc1c5f272011-12-13 06:39:58 +00002552 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002553 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002554 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002555
Richard Smithc1c5f272011-12-13 06:39:58 +00002556 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002557 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2558 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002559 return false;
2560
Richard Smith83587db2012-02-15 02:18:13 +00002561 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002562 }
2563
Richard Smithc49bd112011-10-28 17:51:58 +00002564 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2565 return StmtVisitorTy::Visit(E->getInitializer());
2566 }
Richard Smithf10d9172011-10-11 21:43:33 +00002567 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002568 if (E->getNumInits() == 0)
2569 return DerivedZeroInitialization(E);
2570 if (E->getNumInits() == 1)
2571 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002572 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002573 }
2574 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002575 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002576 }
2577 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002578 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002579 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002580 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002581 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002582 }
Richard Smithf10d9172011-10-11 21:43:33 +00002583
Richard Smith180f4792011-11-10 06:34:14 +00002584 /// A member expression where the object is a prvalue is itself a prvalue.
2585 RetTy VisitMemberExpr(const MemberExpr *E) {
2586 assert(!E->isArrow() && "missing call to bound member function?");
2587
Richard Smith1aa0be82012-03-03 22:46:17 +00002588 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002589 if (!Evaluate(Val, Info, E->getBase()))
2590 return false;
2591
2592 QualType BaseTy = E->getBase()->getType();
2593
2594 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002595 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002596 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek890f0f12012-08-23 20:46:57 +00002597 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smith180f4792011-11-10 06:34:14 +00002598 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2599
Richard Smithb4e85ed2012-01-06 16:39:00 +00002600 SubobjectDesignator Designator(BaseTy);
2601 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002602
Richard Smithf48fdb02011-12-09 22:58:01 +00002603 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002604 DerivedSuccess(Val, E);
2605 }
2606
Richard Smithc49bd112011-10-28 17:51:58 +00002607 RetTy VisitCastExpr(const CastExpr *E) {
2608 switch (E->getCastKind()) {
2609 default:
2610 break;
2611
David Chisnall7a7ee302012-01-16 17:27:18 +00002612 case CK_AtomicToNonAtomic:
2613 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002614 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002615 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002616 return StmtVisitorTy::Visit(E->getSubExpr());
2617
2618 case CK_LValueToRValue: {
2619 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002620 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2621 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002622 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002623 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2624 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2625 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002626 return false;
2627 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002628 }
2629 }
2630
Richard Smithf48fdb02011-12-09 22:58:01 +00002631 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002632 }
2633
Richard Smith8327fad2011-10-24 18:44:57 +00002634 /// Visit a value which is evaluated, but whose value is ignored.
2635 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002636 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002637 if (!Evaluate(Scratch, Info, E))
2638 Info.EvalStatus.HasSideEffects = true;
2639 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002640};
2641
2642}
2643
2644//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002645// Common base class for lvalue and temporary evaluation.
2646//===----------------------------------------------------------------------===//
2647namespace {
2648template<class Derived>
2649class LValueExprEvaluatorBase
2650 : public ExprEvaluatorBase<Derived, bool> {
2651protected:
2652 LValue &Result;
2653 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2654 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2655
2656 bool Success(APValue::LValueBase B) {
2657 Result.set(B);
2658 return true;
2659 }
2660
2661public:
2662 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2663 ExprEvaluatorBaseTy(Info), Result(Result) {}
2664
Richard Smith1aa0be82012-03-03 22:46:17 +00002665 bool Success(const APValue &V, const Expr *E) {
2666 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002667 return true;
2668 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002669
Richard Smithe24f5fc2011-11-17 22:56:20 +00002670 bool VisitMemberExpr(const MemberExpr *E) {
2671 // Handle non-static data members.
2672 QualType BaseTy;
2673 if (E->isArrow()) {
2674 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2675 return false;
Ted Kremenek890f0f12012-08-23 20:46:57 +00002676 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002677 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002678 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002679 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2680 return false;
2681 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002682 } else {
2683 if (!this->Visit(E->getBase()))
2684 return false;
2685 BaseTy = E->getBase()->getType();
2686 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002687
Richard Smithd9b02e72012-01-25 22:15:11 +00002688 const ValueDecl *MD = E->getMemberDecl();
2689 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2690 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2691 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2692 (void)BaseTy;
John McCall8d59dee2012-05-01 00:38:49 +00002693 if (!HandleLValueMember(this->Info, E, Result, FD))
2694 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002695 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCall8d59dee2012-05-01 00:38:49 +00002696 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2697 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002698 } else
2699 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002700
Richard Smithd9b02e72012-01-25 22:15:11 +00002701 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002702 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002703 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002704 RefValue))
2705 return false;
2706 return Success(RefValue, E);
2707 }
2708 return true;
2709 }
2710
2711 bool VisitBinaryOperator(const BinaryOperator *E) {
2712 switch (E->getOpcode()) {
2713 default:
2714 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2715
2716 case BO_PtrMemD:
2717 case BO_PtrMemI:
2718 return HandleMemberPointerAccess(this->Info, E, Result);
2719 }
2720 }
2721
2722 bool VisitCastExpr(const CastExpr *E) {
2723 switch (E->getCastKind()) {
2724 default:
2725 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2726
2727 case CK_DerivedToBase:
2728 case CK_UncheckedDerivedToBase: {
2729 if (!this->Visit(E->getSubExpr()))
2730 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002731
2732 // Now figure out the necessary offset to add to the base LV to get from
2733 // the derived class to the base class.
2734 QualType Type = E->getSubExpr()->getType();
2735
2736 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2737 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002738 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002739 *PathI))
2740 return false;
2741 Type = (*PathI)->getType();
2742 }
2743
2744 return true;
2745 }
2746 }
2747 }
2748};
2749}
2750
2751//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002752// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002753//
2754// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2755// function designators (in C), decl references to void objects (in C), and
2756// temporaries (if building with -Wno-address-of-temporary).
2757//
2758// LValue evaluation produces values comprising a base expression of one of the
2759// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002760// - Declarations
2761// * VarDecl
2762// * FunctionDecl
2763// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002764// * CompoundLiteralExpr in C
2765// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002766// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002767// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002768// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002769// * ObjCEncodeExpr
2770// * AddrLabelExpr
2771// * BlockExpr
2772// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002773// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002774// * Any Expr, with a CallIndex indicating the function in which the temporary
2775// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002776// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002777//===----------------------------------------------------------------------===//
2778namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002779class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002780 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002781public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002782 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2783 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002784
Richard Smithc49bd112011-10-28 17:51:58 +00002785 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2786
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002787 bool VisitDeclRefExpr(const DeclRefExpr *E);
2788 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002789 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002790 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2791 bool VisitMemberExpr(const MemberExpr *E);
2792 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2793 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002794 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichete275a182012-04-16 04:08:35 +00002795 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002796 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2797 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002798 bool VisitUnaryReal(const UnaryOperator *E);
2799 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002800
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002801 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002802 switch (E->getCastKind()) {
2803 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002804 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002805
Eli Friedmandb924222011-10-11 00:13:24 +00002806 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002807 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002808 if (!Visit(E->getSubExpr()))
2809 return false;
2810 Result.Designator.setInvalid();
2811 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002812
Richard Smithe24f5fc2011-11-17 22:56:20 +00002813 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002814 if (!Visit(E->getSubExpr()))
2815 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002816 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002817 }
2818 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002819};
2820} // end anonymous namespace
2821
Richard Smithc49bd112011-10-28 17:51:58 +00002822/// Evaluate an expression as an lvalue. This can be legitimately called on
2823/// expressions which are not glvalues, in a few cases:
2824/// * function designators in C,
2825/// * "extern void" objects,
2826/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002827static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002828 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2829 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2830 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002831 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002832}
2833
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002834bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002835 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2836 return Success(FD);
2837 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002838 return VisitVarDecl(E, VD);
2839 return Error(E);
2840}
Richard Smith436c8892011-10-24 23:14:33 +00002841
Richard Smithc49bd112011-10-28 17:51:58 +00002842bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002843 if (!VD->getType()->isReferenceType()) {
2844 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002845 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002846 return true;
2847 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002848 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002849 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002850
Richard Smith1aa0be82012-03-03 22:46:17 +00002851 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002852 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2853 return false;
2854 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002855}
2856
Richard Smithbd552ef2011-10-31 05:52:43 +00002857bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2858 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002859 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002860 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002861 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2862
Richard Smith83587db2012-02-15 02:18:13 +00002863 Result.set(E, Info.CurrentCall->Index);
2864 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2865 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002866 }
2867
2868 // Materialization of an lvalue temporary occurs when we need to force a copy
2869 // (for instance, if it's a bitfield).
2870 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2871 if (!Visit(E->GetTemporaryExpr()))
2872 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002873 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002874 Info.CurrentCall->Temporaries[E]))
2875 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002876 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002877 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002878}
2879
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002880bool
2881LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002882 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2883 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2884 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002885 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002886}
2887
Richard Smith47d21452011-12-27 12:18:28 +00002888bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2889 if (E->isTypeOperand())
2890 return Success(E);
2891 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
Richard Smith0d729102012-08-13 20:08:14 +00002892 // FIXME: The standard says "a typeid expression whose operand is of a
2893 // polymorphic class type" is not a constant expression, but it probably
2894 // means "a typeid expression whose operand is potentially evaluated".
Richard Smith47d21452011-12-27 12:18:28 +00002895 if (RD && RD->isPolymorphic()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002896 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith47d21452011-12-27 12:18:28 +00002897 << E->getExprOperand()->getType()
2898 << E->getExprOperand()->getSourceRange();
2899 return false;
2900 }
2901 return Success(E);
2902}
2903
Francois Pichete275a182012-04-16 04:08:35 +00002904bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2905 return Success(E);
2906}
2907
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002908bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002909 // Handle static data members.
2910 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2911 VisitIgnoredValue(E->getBase());
2912 return VisitVarDecl(E, VD);
2913 }
2914
Richard Smithd0dccea2011-10-28 22:34:42 +00002915 // Handle static member functions.
2916 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2917 if (MD->isStatic()) {
2918 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002919 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002920 }
2921 }
2922
Richard Smith180f4792011-11-10 06:34:14 +00002923 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002924 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002925}
2926
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002927bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002928 // FIXME: Deal with vectors as array subscript bases.
2929 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002930 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002931
Anders Carlsson3068d112008-11-16 19:01:22 +00002932 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002933 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002934
Anders Carlsson3068d112008-11-16 19:01:22 +00002935 APSInt Index;
2936 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002937 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002938 int64_t IndexValue
2939 = Index.isSigned() ? Index.getSExtValue()
2940 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002941
Richard Smithb4e85ed2012-01-06 16:39:00 +00002942 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002943}
Eli Friedman4efaa272008-11-12 09:44:48 +00002944
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002945bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002946 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002947}
2948
Richard Smith86024012012-02-18 22:04:06 +00002949bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2950 if (!Visit(E->getSubExpr()))
2951 return false;
2952 // __real is a no-op on scalar lvalues.
2953 if (E->getSubExpr()->getType()->isAnyComplexType())
2954 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
2955 return true;
2956}
2957
2958bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
2959 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
2960 "lvalue __imag__ on scalar?");
2961 if (!Visit(E->getSubExpr()))
2962 return false;
2963 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
2964 return true;
2965}
2966
Eli Friedman4efaa272008-11-12 09:44:48 +00002967//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002968// Pointer Evaluation
2969//===----------------------------------------------------------------------===//
2970
Anders Carlssonc754aa62008-07-08 05:13:58 +00002971namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002972class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002973 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002974 LValue &Result;
2975
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002976 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002977 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002978 return true;
2979 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002980public:
Mike Stump1eb44332009-09-09 15:08:12 +00002981
John McCallefdb83e2010-05-07 21:00:08 +00002982 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002983 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002984
Richard Smith1aa0be82012-03-03 22:46:17 +00002985 bool Success(const APValue &V, const Expr *E) {
2986 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002987 return true;
2988 }
Richard Smith51201882011-12-30 21:15:51 +00002989 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002990 return Success((Expr*)0);
2991 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002992
John McCallefdb83e2010-05-07 21:00:08 +00002993 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002994 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002995 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002996 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002997 { return Success(E); }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002998 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002999 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003000 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003001 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003002 bool VisitCallExpr(const CallExpr *E);
3003 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003004 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003005 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003006 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003007 }
Richard Smith180f4792011-11-10 06:34:14 +00003008 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3009 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003010 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003011 Result = *Info.CurrentCall->This;
3012 return true;
3013 }
John McCall56ca35d2011-02-17 10:25:35 +00003014
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003015 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003016};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003017} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003018
John McCallefdb83e2010-05-07 21:00:08 +00003019static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003020 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003021 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003022}
3023
John McCallefdb83e2010-05-07 21:00:08 +00003024bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003025 if (E->getOpcode() != BO_Add &&
3026 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003027 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003028
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003029 const Expr *PExp = E->getLHS();
3030 const Expr *IExp = E->getRHS();
3031 if (IExp->getType()->isPointerType())
3032 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003033
Richard Smith745f5142012-01-27 01:14:48 +00003034 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3035 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003036 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003037
John McCallefdb83e2010-05-07 21:00:08 +00003038 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003039 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003040 return false;
3041 int64_t AdditionalOffset
3042 = Offset.isSigned() ? Offset.getSExtValue()
3043 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003044 if (E->getOpcode() == BO_Sub)
3045 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003046
Ted Kremenek890f0f12012-08-23 20:46:57 +00003047 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003048 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3049 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003050}
Eli Friedman4efaa272008-11-12 09:44:48 +00003051
John McCallefdb83e2010-05-07 21:00:08 +00003052bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3053 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003054}
Mike Stump1eb44332009-09-09 15:08:12 +00003055
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003056bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3057 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003058
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003059 switch (E->getCastKind()) {
3060 default:
3061 break;
3062
John McCall2de56d12010-08-25 11:45:40 +00003063 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003064 case CK_CPointerToObjCPointerCast:
3065 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003066 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003067 if (!Visit(SubExpr))
3068 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003069 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3070 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3071 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003072 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003073 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003074 if (SubExpr->getType()->isVoidPointerType())
3075 CCEDiag(E, diag::note_constexpr_invalid_cast)
3076 << 3 << SubExpr->getType();
3077 else
3078 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3079 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003080 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003081
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003082 case CK_DerivedToBase:
3083 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003084 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003085 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003086 if (!Result.Base && Result.Offset.isZero())
3087 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003088
Richard Smith180f4792011-11-10 06:34:14 +00003089 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003090 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003091 QualType Type =
3092 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003093
Richard Smith180f4792011-11-10 06:34:14 +00003094 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003095 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003096 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3097 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003098 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003099 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003100 }
3101
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003102 return true;
3103 }
3104
Richard Smithe24f5fc2011-11-17 22:56:20 +00003105 case CK_BaseToDerived:
3106 if (!Visit(E->getSubExpr()))
3107 return false;
3108 if (!Result.Base && Result.Offset.isZero())
3109 return true;
3110 return HandleBaseToDerivedCast(Info, E, Result);
3111
Richard Smith47a1eed2011-10-29 20:57:55 +00003112 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003113 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003114 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003115
John McCall2de56d12010-08-25 11:45:40 +00003116 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003117 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3118
Richard Smith1aa0be82012-03-03 22:46:17 +00003119 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003120 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003121 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003122
John McCallefdb83e2010-05-07 21:00:08 +00003123 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003124 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3125 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003126 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003127 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003128 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003129 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003130 return true;
3131 } else {
3132 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003133 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003134 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003135 }
3136 }
John McCall2de56d12010-08-25 11:45:40 +00003137 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003138 if (SubExpr->isGLValue()) {
3139 if (!EvaluateLValue(SubExpr, Result, Info))
3140 return false;
3141 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003142 Result.set(SubExpr, Info.CurrentCall->Index);
3143 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3144 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003145 return false;
3146 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003147 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003148 if (const ConstantArrayType *CAT
3149 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3150 Result.addArray(Info, E, CAT);
3151 else
3152 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003153 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003154
John McCall2de56d12010-08-25 11:45:40 +00003155 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003156 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003157 }
3158
Richard Smithc49bd112011-10-28 17:51:58 +00003159 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003160}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003161
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003162bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003163 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003164 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003165
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003166 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003167}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003168
3169//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003170// Member Pointer Evaluation
3171//===----------------------------------------------------------------------===//
3172
3173namespace {
3174class MemberPointerExprEvaluator
3175 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3176 MemberPtr &Result;
3177
3178 bool Success(const ValueDecl *D) {
3179 Result = MemberPtr(D);
3180 return true;
3181 }
3182public:
3183
3184 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3185 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3186
Richard Smith1aa0be82012-03-03 22:46:17 +00003187 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003188 Result.setFrom(V);
3189 return true;
3190 }
Richard Smith51201882011-12-30 21:15:51 +00003191 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003192 return Success((const ValueDecl*)0);
3193 }
3194
3195 bool VisitCastExpr(const CastExpr *E);
3196 bool VisitUnaryAddrOf(const UnaryOperator *E);
3197};
3198} // end anonymous namespace
3199
3200static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3201 EvalInfo &Info) {
3202 assert(E->isRValue() && E->getType()->isMemberPointerType());
3203 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3204}
3205
3206bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3207 switch (E->getCastKind()) {
3208 default:
3209 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3210
3211 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003212 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003213 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003214
3215 case CK_BaseToDerivedMemberPointer: {
3216 if (!Visit(E->getSubExpr()))
3217 return false;
3218 if (E->path_empty())
3219 return true;
3220 // Base-to-derived member pointer casts store the path in derived-to-base
3221 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3222 // the wrong end of the derived->base arc, so stagger the path by one class.
3223 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3224 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3225 PathI != PathE; ++PathI) {
3226 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3227 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3228 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003229 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003230 }
3231 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3232 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003233 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003234 return true;
3235 }
3236
3237 case CK_DerivedToBaseMemberPointer:
3238 if (!Visit(E->getSubExpr()))
3239 return false;
3240 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3241 PathE = E->path_end(); PathI != PathE; ++PathI) {
3242 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3243 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3244 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003245 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003246 }
3247 return true;
3248 }
3249}
3250
3251bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3252 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3253 // member can be formed.
3254 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3255}
3256
3257//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003258// Record Evaluation
3259//===----------------------------------------------------------------------===//
3260
3261namespace {
3262 class RecordExprEvaluator
3263 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3264 const LValue &This;
3265 APValue &Result;
3266 public:
3267
3268 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3269 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3270
Richard Smith1aa0be82012-03-03 22:46:17 +00003271 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003272 Result = V;
3273 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003274 }
Richard Smith51201882011-12-30 21:15:51 +00003275 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003276
Richard Smith59efe262011-11-11 04:05:33 +00003277 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003278 bool VisitInitListExpr(const InitListExpr *E);
3279 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3280 };
3281}
3282
Richard Smith51201882011-12-30 21:15:51 +00003283/// Perform zero-initialization on an object of non-union class type.
3284/// C++11 [dcl.init]p5:
3285/// To zero-initialize an object or reference of type T means:
3286/// [...]
3287/// -- if T is a (possibly cv-qualified) non-union class type,
3288/// each non-static data member and each base-class subobject is
3289/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003290static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3291 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003292 const LValue &This, APValue &Result) {
3293 assert(!RD->isUnion() && "Expected non-union class type");
3294 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3295 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3296 std::distance(RD->field_begin(), RD->field_end()));
3297
John McCall8d59dee2012-05-01 00:38:49 +00003298 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003299 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3300
3301 if (CD) {
3302 unsigned Index = 0;
3303 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003304 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003305 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3306 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003307 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3308 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003309 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003310 Result.getStructBase(Index)))
3311 return false;
3312 }
3313 }
3314
Richard Smithb4e85ed2012-01-06 16:39:00 +00003315 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3316 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003317 // -- if T is a reference type, no initialization is performed.
David Blaikie262bc182012-04-30 02:36:29 +00003318 if (I->getType()->isReferenceType())
Richard Smith51201882011-12-30 21:15:51 +00003319 continue;
3320
3321 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003322 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003323 return false;
Richard Smith51201882011-12-30 21:15:51 +00003324
David Blaikie262bc182012-04-30 02:36:29 +00003325 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003326 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003327 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003328 return false;
3329 }
3330
3331 return true;
3332}
3333
3334bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3335 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003336 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003337 if (RD->isUnion()) {
3338 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3339 // object's first non-static named data member is zero-initialized
3340 RecordDecl::field_iterator I = RD->field_begin();
3341 if (I == RD->field_end()) {
3342 Result = APValue((const FieldDecl*)0);
3343 return true;
3344 }
3345
3346 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003347 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCall8d59dee2012-05-01 00:38:49 +00003348 return false;
David Blaikie581deb32012-06-06 20:45:41 +00003349 Result = APValue(*I);
David Blaikie262bc182012-04-30 02:36:29 +00003350 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003351 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003352 }
3353
Richard Smithce582fe2012-02-17 00:44:16 +00003354 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003355 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003356 return false;
3357 }
3358
Richard Smithb4e85ed2012-01-06 16:39:00 +00003359 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003360}
3361
Richard Smith59efe262011-11-11 04:05:33 +00003362bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3363 switch (E->getCastKind()) {
3364 default:
3365 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3366
3367 case CK_ConstructorConversion:
3368 return Visit(E->getSubExpr());
3369
3370 case CK_DerivedToBase:
3371 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003372 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003373 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003374 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003375 if (!DerivedObject.isStruct())
3376 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003377
3378 // Derived-to-base rvalue conversion: just slice off the derived part.
3379 APValue *Value = &DerivedObject;
3380 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3381 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3382 PathE = E->path_end(); PathI != PathE; ++PathI) {
3383 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3384 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3385 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3386 RD = Base;
3387 }
3388 Result = *Value;
3389 return true;
3390 }
3391 }
3392}
3393
Richard Smith180f4792011-11-10 06:34:14 +00003394bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003395 // Cannot constant-evaluate std::initializer_list inits.
3396 if (E->initializesStdInitializerList())
3397 return false;
3398
Richard Smith180f4792011-11-10 06:34:14 +00003399 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003400 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00003401 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3402
3403 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003404 const FieldDecl *Field = E->getInitializedFieldInUnion();
3405 Result = APValue(Field);
3406 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003407 return true;
Richard Smithec789162012-01-12 18:54:33 +00003408
3409 // If the initializer list for a union does not contain any elements, the
3410 // first element of the union is value-initialized.
3411 ImplicitValueInitExpr VIE(Field->getType());
3412 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3413
Richard Smith180f4792011-11-10 06:34:14 +00003414 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003415 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3416 return false;
Richard Smith83587db2012-02-15 02:18:13 +00003417 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003418 }
3419
3420 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3421 "initializer list for class with base classes");
3422 Result = APValue(APValue::UninitStruct(), 0,
3423 std::distance(RD->field_begin(), RD->field_end()));
3424 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003425 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003426 for (RecordDecl::field_iterator Field = RD->field_begin(),
3427 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3428 // Anonymous bit-fields are not considered members of the class for
3429 // purposes of aggregate initialization.
3430 if (Field->isUnnamedBitfield())
3431 continue;
3432
3433 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003434
Richard Smith745f5142012-01-27 01:14:48 +00003435 bool HaveInit = ElementNo < E->getNumInits();
3436
3437 // FIXME: Diagnostics here should point to the end of the initializer
3438 // list, not the start.
John McCall8d59dee2012-05-01 00:38:49 +00003439 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie581deb32012-06-06 20:45:41 +00003440 Subobject, *Field, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003441 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003442
3443 // Perform an implicit value-initialization for members beyond the end of
3444 // the initializer list.
3445 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3446
Richard Smith83587db2012-02-15 02:18:13 +00003447 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003448 Result.getStructField(Field->getFieldIndex()),
Richard Smith745f5142012-01-27 01:14:48 +00003449 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3450 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003451 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003452 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003453 }
3454 }
3455
Richard Smith745f5142012-01-27 01:14:48 +00003456 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003457}
3458
3459bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3460 const CXXConstructorDecl *FD = E->getConstructor();
John McCall1de9d7d2012-04-26 18:10:01 +00003461 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3462
Richard Smith51201882011-12-30 21:15:51 +00003463 bool ZeroInit = E->requiresZeroInitialization();
3464 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003465 // If we've already performed zero-initialization, we're already done.
3466 if (!Result.isUninit())
3467 return true;
3468
Richard Smith51201882011-12-30 21:15:51 +00003469 if (ZeroInit)
3470 return ZeroInitialization(E);
3471
Richard Smith61802452011-12-22 02:22:31 +00003472 const CXXRecordDecl *RD = FD->getParent();
3473 if (RD->isUnion())
3474 Result = APValue((FieldDecl*)0);
3475 else
3476 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3477 std::distance(RD->field_begin(), RD->field_end()));
3478 return true;
3479 }
3480
Richard Smith180f4792011-11-10 06:34:14 +00003481 const FunctionDecl *Definition = 0;
3482 FD->getBody(Definition);
3483
Richard Smithc1c5f272011-12-13 06:39:58 +00003484 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3485 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003486
Richard Smith610a60c2012-01-10 04:32:03 +00003487 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003488 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003489 if (const MaterializeTemporaryExpr *ME
3490 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3491 return Visit(ME->GetTemporaryExpr());
3492
Richard Smith51201882011-12-30 21:15:51 +00003493 if (ZeroInit && !ZeroInitialization(E))
3494 return false;
3495
Richard Smith180f4792011-11-10 06:34:14 +00003496 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003497 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003498 cast<CXXConstructorDecl>(Definition), Info,
3499 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003500}
3501
3502static bool EvaluateRecord(const Expr *E, const LValue &This,
3503 APValue &Result, EvalInfo &Info) {
3504 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003505 "can't evaluate expression as a record rvalue");
3506 return RecordExprEvaluator(Info, This, Result).Visit(E);
3507}
3508
3509//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003510// Temporary Evaluation
3511//
3512// Temporaries are represented in the AST as rvalues, but generally behave like
3513// lvalues. The full-object of which the temporary is a subobject is implicitly
3514// materialized so that a reference can bind to it.
3515//===----------------------------------------------------------------------===//
3516namespace {
3517class TemporaryExprEvaluator
3518 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3519public:
3520 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3521 LValueExprEvaluatorBaseTy(Info, Result) {}
3522
3523 /// Visit an expression which constructs the value of this temporary.
3524 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003525 Result.set(E, Info.CurrentCall->Index);
3526 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003527 }
3528
3529 bool VisitCastExpr(const CastExpr *E) {
3530 switch (E->getCastKind()) {
3531 default:
3532 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3533
3534 case CK_ConstructorConversion:
3535 return VisitConstructExpr(E->getSubExpr());
3536 }
3537 }
3538 bool VisitInitListExpr(const InitListExpr *E) {
3539 return VisitConstructExpr(E);
3540 }
3541 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3542 return VisitConstructExpr(E);
3543 }
3544 bool VisitCallExpr(const CallExpr *E) {
3545 return VisitConstructExpr(E);
3546 }
3547};
3548} // end anonymous namespace
3549
3550/// Evaluate an expression of record type as a temporary.
3551static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003552 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003553 return TemporaryExprEvaluator(Info, Result).Visit(E);
3554}
3555
3556//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003557// Vector Evaluation
3558//===----------------------------------------------------------------------===//
3559
3560namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003561 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003562 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3563 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003564 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003565
Richard Smith07fc6572011-10-22 21:10:00 +00003566 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3567 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003568
Richard Smith07fc6572011-10-22 21:10:00 +00003569 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3570 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3571 // FIXME: remove this APValue copy.
3572 Result = APValue(V.data(), V.size());
3573 return true;
3574 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003575 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003576 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003577 Result = V;
3578 return true;
3579 }
Richard Smith51201882011-12-30 21:15:51 +00003580 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003581
Richard Smith07fc6572011-10-22 21:10:00 +00003582 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003583 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003584 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003585 bool VisitInitListExpr(const InitListExpr *E);
3586 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003587 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003588 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003589 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003590 };
3591} // end anonymous namespace
3592
3593static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003594 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003595 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003596}
3597
Richard Smith07fc6572011-10-22 21:10:00 +00003598bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3599 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003600 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003601
Richard Smithd62ca372011-12-06 22:44:34 +00003602 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003603 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003604
Eli Friedman46a52322011-03-25 00:43:55 +00003605 switch (E->getCastKind()) {
3606 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003607 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003608 if (SETy->isIntegerType()) {
3609 APSInt IntResult;
3610 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003611 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003612 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003613 } else if (SETy->isRealFloatingType()) {
3614 APFloat F(0.0);
3615 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003616 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003617 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003618 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003619 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003620 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003621
3622 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003623 SmallVector<APValue, 4> Elts(NElts, Val);
3624 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003625 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003626 case CK_BitCast: {
3627 // Evaluate the operand into an APInt we can extract from.
3628 llvm::APInt SValInt;
3629 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3630 return false;
3631 // Extract the elements
3632 QualType EltTy = VTy->getElementType();
3633 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3634 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3635 SmallVector<APValue, 4> Elts;
3636 if (EltTy->isRealFloatingType()) {
3637 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3638 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3639 unsigned FloatEltSize = EltSize;
3640 if (&Sem == &APFloat::x87DoubleExtended)
3641 FloatEltSize = 80;
3642 for (unsigned i = 0; i < NElts; i++) {
3643 llvm::APInt Elt;
3644 if (BigEndian)
3645 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3646 else
3647 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3648 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3649 }
3650 } else if (EltTy->isIntegerType()) {
3651 for (unsigned i = 0; i < NElts; i++) {
3652 llvm::APInt Elt;
3653 if (BigEndian)
3654 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3655 else
3656 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3657 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3658 }
3659 } else {
3660 return Error(E);
3661 }
3662 return Success(Elts, E);
3663 }
Eli Friedman46a52322011-03-25 00:43:55 +00003664 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003665 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003666 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003667}
3668
Richard Smith07fc6572011-10-22 21:10:00 +00003669bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003670VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003671 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003672 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003673 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003674
Nate Begeman59b5da62009-01-18 03:20:47 +00003675 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003676 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003677
Eli Friedman3edd5a92012-01-03 23:24:20 +00003678 // The number of initializers can be less than the number of
3679 // vector elements. For OpenCL, this can be due to nested vector
3680 // initialization. For GCC compatibility, missing trailing elements
3681 // should be initialized with zeroes.
3682 unsigned CountInits = 0, CountElts = 0;
3683 while (CountElts < NumElements) {
3684 // Handle nested vector initialization.
3685 if (CountInits < NumInits
3686 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3687 APValue v;
3688 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3689 return Error(E);
3690 unsigned vlen = v.getVectorLength();
3691 for (unsigned j = 0; j < vlen; j++)
3692 Elements.push_back(v.getVectorElt(j));
3693 CountElts += vlen;
3694 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003695 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003696 if (CountInits < NumInits) {
3697 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003698 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003699 } else // trailing integer zero.
3700 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3701 Elements.push_back(APValue(sInt));
3702 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003703 } else {
3704 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003705 if (CountInits < NumInits) {
3706 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003707 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003708 } else // trailing float zero.
3709 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3710 Elements.push_back(APValue(f));
3711 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003712 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003713 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003714 }
Richard Smith07fc6572011-10-22 21:10:00 +00003715 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003716}
3717
Richard Smith07fc6572011-10-22 21:10:00 +00003718bool
Richard Smith51201882011-12-30 21:15:51 +00003719VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003720 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003721 QualType EltTy = VT->getElementType();
3722 APValue ZeroElement;
3723 if (EltTy->isIntegerType())
3724 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3725 else
3726 ZeroElement =
3727 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3728
Chris Lattner5f9e2722011-07-23 10:55:15 +00003729 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003730 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003731}
3732
Richard Smith07fc6572011-10-22 21:10:00 +00003733bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003734 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003735 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003736}
3737
Nate Begeman59b5da62009-01-18 03:20:47 +00003738//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003739// Array Evaluation
3740//===----------------------------------------------------------------------===//
3741
3742namespace {
3743 class ArrayExprEvaluator
3744 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003745 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003746 APValue &Result;
3747 public:
3748
Richard Smith180f4792011-11-10 06:34:14 +00003749 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3750 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003751
3752 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003753 assert((V.isArray() || V.isLValue()) &&
3754 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003755 Result = V;
3756 return true;
3757 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003758
Richard Smith51201882011-12-30 21:15:51 +00003759 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003760 const ConstantArrayType *CAT =
3761 Info.Ctx.getAsConstantArrayType(E->getType());
3762 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003763 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003764
3765 Result = APValue(APValue::UninitArray(), 0,
3766 CAT->getSize().getZExtValue());
3767 if (!Result.hasArrayFiller()) return true;
3768
Richard Smith51201882011-12-30 21:15:51 +00003769 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003770 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003771 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003772 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003773 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003774 }
3775
Richard Smithcc5d4f62011-11-07 09:22:26 +00003776 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003777 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003778 };
3779} // end anonymous namespace
3780
Richard Smith180f4792011-11-10 06:34:14 +00003781static bool EvaluateArray(const Expr *E, const LValue &This,
3782 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003783 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003784 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003785}
3786
3787bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3788 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3789 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003790 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003791
Richard Smith974c5f92011-12-22 01:07:19 +00003792 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3793 // an appropriately-typed string literal enclosed in braces.
Richard Smithfe587202012-04-15 02:50:59 +00003794 if (E->isStringLiteralInit()) {
Richard Smith974c5f92011-12-22 01:07:19 +00003795 LValue LV;
3796 if (!EvaluateLValue(E->getInit(0), LV, Info))
3797 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003798 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003799 LV.moveInto(Val);
3800 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003801 }
3802
Richard Smith745f5142012-01-27 01:14:48 +00003803 bool Success = true;
3804
Richard Smithde31aa72012-07-07 22:48:24 +00003805 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
3806 "zero-initialized array shouldn't have any initialized elts");
3807 APValue Filler;
3808 if (Result.isArray() && Result.hasArrayFiller())
3809 Filler = Result.getArrayFiller();
3810
Richard Smithcc5d4f62011-11-07 09:22:26 +00003811 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3812 CAT->getSize().getZExtValue());
Richard Smithde31aa72012-07-07 22:48:24 +00003813
3814 // If the array was previously zero-initialized, preserve the
3815 // zero-initialized values.
3816 if (!Filler.isUninit()) {
3817 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
3818 Result.getArrayInitializedElt(I) = Filler;
3819 if (Result.hasArrayFiller())
3820 Result.getArrayFiller() = Filler;
3821 }
3822
Richard Smith180f4792011-11-10 06:34:14 +00003823 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003824 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003825 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003826 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003827 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003828 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3829 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003830 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3831 CAT->getElementType(), 1)) {
3832 if (!Info.keepEvaluatingAfterFailure())
3833 return false;
3834 Success = false;
3835 }
Richard Smith180f4792011-11-10 06:34:14 +00003836 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003837
Richard Smith745f5142012-01-27 01:14:48 +00003838 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003839 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003840 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3841 // but sometimes does:
3842 // struct S { constexpr S() : p(&p) {} void *p; };
3843 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003844 return EvaluateInPlace(Result.getArrayFiller(), Info,
3845 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003846}
3847
Richard Smithe24f5fc2011-11-17 22:56:20 +00003848bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smithde31aa72012-07-07 22:48:24 +00003849 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3850 // but sometimes does:
3851 // struct S { constexpr S() : p(&p) {} void *p; };
3852 // S s[10];
3853 LValue Subobject = This;
3854
3855 APValue *Value = &Result;
3856 bool HadZeroInit = true;
Richard Smitha4334df2012-07-10 22:12:55 +00003857 QualType ElemTy = E->getType();
3858 while (const ConstantArrayType *CAT =
3859 Info.Ctx.getAsConstantArrayType(ElemTy)) {
Richard Smithde31aa72012-07-07 22:48:24 +00003860 Subobject.addArray(Info, E, CAT);
3861 HadZeroInit &= !Value->isUninit();
3862 if (!HadZeroInit)
3863 *Value = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3864 if (!Value->hasArrayFiller())
3865 return true;
Richard Smithde31aa72012-07-07 22:48:24 +00003866 Value = &Value->getArrayFiller();
Richard Smitha4334df2012-07-10 22:12:55 +00003867 ElemTy = CAT->getElementType();
Richard Smithde31aa72012-07-07 22:48:24 +00003868 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00003869
Richard Smitha4334df2012-07-10 22:12:55 +00003870 if (!ElemTy->isRecordType())
3871 return Error(E);
3872
Richard Smithe24f5fc2011-11-17 22:56:20 +00003873 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003874
Richard Smith51201882011-12-30 21:15:51 +00003875 bool ZeroInit = E->requiresZeroInitialization();
3876 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003877 if (HadZeroInit)
3878 return true;
3879
Richard Smith51201882011-12-30 21:15:51 +00003880 if (ZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003881 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003882 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003883 }
3884
Richard Smith61802452011-12-22 02:22:31 +00003885 const CXXRecordDecl *RD = FD->getParent();
3886 if (RD->isUnion())
Richard Smithde31aa72012-07-07 22:48:24 +00003887 *Value = APValue((FieldDecl*)0);
Richard Smith61802452011-12-22 02:22:31 +00003888 else
Richard Smithde31aa72012-07-07 22:48:24 +00003889 *Value =
Richard Smith61802452011-12-22 02:22:31 +00003890 APValue(APValue::UninitStruct(), RD->getNumBases(),
3891 std::distance(RD->field_begin(), RD->field_end()));
3892 return true;
3893 }
3894
Richard Smithe24f5fc2011-11-17 22:56:20 +00003895 const FunctionDecl *Definition = 0;
3896 FD->getBody(Definition);
3897
Richard Smithc1c5f272011-12-13 06:39:58 +00003898 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3899 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003900
Richard Smithec789162012-01-12 18:54:33 +00003901 if (ZeroInit && !HadZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003902 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003903 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003904 return false;
3905 }
3906
Richard Smithe24f5fc2011-11-17 22:56:20 +00003907 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003908 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003909 cast<CXXConstructorDecl>(Definition),
Richard Smithde31aa72012-07-07 22:48:24 +00003910 Info, *Value);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003911}
3912
Richard Smithcc5d4f62011-11-07 09:22:26 +00003913//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003914// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003915//
3916// As a GNU extension, we support casting pointers to sufficiently-wide integer
3917// types and back in constant folding. Integer values are thus represented
3918// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003919//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003920
3921namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003922class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003923 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003924 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003925public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003926 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003927 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003928
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003929 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003930 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003931 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003932 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003933 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003934 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003935 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003936 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003937 return true;
3938 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003939 bool Success(const llvm::APSInt &SI, const Expr *E) {
3940 return Success(SI, E, Result);
3941 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003942
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003943 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003944 assert(E->getType()->isIntegralOrEnumerationType() &&
3945 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003946 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003947 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003948 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003949 Result.getInt().setIsUnsigned(
3950 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003951 return true;
3952 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003953 bool Success(const llvm::APInt &I, const Expr *E) {
3954 return Success(I, E, Result);
3955 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003956
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003957 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003958 assert(E->getType()->isIntegralOrEnumerationType() &&
3959 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003960 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003961 return true;
3962 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003963 bool Success(uint64_t Value, const Expr *E) {
3964 return Success(Value, E, Result);
3965 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003966
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003967 bool Success(CharUnits Size, const Expr *E) {
3968 return Success(Size.getQuantity(), E);
3969 }
3970
Richard Smith1aa0be82012-03-03 22:46:17 +00003971 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003972 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003973 Result = V;
3974 return true;
3975 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003976 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003977 }
Mike Stump1eb44332009-09-09 15:08:12 +00003978
Richard Smith51201882011-12-30 21:15:51 +00003979 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003980
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003981 //===--------------------------------------------------------------------===//
3982 // Visitor Methods
3983 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003984
Chris Lattner4c4867e2008-07-12 00:38:25 +00003985 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003986 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003987 }
3988 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003989 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003990 }
Eli Friedman04309752009-11-24 05:28:59 +00003991
3992 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3993 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003994 if (CheckReferencedDecl(E, E->getDecl()))
3995 return true;
3996
3997 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003998 }
3999 bool VisitMemberExpr(const MemberExpr *E) {
4000 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004001 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004002 return true;
4003 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004004
4005 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004006 }
4007
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004008 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004009 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004010 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004011 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004012
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004013 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004014 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004015
Anders Carlsson3068d112008-11-16 19:01:22 +00004016 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004017 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004018 }
Mike Stump1eb44332009-09-09 15:08:12 +00004019
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004020 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4021 return Success(E->getValue(), E);
4022 }
4023
Richard Smithf10d9172011-10-11 21:43:33 +00004024 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004025 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004026 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004027 }
4028
Sebastian Redl64b45f72009-01-05 20:52:13 +00004029 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004030 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004031 }
4032
Francois Pichet6ad6f282010-12-07 00:08:36 +00004033 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4034 return Success(E->getValue(), E);
4035 }
4036
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004037 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4038 return Success(E->getValue(), E);
4039 }
4040
John Wiegley21ff2e52011-04-28 00:16:57 +00004041 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4042 return Success(E->getValue(), E);
4043 }
4044
John Wiegley55262202011-04-25 06:54:41 +00004045 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4046 return Success(E->getValue(), E);
4047 }
4048
Eli Friedman722c7172009-02-28 03:59:05 +00004049 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004050 bool VisitUnaryImag(const UnaryOperator *E);
4051
Sebastian Redl295995c2010-09-10 20:55:47 +00004052 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004053 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004054
Chris Lattnerfcee0012008-07-11 21:24:13 +00004055private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004056 CharUnits GetAlignOfExpr(const Expr *E);
4057 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004058 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004059 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004060 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004061};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004062} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004063
Richard Smithc49bd112011-10-28 17:51:58 +00004064/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4065/// produce either the integer value or a pointer.
4066///
4067/// GCC has a heinous extension which folds casts between pointer types and
4068/// pointer-sized integral types. We support this by allowing the evaluation of
4069/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4070/// Some simple arithmetic on such values is supported (they are treated much
4071/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004072static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004073 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004074 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004075 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004076}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004077
Richard Smithf48fdb02011-12-09 22:58:01 +00004078static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004079 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004080 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004081 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004082 if (!Val.isInt()) {
4083 // FIXME: It would be better to produce the diagnostic for casting
4084 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004085 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004086 return false;
4087 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004088 Result = Val.getInt();
4089 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004090}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004091
Richard Smithf48fdb02011-12-09 22:58:01 +00004092/// Check whether the given declaration can be directly converted to an integral
4093/// rvalue. If not, no diagnostic is produced; there are other things we can
4094/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004095bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004096 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004097 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004098 // Check for signedness/width mismatches between E type and ECD value.
4099 bool SameSign = (ECD->getInitVal().isSigned()
4100 == E->getType()->isSignedIntegerOrEnumerationType());
4101 bool SameWidth = (ECD->getInitVal().getBitWidth()
4102 == Info.Ctx.getIntWidth(E->getType()));
4103 if (SameSign && SameWidth)
4104 return Success(ECD->getInitVal(), E);
4105 else {
4106 // Get rid of mismatch (otherwise Success assertions will fail)
4107 // by computing a new value matching the type of E.
4108 llvm::APSInt Val = ECD->getInitVal();
4109 if (!SameSign)
4110 Val.setIsSigned(!ECD->getInitVal().isSigned());
4111 if (!SameWidth)
4112 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4113 return Success(Val, E);
4114 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004115 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004116 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004117}
4118
Chris Lattnera4d55d82008-10-06 06:40:35 +00004119/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4120/// as GCC.
4121static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4122 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004123 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004124 enum gcc_type_class {
4125 no_type_class = -1,
4126 void_type_class, integer_type_class, char_type_class,
4127 enumeral_type_class, boolean_type_class,
4128 pointer_type_class, reference_type_class, offset_type_class,
4129 real_type_class, complex_type_class,
4130 function_type_class, method_type_class,
4131 record_type_class, union_type_class,
4132 array_type_class, string_type_class,
4133 lang_type_class
4134 };
Mike Stump1eb44332009-09-09 15:08:12 +00004135
4136 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004137 // ideal, however it is what gcc does.
4138 if (E->getNumArgs() == 0)
4139 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004140
Chris Lattnera4d55d82008-10-06 06:40:35 +00004141 QualType ArgTy = E->getArg(0)->getType();
4142 if (ArgTy->isVoidType())
4143 return void_type_class;
4144 else if (ArgTy->isEnumeralType())
4145 return enumeral_type_class;
4146 else if (ArgTy->isBooleanType())
4147 return boolean_type_class;
4148 else if (ArgTy->isCharType())
4149 return string_type_class; // gcc doesn't appear to use char_type_class
4150 else if (ArgTy->isIntegerType())
4151 return integer_type_class;
4152 else if (ArgTy->isPointerType())
4153 return pointer_type_class;
4154 else if (ArgTy->isReferenceType())
4155 return reference_type_class;
4156 else if (ArgTy->isRealType())
4157 return real_type_class;
4158 else if (ArgTy->isComplexType())
4159 return complex_type_class;
4160 else if (ArgTy->isFunctionType())
4161 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004162 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004163 return record_type_class;
4164 else if (ArgTy->isUnionType())
4165 return union_type_class;
4166 else if (ArgTy->isArrayType())
4167 return array_type_class;
4168 else if (ArgTy->isUnionType())
4169 return union_type_class;
4170 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004171 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004172}
4173
Richard Smith80d4b552011-12-28 19:48:30 +00004174/// EvaluateBuiltinConstantPForLValue - Determine the result of
4175/// __builtin_constant_p when applied to the given lvalue.
4176///
4177/// An lvalue is only "constant" if it is a pointer or reference to the first
4178/// character of a string literal.
4179template<typename LValue>
4180static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004181 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004182 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4183}
4184
4185/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4186/// GCC as we can manage.
4187static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4188 QualType ArgType = Arg->getType();
4189
4190 // __builtin_constant_p always has one operand. The rules which gcc follows
4191 // are not precisely documented, but are as follows:
4192 //
4193 // - If the operand is of integral, floating, complex or enumeration type,
4194 // and can be folded to a known value of that type, it returns 1.
4195 // - If the operand and can be folded to a pointer to the first character
4196 // of a string literal (or such a pointer cast to an integral type), it
4197 // returns 1.
4198 //
4199 // Otherwise, it returns 0.
4200 //
4201 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4202 // its support for this does not currently work.
4203 if (ArgType->isIntegralOrEnumerationType()) {
4204 Expr::EvalResult Result;
4205 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4206 return false;
4207
4208 APValue &V = Result.Val;
4209 if (V.getKind() == APValue::Int)
4210 return true;
4211
4212 return EvaluateBuiltinConstantPForLValue(V);
4213 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4214 return Arg->isEvaluatable(Ctx);
4215 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4216 LValue LV;
4217 Expr::EvalStatus Status;
4218 EvalInfo Info(Ctx, Status);
4219 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4220 : EvaluatePointer(Arg, LV, Info)) &&
4221 !Status.HasSideEffects)
4222 return EvaluateBuiltinConstantPForLValue(LV);
4223 }
4224
4225 // Anything else isn't considered to be sufficiently constant.
4226 return false;
4227}
4228
John McCall42c8f872010-05-10 23:27:23 +00004229/// Retrieves the "underlying object type" of the given expression,
4230/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004231QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4232 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4233 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004234 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004235 } else if (const Expr *E = B.get<const Expr*>()) {
4236 if (isa<CompoundLiteralExpr>(E))
4237 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004238 }
4239
4240 return QualType();
4241}
4242
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004243bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004244 LValue Base;
Richard Smithc6794852012-05-23 04:13:20 +00004245
4246 {
4247 // The operand of __builtin_object_size is never evaluated for side-effects.
4248 // If there are any, but we can determine the pointed-to object anyway, then
4249 // ignore the side-effects.
4250 SpeculativeEvaluationRAII SpeculativeEval(Info);
4251 if (!EvaluatePointer(E->getArg(0), Base, Info))
4252 return false;
4253 }
John McCall42c8f872010-05-10 23:27:23 +00004254
4255 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004256 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004257
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004258 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004259 if (T.isNull() ||
4260 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004261 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004262 T->isVariablyModifiedType() ||
4263 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004264 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004265
4266 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4267 CharUnits Offset = Base.getLValueOffset();
4268
4269 if (!Offset.isNegative() && Offset <= Size)
4270 Size -= Offset;
4271 else
4272 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004273 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004274}
4275
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004276bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00004277 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004278 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004279 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004280
4281 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004282 if (TryEvaluateBuiltinObjectSize(E))
4283 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004284
Richard Smith8ae4ec22012-08-07 04:16:51 +00004285 // If evaluating the argument has side-effects, we can't determine the size
4286 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4287 // handle all cases where the expression has side-effects.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004288 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004289 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004290 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004291 return Success(0, E);
4292 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004293
Richard Smithc6794852012-05-23 04:13:20 +00004294 // Expression had no side effects, but we couldn't statically determine the
4295 // size of the referenced object.
Richard Smithf48fdb02011-12-09 22:58:01 +00004296 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004297 }
4298
Chris Lattner019f4e82008-10-06 05:28:25 +00004299 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004300 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004301
Richard Smith80d4b552011-12-28 19:48:30 +00004302 case Builtin::BI__builtin_constant_p:
4303 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004304
Chris Lattner21fb98e2009-09-23 06:06:36 +00004305 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004306 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004307 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004308 return Success(Operand, E);
4309 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004310
4311 case Builtin::BI__builtin_expect:
4312 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004313
Douglas Gregor5726d402010-09-10 06:27:15 +00004314 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004315 // A call to strlen is not a constant expression.
4316 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004317 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004318 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4319 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004320 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004321 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004322 case Builtin::BI__builtin_strlen:
4323 // As an extension, we support strlen() and __builtin_strlen() as constant
4324 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004325 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004326 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4327 // The string literal may have embedded null characters. Find the first
4328 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004329 StringRef Str = S->getString();
4330 StringRef::size_type Pos = Str.find(0);
4331 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004332 Str = Str.substr(0, Pos);
4333
4334 return Success(Str.size(), E);
4335 }
4336
Richard Smithf48fdb02011-12-09 22:58:01 +00004337 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004338
Richard Smith2c39d712012-04-13 00:45:38 +00004339 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00004340 case Builtin::BI__atomic_is_lock_free:
4341 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00004342 APSInt SizeVal;
4343 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4344 return false;
4345
4346 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4347 // of two less than the maximum inline atomic width, we know it is
4348 // lock-free. If the size isn't a power of two, or greater than the
4349 // maximum alignment where we promote atomics, we know it is not lock-free
4350 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4351 // the answer can only be determined at runtime; for example, 16-byte
4352 // atomics have lock-free implementations on some, but not all,
4353 // x86-64 processors.
4354
4355 // Check power-of-two.
4356 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00004357 if (Size.isPowerOfTwo()) {
4358 // Check against inlining width.
4359 unsigned InlineWidthBits =
4360 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4361 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4362 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4363 Size == CharUnits::One() ||
4364 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4365 Expr::NPC_NeverValueDependent))
4366 // OK, we will inline appropriately-aligned operations of this size,
4367 // and _Atomic(T) is appropriately-aligned.
4368 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004369
Richard Smith2c39d712012-04-13 00:45:38 +00004370 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4371 castAs<PointerType>()->getPointeeType();
4372 if (!PointeeType->isIncompleteType() &&
4373 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4374 // OK, we will inline operations on this object.
4375 return Success(1, E);
4376 }
4377 }
4378 }
Eli Friedman454b57a2011-10-17 21:44:23 +00004379
Richard Smith2c39d712012-04-13 00:45:38 +00004380 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4381 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004382 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004383 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004384}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004385
Richard Smith625b8072011-10-31 01:37:14 +00004386static bool HasSameBase(const LValue &A, const LValue &B) {
4387 if (!A.getLValueBase())
4388 return !B.getLValueBase();
4389 if (!B.getLValueBase())
4390 return false;
4391
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004392 if (A.getLValueBase().getOpaqueValue() !=
4393 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004394 const Decl *ADecl = GetLValueBaseDecl(A);
4395 if (!ADecl)
4396 return false;
4397 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004398 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004399 return false;
4400 }
4401
4402 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004403 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004404}
4405
Richard Smith7b48a292012-02-01 05:53:12 +00004406/// Perform the given integer operation, which is known to need at most BitWidth
4407/// bits, and check for overflow in the original type (if that type was not an
4408/// unsigned type).
4409template<typename Operation>
4410static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4411 const APSInt &LHS, const APSInt &RHS,
4412 unsigned BitWidth, Operation Op) {
4413 if (LHS.isUnsigned())
4414 return Op(LHS, RHS);
4415
4416 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4417 APSInt Result = Value.trunc(LHS.getBitWidth());
4418 if (Result.extend(BitWidth) != Value)
4419 HandleOverflow(Info, E, Value, E->getType());
4420 return Result;
4421}
4422
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004423namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004424
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004425/// \brief Data recursive integer evaluator of certain binary operators.
4426///
4427/// We use a data recursive algorithm for binary operators so that we are able
4428/// to handle extreme cases of chained binary operators without causing stack
4429/// overflow.
4430class DataRecursiveIntBinOpEvaluator {
4431 struct EvalResult {
4432 APValue Val;
4433 bool Failed;
4434
4435 EvalResult() : Failed(false) { }
4436
4437 void swap(EvalResult &RHS) {
4438 Val.swap(RHS.Val);
4439 Failed = RHS.Failed;
4440 RHS.Failed = false;
4441 }
4442 };
4443
4444 struct Job {
4445 const Expr *E;
4446 EvalResult LHSResult; // meaningful only for binary operator expression.
4447 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4448
4449 Job() : StoredInfo(0) { }
4450 void startSpeculativeEval(EvalInfo &Info) {
4451 OldEvalStatus = Info.EvalStatus;
4452 Info.EvalStatus.Diag = 0;
4453 StoredInfo = &Info;
4454 }
4455 ~Job() {
4456 if (StoredInfo) {
4457 StoredInfo->EvalStatus = OldEvalStatus;
4458 }
4459 }
4460 private:
4461 EvalInfo *StoredInfo; // non-null if status changed.
4462 Expr::EvalStatus OldEvalStatus;
4463 };
4464
4465 SmallVector<Job, 16> Queue;
4466
4467 IntExprEvaluator &IntEval;
4468 EvalInfo &Info;
4469 APValue &FinalResult;
4470
4471public:
4472 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4473 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4474
4475 /// \brief True if \param E is a binary operator that we are going to handle
4476 /// data recursively.
4477 /// We handle binary operators that are comma, logical, or that have operands
4478 /// with integral or enumeration type.
4479 static bool shouldEnqueue(const BinaryOperator *E) {
4480 return E->getOpcode() == BO_Comma ||
4481 E->isLogicalOp() ||
4482 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4483 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004484 }
4485
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004486 bool Traverse(const BinaryOperator *E) {
4487 enqueue(E);
4488 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004489 while (!Queue.empty())
4490 process(PrevResult);
4491
4492 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004493
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004494 FinalResult.swap(PrevResult.Val);
4495 return true;
4496 }
4497
4498private:
4499 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4500 return IntEval.Success(Value, E, Result);
4501 }
4502 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4503 return IntEval.Success(Value, E, Result);
4504 }
4505 bool Error(const Expr *E) {
4506 return IntEval.Error(E);
4507 }
4508 bool Error(const Expr *E, diag::kind D) {
4509 return IntEval.Error(E, D);
4510 }
4511
4512 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4513 return Info.CCEDiag(E, D);
4514 }
4515
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004516 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4517 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004518 bool &SuppressRHSDiags);
4519
4520 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4521 const BinaryOperator *E, APValue &Result);
4522
4523 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4524 Result.Failed = !Evaluate(Result.Val, Info, E);
4525 if (Result.Failed)
4526 Result.Val = APValue();
4527 }
4528
Richard Trieub7783052012-03-21 23:30:30 +00004529 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004530
4531 void enqueue(const Expr *E) {
4532 E = E->IgnoreParens();
4533 Queue.resize(Queue.size()+1);
4534 Queue.back().E = E;
4535 Queue.back().Kind = Job::AnyExprKind;
4536 }
4537};
4538
4539}
4540
4541bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004542 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004543 bool &SuppressRHSDiags) {
4544 if (E->getOpcode() == BO_Comma) {
4545 // Ignore LHS but note if we could not evaluate it.
4546 if (LHSResult.Failed)
4547 Info.EvalStatus.HasSideEffects = true;
4548 return true;
4549 }
4550
4551 if (E->isLogicalOp()) {
4552 bool lhsResult;
4553 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004554 // We were able to evaluate the LHS, see if we can get away with not
4555 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004556 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004557 Success(lhsResult, E, LHSResult.Val);
4558 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004559 }
4560 } else {
4561 // Since we weren't able to evaluate the left hand side, it
4562 // must have had side effects.
4563 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004564
4565 // We can't evaluate the LHS; however, sometimes the result
4566 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4567 // Don't ignore RHS and suppress diagnostics from this arm.
4568 SuppressRHSDiags = true;
4569 }
4570
4571 return true;
4572 }
4573
4574 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4575 E->getRHS()->getType()->isIntegralOrEnumerationType());
4576
4577 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004578 return false; // Ignore RHS;
4579
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004580 return true;
4581}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004582
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004583bool DataRecursiveIntBinOpEvaluator::
4584 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4585 const BinaryOperator *E, APValue &Result) {
4586 if (E->getOpcode() == BO_Comma) {
4587 if (RHSResult.Failed)
4588 return false;
4589 Result = RHSResult.Val;
4590 return true;
4591 }
4592
4593 if (E->isLogicalOp()) {
4594 bool lhsResult, rhsResult;
4595 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4596 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4597
4598 if (LHSIsOK) {
4599 if (RHSIsOK) {
4600 if (E->getOpcode() == BO_LOr)
4601 return Success(lhsResult || rhsResult, E, Result);
4602 else
4603 return Success(lhsResult && rhsResult, E, Result);
4604 }
4605 } else {
4606 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004607 // We can't evaluate the LHS; however, sometimes the result
4608 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4609 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004610 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004611 }
4612 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004613
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004614 return false;
4615 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004616
4617 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4618 E->getRHS()->getType()->isIntegralOrEnumerationType());
4619
4620 if (LHSResult.Failed || RHSResult.Failed)
4621 return false;
4622
4623 const APValue &LHSVal = LHSResult.Val;
4624 const APValue &RHSVal = RHSResult.Val;
4625
4626 // Handle cases like (unsigned long)&a + 4.
4627 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4628 Result = LHSVal;
4629 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4630 RHSVal.getInt().getZExtValue());
4631 if (E->getOpcode() == BO_Add)
4632 Result.getLValueOffset() += AdditionalOffset;
4633 else
4634 Result.getLValueOffset() -= AdditionalOffset;
4635 return true;
4636 }
4637
4638 // Handle cases like 4 + (unsigned long)&a
4639 if (E->getOpcode() == BO_Add &&
4640 RHSVal.isLValue() && LHSVal.isInt()) {
4641 Result = RHSVal;
4642 Result.getLValueOffset() += CharUnits::fromQuantity(
4643 LHSVal.getInt().getZExtValue());
4644 return true;
4645 }
4646
4647 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4648 // Handle (intptr_t)&&A - (intptr_t)&&B.
4649 if (!LHSVal.getLValueOffset().isZero() ||
4650 !RHSVal.getLValueOffset().isZero())
4651 return false;
4652 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4653 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4654 if (!LHSExpr || !RHSExpr)
4655 return false;
4656 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4657 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4658 if (!LHSAddrExpr || !RHSAddrExpr)
4659 return false;
4660 // Make sure both labels come from the same function.
4661 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4662 RHSAddrExpr->getLabel()->getDeclContext())
4663 return false;
4664 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4665 return true;
4666 }
4667
4668 // All the following cases expect both operands to be an integer
4669 if (!LHSVal.isInt() || !RHSVal.isInt())
4670 return Error(E);
4671
4672 const APSInt &LHS = LHSVal.getInt();
4673 APSInt RHS = RHSVal.getInt();
4674
4675 switch (E->getOpcode()) {
4676 default:
4677 return Error(E);
4678 case BO_Mul:
4679 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4680 LHS.getBitWidth() * 2,
4681 std::multiplies<APSInt>()), E,
4682 Result);
4683 case BO_Add:
4684 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4685 LHS.getBitWidth() + 1,
4686 std::plus<APSInt>()), E, Result);
4687 case BO_Sub:
4688 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4689 LHS.getBitWidth() + 1,
4690 std::minus<APSInt>()), E, Result);
4691 case BO_And: return Success(LHS & RHS, E, Result);
4692 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4693 case BO_Or: return Success(LHS | RHS, E, Result);
4694 case BO_Div:
4695 case BO_Rem:
4696 if (RHS == 0)
4697 return Error(E, diag::note_expr_divide_by_zero);
4698 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4699 // not actually undefined behavior in C++11 due to a language defect.
4700 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4701 LHS.isSigned() && LHS.isMinSignedValue())
4702 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4703 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4704 Result);
4705 case BO_Shl: {
4706 // During constant-folding, a negative shift is an opposite shift. Such
4707 // a shift is not a constant expression.
4708 if (RHS.isSigned() && RHS.isNegative()) {
4709 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4710 RHS = -RHS;
4711 goto shift_right;
4712 }
4713
4714 shift_left:
4715 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4716 // the shifted type.
4717 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4718 if (SA != RHS) {
4719 CCEDiag(E, diag::note_constexpr_large_shift)
4720 << RHS << E->getType() << LHS.getBitWidth();
4721 } else if (LHS.isSigned()) {
4722 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4723 // operand, and must not overflow the corresponding unsigned type.
4724 if (LHS.isNegative())
4725 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4726 else if (LHS.countLeadingZeros() < SA)
4727 CCEDiag(E, diag::note_constexpr_lshift_discards);
4728 }
4729
4730 return Success(LHS << SA, E, Result);
4731 }
4732 case BO_Shr: {
4733 // During constant-folding, a negative shift is an opposite shift. Such a
4734 // shift is not a constant expression.
4735 if (RHS.isSigned() && RHS.isNegative()) {
4736 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4737 RHS = -RHS;
4738 goto shift_left;
4739 }
4740
4741 shift_right:
4742 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4743 // shifted type.
4744 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4745 if (SA != RHS)
4746 CCEDiag(E, diag::note_constexpr_large_shift)
4747 << RHS << E->getType() << LHS.getBitWidth();
4748
4749 return Success(LHS >> SA, E, Result);
4750 }
4751
4752 case BO_LT: return Success(LHS < RHS, E, Result);
4753 case BO_GT: return Success(LHS > RHS, E, Result);
4754 case BO_LE: return Success(LHS <= RHS, E, Result);
4755 case BO_GE: return Success(LHS >= RHS, E, Result);
4756 case BO_EQ: return Success(LHS == RHS, E, Result);
4757 case BO_NE: return Success(LHS != RHS, E, Result);
4758 }
4759}
4760
Richard Trieub7783052012-03-21 23:30:30 +00004761void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004762 Job &job = Queue.back();
4763
4764 switch (job.Kind) {
4765 case Job::AnyExprKind: {
4766 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4767 if (shouldEnqueue(Bop)) {
4768 job.Kind = Job::BinOpKind;
4769 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004770 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004771 }
4772 }
4773
4774 EvaluateExpr(job.E, Result);
4775 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004776 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004777 }
4778
4779 case Job::BinOpKind: {
4780 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004781 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004782 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004783 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004784 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004785 }
4786 if (SuppressRHSDiags)
4787 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004788 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004789 job.Kind = Job::BinOpVisitedLHSKind;
4790 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004791 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004792 }
4793
4794 case Job::BinOpVisitedLHSKind: {
4795 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4796 EvalResult RHS;
4797 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004798 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004799 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004800 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004801 }
4802 }
4803
4804 llvm_unreachable("Invalid Job::Kind!");
4805}
4806
4807bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4808 if (E->isAssignmentOp())
4809 return Error(E);
4810
4811 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4812 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004813
Anders Carlsson286f85e2008-11-16 07:17:21 +00004814 QualType LHSTy = E->getLHS()->getType();
4815 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004816
4817 if (LHSTy->isAnyComplexType()) {
4818 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004819 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004820
Richard Smith745f5142012-01-27 01:14:48 +00004821 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4822 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004823 return false;
4824
Richard Smith745f5142012-01-27 01:14:48 +00004825 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004826 return false;
4827
4828 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004829 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004830 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004831 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004832 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4833
John McCall2de56d12010-08-25 11:45:40 +00004834 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004835 return Success((CR_r == APFloat::cmpEqual &&
4836 CR_i == APFloat::cmpEqual), E);
4837 else {
John McCall2de56d12010-08-25 11:45:40 +00004838 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004839 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004840 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004841 CR_r == APFloat::cmpLessThan ||
4842 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004843 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004844 CR_i == APFloat::cmpLessThan ||
4845 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004846 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004847 } else {
John McCall2de56d12010-08-25 11:45:40 +00004848 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004849 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4850 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4851 else {
John McCall2de56d12010-08-25 11:45:40 +00004852 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004853 "Invalid compex comparison.");
4854 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4855 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4856 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004857 }
4858 }
Mike Stump1eb44332009-09-09 15:08:12 +00004859
Anders Carlsson286f85e2008-11-16 07:17:21 +00004860 if (LHSTy->isRealFloatingType() &&
4861 RHSTy->isRealFloatingType()) {
4862 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004863
Richard Smith745f5142012-01-27 01:14:48 +00004864 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4865 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004866 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004867
Richard Smith745f5142012-01-27 01:14:48 +00004868 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004869 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004870
Anders Carlsson286f85e2008-11-16 07:17:21 +00004871 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004872
Anders Carlsson286f85e2008-11-16 07:17:21 +00004873 switch (E->getOpcode()) {
4874 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004875 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004876 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004877 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004878 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004879 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004880 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004881 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004882 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004883 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004884 E);
John McCall2de56d12010-08-25 11:45:40 +00004885 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004886 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004887 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004888 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004889 || CR == APFloat::cmpLessThan
4890 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004891 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004892 }
Mike Stump1eb44332009-09-09 15:08:12 +00004893
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004894 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004895 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004896 LValue LHSValue, RHSValue;
4897
4898 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4899 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004900 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004901
Richard Smith745f5142012-01-27 01:14:48 +00004902 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004903 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004904
Richard Smith625b8072011-10-31 01:37:14 +00004905 // Reject differing bases from the normal codepath; we special-case
4906 // comparisons to null.
4907 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004908 if (E->getOpcode() == BO_Sub) {
4909 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004910 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4911 return false;
4912 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4913 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4914 if (!LHSExpr || !RHSExpr)
4915 return false;
4916 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4917 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4918 if (!LHSAddrExpr || !RHSAddrExpr)
4919 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004920 // Make sure both labels come from the same function.
4921 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4922 RHSAddrExpr->getLabel()->getDeclContext())
4923 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004924 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004925 return true;
4926 }
Richard Smith9e36b532011-10-31 05:11:32 +00004927 // Inequalities and subtractions between unrelated pointers have
4928 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004929 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004930 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004931 // A constant address may compare equal to the address of a symbol.
4932 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004933 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004934 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4935 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004936 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004937 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004938 // distinct addresses. In clang, the result of such a comparison is
4939 // unspecified, so it is not a constant expression. However, we do know
4940 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004941 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4942 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004943 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004944 // We can't tell whether weak symbols will end up pointing to the same
4945 // object.
4946 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004947 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004948 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004949 // (Note that clang defaults to -fmerge-all-constants, which can
4950 // lead to inconsistent results for comparisons involving the address
4951 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004952 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004953 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004954
Richard Smith15efc4d2012-02-01 08:10:20 +00004955 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4956 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4957
Richard Smithf15fda02012-02-02 01:16:57 +00004958 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4959 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4960
John McCall2de56d12010-08-25 11:45:40 +00004961 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004962 // C++11 [expr.add]p6:
4963 // Unless both pointers point to elements of the same array object, or
4964 // one past the last element of the array object, the behavior is
4965 // undefined.
4966 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4967 !AreElementsOfSameArray(getType(LHSValue.Base),
4968 LHSDesignator, RHSDesignator))
4969 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4970
Chris Lattner4992bdd2010-04-20 17:13:14 +00004971 QualType Type = E->getLHS()->getType();
4972 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004973
Richard Smith180f4792011-11-10 06:34:14 +00004974 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004975 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004976 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004977
Richard Smith15efc4d2012-02-01 08:10:20 +00004978 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4979 // and produce incorrect results when it overflows. Such behavior
4980 // appears to be non-conforming, but is common, so perhaps we should
4981 // assume the standard intended for such cases to be undefined behavior
4982 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004983
Richard Smith15efc4d2012-02-01 08:10:20 +00004984 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4985 // overflow in the final conversion to ptrdiff_t.
4986 APSInt LHS(
4987 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4988 APSInt RHS(
4989 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4990 APSInt ElemSize(
4991 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4992 APSInt TrueResult = (LHS - RHS) / ElemSize;
4993 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4994
4995 if (Result.extend(65) != TrueResult)
4996 HandleOverflow(Info, E, TrueResult, E->getType());
4997 return Success(Result, E);
4998 }
Richard Smith82f28582012-01-31 06:41:30 +00004999
5000 // C++11 [expr.rel]p3:
5001 // Pointers to void (after pointer conversions) can be compared, with a
5002 // result defined as follows: If both pointers represent the same
5003 // address or are both the null pointer value, the result is true if the
5004 // operator is <= or >= and false otherwise; otherwise the result is
5005 // unspecified.
5006 // We interpret this as applying to pointers to *cv* void.
5007 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005008 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005009 CCEDiag(E, diag::note_constexpr_void_comparison);
5010
Richard Smithf15fda02012-02-02 01:16:57 +00005011 // C++11 [expr.rel]p2:
5012 // - If two pointers point to non-static data members of the same object,
5013 // or to subobjects or array elements fo such members, recursively, the
5014 // pointer to the later declared member compares greater provided the
5015 // two members have the same access control and provided their class is
5016 // not a union.
5017 // [...]
5018 // - Otherwise pointer comparisons are unspecified.
5019 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5020 E->isRelationalOp()) {
5021 bool WasArrayIndex;
5022 unsigned Mismatch =
5023 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5024 RHSDesignator, WasArrayIndex);
5025 // At the point where the designators diverge, the comparison has a
5026 // specified value if:
5027 // - we are comparing array indices
5028 // - we are comparing fields of a union, or fields with the same access
5029 // Otherwise, the result is unspecified and thus the comparison is not a
5030 // constant expression.
5031 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5032 Mismatch < RHSDesignator.Entries.size()) {
5033 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5034 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5035 if (!LF && !RF)
5036 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5037 else if (!LF)
5038 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5039 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5040 << RF->getParent() << RF;
5041 else if (!RF)
5042 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5043 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5044 << LF->getParent() << LF;
5045 else if (!LF->getParent()->isUnion() &&
5046 LF->getAccess() != RF->getAccess())
5047 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5048 << LF << LF->getAccess() << RF << RF->getAccess()
5049 << LF->getParent();
5050 }
5051 }
5052
Eli Friedmana3169882012-04-16 04:30:08 +00005053 // The comparison here must be unsigned, and performed with the same
5054 // width as the pointer.
Eli Friedmana3169882012-04-16 04:30:08 +00005055 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5056 uint64_t CompareLHS = LHSOffset.getQuantity();
5057 uint64_t CompareRHS = RHSOffset.getQuantity();
5058 assert(PtrSize <= 64 && "Unexpected pointer width");
5059 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5060 CompareLHS &= Mask;
5061 CompareRHS &= Mask;
5062
Eli Friedman28503762012-04-16 19:23:57 +00005063 // If there is a base and this is a relational operator, we can only
5064 // compare pointers within the object in question; otherwise, the result
5065 // depends on where the object is located in memory.
5066 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5067 QualType BaseTy = getType(LHSValue.Base);
5068 if (BaseTy->isIncompleteType())
5069 return Error(E);
5070 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5071 uint64_t OffsetLimit = Size.getQuantity();
5072 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5073 return Error(E);
5074 }
5075
Richard Smith625b8072011-10-31 01:37:14 +00005076 switch (E->getOpcode()) {
5077 default: llvm_unreachable("missing comparison operator");
Eli Friedmana3169882012-04-16 04:30:08 +00005078 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5079 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5080 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5081 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5082 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5083 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005084 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005085 }
5086 }
Richard Smithb02e4622012-02-01 01:42:44 +00005087
5088 if (LHSTy->isMemberPointerType()) {
5089 assert(E->isEqualityOp() && "unexpected member pointer operation");
5090 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5091
5092 MemberPtr LHSValue, RHSValue;
5093
5094 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5095 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5096 return false;
5097
5098 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5099 return false;
5100
5101 // C++11 [expr.eq]p2:
5102 // If both operands are null, they compare equal. Otherwise if only one is
5103 // null, they compare unequal.
5104 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5105 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5106 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5107 }
5108
5109 // Otherwise if either is a pointer to a virtual member function, the
5110 // result is unspecified.
5111 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5112 if (MD->isVirtual())
5113 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5114 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5115 if (MD->isVirtual())
5116 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5117
5118 // Otherwise they compare equal if and only if they would refer to the
5119 // same member of the same most derived object or the same subobject if
5120 // they were dereferenced with a hypothetical object of the associated
5121 // class type.
5122 bool Equal = LHSValue == RHSValue;
5123 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5124 }
5125
Richard Smith26f2cac2012-02-14 22:35:28 +00005126 if (LHSTy->isNullPtrType()) {
5127 assert(E->isComparisonOp() && "unexpected nullptr operation");
5128 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5129 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5130 // are compared, the result is true of the operator is <=, >= or ==, and
5131 // false otherwise.
5132 BinaryOperator::Opcode Opcode = E->getOpcode();
5133 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5134 }
5135
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005136 assert((!LHSTy->isIntegralOrEnumerationType() ||
5137 !RHSTy->isIntegralOrEnumerationType()) &&
5138 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5139 // We can't continue from here for non-integral types.
5140 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005141}
5142
Ken Dyck8b752f12010-01-27 17:10:57 +00005143CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005144 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5145 // result shall be the alignment of the referenced type."
5146 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5147 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005148
5149 // __alignof is defined to return the preferred alignment.
5150 return Info.Ctx.toCharUnitsFromBits(
5151 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005152}
5153
Ken Dyck8b752f12010-01-27 17:10:57 +00005154CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005155 E = E->IgnoreParens();
5156
5157 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005158 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005159 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005160 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5161 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005162
Chris Lattneraf707ab2009-01-24 21:53:27 +00005163 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005164 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5165 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005166
Chris Lattnere9feb472009-01-24 21:09:06 +00005167 return GetAlignOfType(E->getType());
5168}
5169
5170
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005171/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5172/// a result as the expression's type.
5173bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5174 const UnaryExprOrTypeTraitExpr *E) {
5175 switch(E->getKind()) {
5176 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005177 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005178 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005179 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005180 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005181 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005182
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005183 case UETT_VecStep: {
5184 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005185
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005186 if (Ty->isVectorType()) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00005187 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005188
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005189 // The vec_step built-in functions that take a 3-component
5190 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5191 if (n == 3)
5192 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005193
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005194 return Success(n, E);
5195 } else
5196 return Success(1, E);
5197 }
5198
5199 case UETT_SizeOf: {
5200 QualType SrcTy = E->getTypeOfArgument();
5201 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5202 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005203 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5204 SrcTy = Ref->getPointeeType();
5205
Richard Smith180f4792011-11-10 06:34:14 +00005206 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005207 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005208 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005209 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005210 }
5211 }
5212
5213 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005214}
5215
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005216bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005217 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005218 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005219 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005220 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005221 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005222 for (unsigned i = 0; i != n; ++i) {
5223 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5224 switch (ON.getKind()) {
5225 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005226 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005227 APSInt IdxResult;
5228 if (!EvaluateInteger(Idx, IdxResult, Info))
5229 return false;
5230 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5231 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005232 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005233 CurrentType = AT->getElementType();
5234 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5235 Result += IdxResult.getSExtValue() * ElementSize;
5236 break;
5237 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005238
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005239 case OffsetOfExpr::OffsetOfNode::Field: {
5240 FieldDecl *MemberDecl = ON.getField();
5241 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005242 if (!RT)
5243 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005244 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005245 if (RD->isInvalidDecl()) return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005246 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005247 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005248 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005249 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005250 CurrentType = MemberDecl->getType().getNonReferenceType();
5251 break;
5252 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005253
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005254 case OffsetOfExpr::OffsetOfNode::Identifier:
5255 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005256
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005257 case OffsetOfExpr::OffsetOfNode::Base: {
5258 CXXBaseSpecifier *BaseSpec = ON.getBase();
5259 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005260 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005261
5262 // Find the layout of the class whose base we are looking into.
5263 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005264 if (!RT)
5265 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005266 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005267 if (RD->isInvalidDecl()) return false;
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005268 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5269
5270 // Find the base class itself.
5271 CurrentType = BaseSpec->getType();
5272 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5273 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005274 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005275
5276 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005277 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005278 break;
5279 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005280 }
5281 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005282 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005283}
5284
Chris Lattnerb542afe2008-07-11 19:10:17 +00005285bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005286 switch (E->getOpcode()) {
5287 default:
5288 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5289 // See C99 6.6p3.
5290 return Error(E);
5291 case UO_Extension:
5292 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5293 // If so, we could clear the diagnostic ID.
5294 return Visit(E->getSubExpr());
5295 case UO_Plus:
5296 // The result is just the value.
5297 return Visit(E->getSubExpr());
5298 case UO_Minus: {
5299 if (!Visit(E->getSubExpr()))
5300 return false;
5301 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005302 const APSInt &Value = Result.getInt();
5303 if (Value.isSigned() && Value.isMinSignedValue())
5304 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5305 E->getType());
5306 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005307 }
5308 case UO_Not: {
5309 if (!Visit(E->getSubExpr()))
5310 return false;
5311 if (!Result.isInt()) return Error(E);
5312 return Success(~Result.getInt(), E);
5313 }
5314 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005315 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005316 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005317 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005318 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005319 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005320 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005321}
Mike Stump1eb44332009-09-09 15:08:12 +00005322
Chris Lattner732b2232008-07-12 01:15:53 +00005323/// HandleCast - This is used to evaluate implicit or explicit casts where the
5324/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005325bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5326 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005327 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005328 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005329
Eli Friedman46a52322011-03-25 00:43:55 +00005330 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005331 case CK_BaseToDerived:
5332 case CK_DerivedToBase:
5333 case CK_UncheckedDerivedToBase:
5334 case CK_Dynamic:
5335 case CK_ToUnion:
5336 case CK_ArrayToPointerDecay:
5337 case CK_FunctionToPointerDecay:
5338 case CK_NullToPointer:
5339 case CK_NullToMemberPointer:
5340 case CK_BaseToDerivedMemberPointer:
5341 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005342 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005343 case CK_ConstructorConversion:
5344 case CK_IntegralToPointer:
5345 case CK_ToVoid:
5346 case CK_VectorSplat:
5347 case CK_IntegralToFloating:
5348 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005349 case CK_CPointerToObjCPointerCast:
5350 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005351 case CK_AnyPointerToBlockPointerCast:
5352 case CK_ObjCObjectLValueCast:
5353 case CK_FloatingRealToComplex:
5354 case CK_FloatingComplexToReal:
5355 case CK_FloatingComplexCast:
5356 case CK_FloatingComplexToIntegralComplex:
5357 case CK_IntegralRealToComplex:
5358 case CK_IntegralComplexCast:
5359 case CK_IntegralComplexToFloatingComplex:
Eli Friedmana6c66ce2012-08-31 00:14:07 +00005360 case CK_BuiltinFnToFnPtr:
Eli Friedman46a52322011-03-25 00:43:55 +00005361 llvm_unreachable("invalid cast kind for integral value");
5362
Eli Friedmane50c2972011-03-25 19:07:11 +00005363 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005364 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005365 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005366 case CK_ARCProduceObject:
5367 case CK_ARCConsumeObject:
5368 case CK_ARCReclaimReturnedObject:
5369 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005370 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005371 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005372
Richard Smith7d580a42012-01-17 21:17:26 +00005373 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005374 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005375 case CK_AtomicToNonAtomic:
5376 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005377 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005378 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005379
5380 case CK_MemberPointerToBoolean:
5381 case CK_PointerToBoolean:
5382 case CK_IntegralToBoolean:
5383 case CK_FloatingToBoolean:
5384 case CK_FloatingComplexToBoolean:
5385 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005386 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005387 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005388 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005389 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005390 }
5391
Eli Friedman46a52322011-03-25 00:43:55 +00005392 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005393 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005394 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005395
Eli Friedmanbe265702009-02-20 01:15:07 +00005396 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005397 // Allow casts of address-of-label differences if they are no-ops
5398 // or narrowing. (The narrowing case isn't actually guaranteed to
5399 // be constant-evaluatable except in some narrow cases which are hard
5400 // to detect here. We let it through on the assumption the user knows
5401 // what they are doing.)
5402 if (Result.isAddrLabelDiff())
5403 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005404 // Only allow casts of lvalues if they are lossless.
5405 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5406 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005407
Richard Smithf72fccf2012-01-30 22:27:01 +00005408 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5409 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005410 }
Mike Stump1eb44332009-09-09 15:08:12 +00005411
Eli Friedman46a52322011-03-25 00:43:55 +00005412 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005413 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5414
John McCallefdb83e2010-05-07 21:00:08 +00005415 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005416 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005417 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005418
Daniel Dunbardd211642009-02-19 22:24:01 +00005419 if (LV.getLValueBase()) {
5420 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005421 // FIXME: Allow a larger integer size than the pointer size, and allow
5422 // narrowing back down to pointer width in subsequent integral casts.
5423 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005424 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005425 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005426
Richard Smithb755a9d2011-11-16 07:18:12 +00005427 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005428 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005429 return true;
5430 }
5431
Ken Dycka7305832010-01-15 12:37:54 +00005432 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5433 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005434 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005435 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005436
Eli Friedman46a52322011-03-25 00:43:55 +00005437 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005438 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005439 if (!EvaluateComplex(SubExpr, C, Info))
5440 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005441 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005442 }
Eli Friedman2217c872009-02-22 11:46:18 +00005443
Eli Friedman46a52322011-03-25 00:43:55 +00005444 case CK_FloatingToIntegral: {
5445 APFloat F(0.0);
5446 if (!EvaluateFloat(SubExpr, F, Info))
5447 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005448
Richard Smithc1c5f272011-12-13 06:39:58 +00005449 APSInt Value;
5450 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5451 return false;
5452 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005453 }
5454 }
Mike Stump1eb44332009-09-09 15:08:12 +00005455
Eli Friedman46a52322011-03-25 00:43:55 +00005456 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005457}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005458
Eli Friedman722c7172009-02-28 03:59:05 +00005459bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5460 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005461 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005462 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5463 return false;
5464 if (!LV.isComplexInt())
5465 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005466 return Success(LV.getComplexIntReal(), E);
5467 }
5468
5469 return Visit(E->getSubExpr());
5470}
5471
Eli Friedman664a1042009-02-27 04:45:43 +00005472bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005473 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005474 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005475 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5476 return false;
5477 if (!LV.isComplexInt())
5478 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005479 return Success(LV.getComplexIntImag(), E);
5480 }
5481
Richard Smith8327fad2011-10-24 18:44:57 +00005482 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005483 return Success(0, E);
5484}
5485
Douglas Gregoree8aff02011-01-04 17:33:58 +00005486bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5487 return Success(E->getPackLength(), E);
5488}
5489
Sebastian Redl295995c2010-09-10 20:55:47 +00005490bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5491 return Success(E->getValue(), E);
5492}
5493
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005494//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005495// Float Evaluation
5496//===----------------------------------------------------------------------===//
5497
5498namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005499class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005500 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005501 APFloat &Result;
5502public:
5503 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005504 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005505
Richard Smith1aa0be82012-03-03 22:46:17 +00005506 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005507 Result = V.getFloat();
5508 return true;
5509 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005510
Richard Smith51201882011-12-30 21:15:51 +00005511 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005512 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5513 return true;
5514 }
5515
Chris Lattner019f4e82008-10-06 05:28:25 +00005516 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005517
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005518 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005519 bool VisitBinaryOperator(const BinaryOperator *E);
5520 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005521 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005522
John McCallabd3a852010-05-07 22:08:54 +00005523 bool VisitUnaryReal(const UnaryOperator *E);
5524 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005525
Richard Smith51201882011-12-30 21:15:51 +00005526 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005527};
5528} // end anonymous namespace
5529
5530static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005531 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005532 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005533}
5534
Jay Foad4ba2a172011-01-12 09:06:06 +00005535static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005536 QualType ResultTy,
5537 const Expr *Arg,
5538 bool SNaN,
5539 llvm::APFloat &Result) {
5540 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5541 if (!S) return false;
5542
5543 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5544
5545 llvm::APInt fill;
5546
5547 // Treat empty strings as if they were zero.
5548 if (S->getString().empty())
5549 fill = llvm::APInt(32, 0);
5550 else if (S->getString().getAsInteger(0, fill))
5551 return false;
5552
5553 if (SNaN)
5554 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5555 else
5556 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5557 return true;
5558}
5559
Chris Lattner019f4e82008-10-06 05:28:25 +00005560bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005561 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005562 default:
5563 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5564
Chris Lattner019f4e82008-10-06 05:28:25 +00005565 case Builtin::BI__builtin_huge_val:
5566 case Builtin::BI__builtin_huge_valf:
5567 case Builtin::BI__builtin_huge_vall:
5568 case Builtin::BI__builtin_inf:
5569 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005570 case Builtin::BI__builtin_infl: {
5571 const llvm::fltSemantics &Sem =
5572 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005573 Result = llvm::APFloat::getInf(Sem);
5574 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005575 }
Mike Stump1eb44332009-09-09 15:08:12 +00005576
John McCalldb7b72a2010-02-28 13:00:19 +00005577 case Builtin::BI__builtin_nans:
5578 case Builtin::BI__builtin_nansf:
5579 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005580 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5581 true, Result))
5582 return Error(E);
5583 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005584
Chris Lattner9e621712008-10-06 06:31:58 +00005585 case Builtin::BI__builtin_nan:
5586 case Builtin::BI__builtin_nanf:
5587 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005588 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005589 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005590 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5591 false, Result))
5592 return Error(E);
5593 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005594
5595 case Builtin::BI__builtin_fabs:
5596 case Builtin::BI__builtin_fabsf:
5597 case Builtin::BI__builtin_fabsl:
5598 if (!EvaluateFloat(E->getArg(0), Result, Info))
5599 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005600
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005601 if (Result.isNegative())
5602 Result.changeSign();
5603 return true;
5604
Mike Stump1eb44332009-09-09 15:08:12 +00005605 case Builtin::BI__builtin_copysign:
5606 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005607 case Builtin::BI__builtin_copysignl: {
5608 APFloat RHS(0.);
5609 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5610 !EvaluateFloat(E->getArg(1), RHS, Info))
5611 return false;
5612 Result.copySign(RHS);
5613 return true;
5614 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005615 }
5616}
5617
John McCallabd3a852010-05-07 22:08:54 +00005618bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005619 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5620 ComplexValue CV;
5621 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5622 return false;
5623 Result = CV.FloatReal;
5624 return true;
5625 }
5626
5627 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005628}
5629
5630bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005631 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5632 ComplexValue CV;
5633 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5634 return false;
5635 Result = CV.FloatImag;
5636 return true;
5637 }
5638
Richard Smith8327fad2011-10-24 18:44:57 +00005639 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005640 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5641 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005642 return true;
5643}
5644
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005645bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005646 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005647 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005648 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005649 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005650 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005651 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5652 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005653 Result.changeSign();
5654 return true;
5655 }
5656}
Chris Lattner019f4e82008-10-06 05:28:25 +00005657
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005658bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005659 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5660 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005661
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005662 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005663 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5664 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005665 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005666 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005667 return false;
5668
5669 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005670 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005671 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005672 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005673 break;
John McCall2de56d12010-08-25 11:45:40 +00005674 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005675 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005676 break;
John McCall2de56d12010-08-25 11:45:40 +00005677 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005678 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005679 break;
John McCall2de56d12010-08-25 11:45:40 +00005680 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005681 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005682 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005683 }
Richard Smith7b48a292012-02-01 05:53:12 +00005684
5685 if (Result.isInfinity() || Result.isNaN())
5686 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5687 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005688}
5689
5690bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5691 Result = E->getValue();
5692 return true;
5693}
5694
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005695bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5696 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005697
Eli Friedman2a523ee2011-03-25 00:54:52 +00005698 switch (E->getCastKind()) {
5699 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005700 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005701
5702 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005703 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005704 return EvaluateInteger(SubExpr, IntResult, Info) &&
5705 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5706 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005707 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005708
5709 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005710 if (!Visit(SubExpr))
5711 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005712 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5713 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005714 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005715
Eli Friedman2a523ee2011-03-25 00:54:52 +00005716 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005717 ComplexValue V;
5718 if (!EvaluateComplex(SubExpr, V, Info))
5719 return false;
5720 Result = V.getComplexFloatReal();
5721 return true;
5722 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005723 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005724}
5725
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005726//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005727// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005728//===----------------------------------------------------------------------===//
5729
5730namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005731class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005732 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005733 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005734
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005735public:
John McCallf4cf1a12010-05-07 17:22:02 +00005736 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005737 : ExprEvaluatorBaseTy(info), Result(Result) {}
5738
Richard Smith1aa0be82012-03-03 22:46:17 +00005739 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005740 Result.setFrom(V);
5741 return true;
5742 }
Mike Stump1eb44332009-09-09 15:08:12 +00005743
Eli Friedman7ead5c72012-01-10 04:58:17 +00005744 bool ZeroInitialization(const Expr *E);
5745
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005746 //===--------------------------------------------------------------------===//
5747 // Visitor Methods
5748 //===--------------------------------------------------------------------===//
5749
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005750 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005751 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005752 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005753 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005754 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005755};
5756} // end anonymous namespace
5757
John McCallf4cf1a12010-05-07 17:22:02 +00005758static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5759 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005760 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005761 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005762}
5763
Eli Friedman7ead5c72012-01-10 04:58:17 +00005764bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00005765 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005766 if (ElemTy->isRealFloatingType()) {
5767 Result.makeComplexFloat();
5768 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5769 Result.FloatReal = Zero;
5770 Result.FloatImag = Zero;
5771 } else {
5772 Result.makeComplexInt();
5773 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5774 Result.IntReal = Zero;
5775 Result.IntImag = Zero;
5776 }
5777 return true;
5778}
5779
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005780bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5781 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005782
5783 if (SubExpr->getType()->isRealFloatingType()) {
5784 Result.makeComplexFloat();
5785 APFloat &Imag = Result.FloatImag;
5786 if (!EvaluateFloat(SubExpr, Imag, Info))
5787 return false;
5788
5789 Result.FloatReal = APFloat(Imag.getSemantics());
5790 return true;
5791 } else {
5792 assert(SubExpr->getType()->isIntegerType() &&
5793 "Unexpected imaginary literal.");
5794
5795 Result.makeComplexInt();
5796 APSInt &Imag = Result.IntImag;
5797 if (!EvaluateInteger(SubExpr, Imag, Info))
5798 return false;
5799
5800 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5801 return true;
5802 }
5803}
5804
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005805bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005806
John McCall8786da72010-12-14 17:51:41 +00005807 switch (E->getCastKind()) {
5808 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005809 case CK_BaseToDerived:
5810 case CK_DerivedToBase:
5811 case CK_UncheckedDerivedToBase:
5812 case CK_Dynamic:
5813 case CK_ToUnion:
5814 case CK_ArrayToPointerDecay:
5815 case CK_FunctionToPointerDecay:
5816 case CK_NullToPointer:
5817 case CK_NullToMemberPointer:
5818 case CK_BaseToDerivedMemberPointer:
5819 case CK_DerivedToBaseMemberPointer:
5820 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005821 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005822 case CK_ConstructorConversion:
5823 case CK_IntegralToPointer:
5824 case CK_PointerToIntegral:
5825 case CK_PointerToBoolean:
5826 case CK_ToVoid:
5827 case CK_VectorSplat:
5828 case CK_IntegralCast:
5829 case CK_IntegralToBoolean:
5830 case CK_IntegralToFloating:
5831 case CK_FloatingToIntegral:
5832 case CK_FloatingToBoolean:
5833 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005834 case CK_CPointerToObjCPointerCast:
5835 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005836 case CK_AnyPointerToBlockPointerCast:
5837 case CK_ObjCObjectLValueCast:
5838 case CK_FloatingComplexToReal:
5839 case CK_FloatingComplexToBoolean:
5840 case CK_IntegralComplexToReal:
5841 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005842 case CK_ARCProduceObject:
5843 case CK_ARCConsumeObject:
5844 case CK_ARCReclaimReturnedObject:
5845 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005846 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmana6c66ce2012-08-31 00:14:07 +00005847 case CK_BuiltinFnToFnPtr:
John McCall8786da72010-12-14 17:51:41 +00005848 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005849
John McCall8786da72010-12-14 17:51:41 +00005850 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005851 case CK_AtomicToNonAtomic:
5852 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005853 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005854 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005855
5856 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005857 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005858 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005859 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005860
5861 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005862 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005863 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005864 return false;
5865
John McCall8786da72010-12-14 17:51:41 +00005866 Result.makeComplexFloat();
5867 Result.FloatImag = APFloat(Real.getSemantics());
5868 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005869 }
5870
John McCall8786da72010-12-14 17:51:41 +00005871 case CK_FloatingComplexCast: {
5872 if (!Visit(E->getSubExpr()))
5873 return false;
5874
5875 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5876 QualType From
5877 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5878
Richard Smithc1c5f272011-12-13 06:39:58 +00005879 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5880 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005881 }
5882
5883 case CK_FloatingComplexToIntegralComplex: {
5884 if (!Visit(E->getSubExpr()))
5885 return false;
5886
5887 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5888 QualType From
5889 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5890 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005891 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5892 To, Result.IntReal) &&
5893 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5894 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005895 }
5896
5897 case CK_IntegralRealToComplex: {
5898 APSInt &Real = Result.IntReal;
5899 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5900 return false;
5901
5902 Result.makeComplexInt();
5903 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5904 return true;
5905 }
5906
5907 case CK_IntegralComplexCast: {
5908 if (!Visit(E->getSubExpr()))
5909 return false;
5910
5911 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5912 QualType From
5913 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5914
Richard Smithf72fccf2012-01-30 22:27:01 +00005915 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5916 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005917 return true;
5918 }
5919
5920 case CK_IntegralComplexToFloatingComplex: {
5921 if (!Visit(E->getSubExpr()))
5922 return false;
5923
Ted Kremenek890f0f12012-08-23 20:46:57 +00005924 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005925 QualType From
Ted Kremenek890f0f12012-08-23 20:46:57 +00005926 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005927 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005928 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5929 To, Result.FloatReal) &&
5930 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5931 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005932 }
5933 }
5934
5935 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005936}
5937
John McCallf4cf1a12010-05-07 17:22:02 +00005938bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005939 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005940 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5941
Richard Smith745f5142012-01-27 01:14:48 +00005942 bool LHSOK = Visit(E->getLHS());
5943 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005944 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005945
John McCallf4cf1a12010-05-07 17:22:02 +00005946 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005947 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005948 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005949
Daniel Dunbar3f279872009-01-29 01:32:56 +00005950 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5951 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005952 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005953 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005954 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005955 if (Result.isComplexFloat()) {
5956 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5957 APFloat::rmNearestTiesToEven);
5958 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5959 APFloat::rmNearestTiesToEven);
5960 } else {
5961 Result.getComplexIntReal() += RHS.getComplexIntReal();
5962 Result.getComplexIntImag() += RHS.getComplexIntImag();
5963 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005964 break;
John McCall2de56d12010-08-25 11:45:40 +00005965 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005966 if (Result.isComplexFloat()) {
5967 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5968 APFloat::rmNearestTiesToEven);
5969 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5970 APFloat::rmNearestTiesToEven);
5971 } else {
5972 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5973 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5974 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005975 break;
John McCall2de56d12010-08-25 11:45:40 +00005976 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005977 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005978 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005979 APFloat &LHS_r = LHS.getComplexFloatReal();
5980 APFloat &LHS_i = LHS.getComplexFloatImag();
5981 APFloat &RHS_r = RHS.getComplexFloatReal();
5982 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005983
Daniel Dunbar3f279872009-01-29 01:32:56 +00005984 APFloat Tmp = LHS_r;
5985 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5986 Result.getComplexFloatReal() = Tmp;
5987 Tmp = LHS_i;
5988 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5989 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5990
5991 Tmp = LHS_r;
5992 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5993 Result.getComplexFloatImag() = Tmp;
5994 Tmp = LHS_i;
5995 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5996 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5997 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005998 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005999 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006000 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6001 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00006002 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006003 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6004 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6005 }
6006 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006007 case BO_Div:
6008 if (Result.isComplexFloat()) {
6009 ComplexValue LHS = Result;
6010 APFloat &LHS_r = LHS.getComplexFloatReal();
6011 APFloat &LHS_i = LHS.getComplexFloatImag();
6012 APFloat &RHS_r = RHS.getComplexFloatReal();
6013 APFloat &RHS_i = RHS.getComplexFloatImag();
6014 APFloat &Res_r = Result.getComplexFloatReal();
6015 APFloat &Res_i = Result.getComplexFloatImag();
6016
6017 APFloat Den = RHS_r;
6018 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6019 APFloat Tmp = RHS_i;
6020 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6021 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6022
6023 Res_r = LHS_r;
6024 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6025 Tmp = LHS_i;
6026 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6027 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6028 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6029
6030 Res_i = LHS_i;
6031 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6032 Tmp = LHS_r;
6033 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6034 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6035 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6036 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006037 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6038 return Error(E, diag::note_expr_divide_by_zero);
6039
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006040 ComplexValue LHS = Result;
6041 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6042 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6043 Result.getComplexIntReal() =
6044 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6045 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6046 Result.getComplexIntImag() =
6047 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6048 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6049 }
6050 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006051 }
6052
John McCallf4cf1a12010-05-07 17:22:02 +00006053 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006054}
6055
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006056bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6057 // Get the operand value into 'Result'.
6058 if (!Visit(E->getSubExpr()))
6059 return false;
6060
6061 switch (E->getOpcode()) {
6062 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006063 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006064 case UO_Extension:
6065 return true;
6066 case UO_Plus:
6067 // The result is always just the subexpr.
6068 return true;
6069 case UO_Minus:
6070 if (Result.isComplexFloat()) {
6071 Result.getComplexFloatReal().changeSign();
6072 Result.getComplexFloatImag().changeSign();
6073 }
6074 else {
6075 Result.getComplexIntReal() = -Result.getComplexIntReal();
6076 Result.getComplexIntImag() = -Result.getComplexIntImag();
6077 }
6078 return true;
6079 case UO_Not:
6080 if (Result.isComplexFloat())
6081 Result.getComplexFloatImag().changeSign();
6082 else
6083 Result.getComplexIntImag() = -Result.getComplexIntImag();
6084 return true;
6085 }
6086}
6087
Eli Friedman7ead5c72012-01-10 04:58:17 +00006088bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6089 if (E->getNumInits() == 2) {
6090 if (E->getType()->isComplexType()) {
6091 Result.makeComplexFloat();
6092 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6093 return false;
6094 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6095 return false;
6096 } else {
6097 Result.makeComplexInt();
6098 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6099 return false;
6100 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6101 return false;
6102 }
6103 return true;
6104 }
6105 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6106}
6107
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006108//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006109// Void expression evaluation, primarily for a cast to void on the LHS of a
6110// comma operator
6111//===----------------------------------------------------------------------===//
6112
6113namespace {
6114class VoidExprEvaluator
6115 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6116public:
6117 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6118
Richard Smith1aa0be82012-03-03 22:46:17 +00006119 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006120
6121 bool VisitCastExpr(const CastExpr *E) {
6122 switch (E->getCastKind()) {
6123 default:
6124 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6125 case CK_ToVoid:
6126 VisitIgnoredValue(E->getSubExpr());
6127 return true;
6128 }
6129 }
6130};
6131} // end anonymous namespace
6132
6133static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6134 assert(E->isRValue() && E->getType()->isVoidType());
6135 return VoidExprEvaluator(Info).Visit(E);
6136}
6137
6138//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006139// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006140//===----------------------------------------------------------------------===//
6141
Richard Smith1aa0be82012-03-03 22:46:17 +00006142static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006143 // In C, function designators are not lvalues, but we evaluate them as if they
6144 // are.
6145 if (E->isGLValue() || E->getType()->isFunctionType()) {
6146 LValue LV;
6147 if (!EvaluateLValue(E, LV, Info))
6148 return false;
6149 LV.moveInto(Result);
6150 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006151 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006152 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006153 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006154 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006155 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006156 } else if (E->getType()->hasPointerRepresentation()) {
6157 LValue LV;
6158 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006159 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006160 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006161 } else if (E->getType()->isRealFloatingType()) {
6162 llvm::APFloat F(0.0);
6163 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006164 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006165 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006166 } else if (E->getType()->isAnyComplexType()) {
6167 ComplexValue C;
6168 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006169 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006170 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006171 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006172 MemberPtr P;
6173 if (!EvaluateMemberPointer(E, P, Info))
6174 return false;
6175 P.moveInto(Result);
6176 return true;
Richard Smith51201882011-12-30 21:15:51 +00006177 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006178 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006179 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006180 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006181 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006182 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006183 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006184 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006185 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006186 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6187 return false;
6188 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006189 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006190 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006191 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006192 << E->getType();
6193 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00006194 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006195 if (!EvaluateVoid(E, Info))
6196 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006197 } else if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006198 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006199 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006200 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006201 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006202 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006203 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006204
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006205 return true;
6206}
6207
Richard Smith83587db2012-02-15 02:18:13 +00006208/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6209/// cases, the in-place evaluation is essential, since later initializers for
6210/// an object can indirectly refer to subobjects which were initialized earlier.
6211static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6212 const Expr *E, CheckConstantExpressionKind CCEK,
6213 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006214 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006215 return false;
6216
6217 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006218 // Evaluate arrays and record types in-place, so that later initializers can
6219 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006220 if (E->getType()->isArrayType())
6221 return EvaluateArray(E, This, Result, Info);
6222 else if (E->getType()->isRecordType())
6223 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006224 }
6225
6226 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006227 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006228}
6229
Richard Smithf48fdb02011-12-09 22:58:01 +00006230/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6231/// lvalue-to-rvalue cast if it is an lvalue.
6232static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006233 if (!CheckLiteralType(Info, E))
6234 return false;
6235
Richard Smith1aa0be82012-03-03 22:46:17 +00006236 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006237 return false;
6238
6239 if (E->isGLValue()) {
6240 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006241 LV.setFrom(Info.Ctx, Result);
6242 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006243 return false;
6244 }
6245
Richard Smith1aa0be82012-03-03 22:46:17 +00006246 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006247 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006248}
Richard Smithc49bd112011-10-28 17:51:58 +00006249
Richard Smith51f47082011-10-29 00:50:52 +00006250/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006251/// any crazy technique (that has nothing to do with language standards) that
6252/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006253/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6254/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006255bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006256 // Fast-path evaluations of integer literals, since we sometimes see files
6257 // containing vast quantities of these.
6258 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6259 Result.Val = APValue(APSInt(L->getValue(),
6260 L->getType()->isUnsignedIntegerType()));
6261 return true;
6262 }
6263
Richard Smith2d6a5672012-01-14 04:30:29 +00006264 // FIXME: Evaluating values of large array and record types can cause
6265 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006266 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006267 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006268 return false;
6269
Richard Smithf48fdb02011-12-09 22:58:01 +00006270 EvalInfo Info(Ctx, Result);
6271 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006272}
6273
Jay Foad4ba2a172011-01-12 09:06:06 +00006274bool Expr::EvaluateAsBooleanCondition(bool &Result,
6275 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006276 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006277 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006278 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006279}
6280
Richard Smith80d4b552011-12-28 19:48:30 +00006281bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6282 SideEffectsKind AllowSideEffects) const {
6283 if (!getType()->isIntegralOrEnumerationType())
6284 return false;
6285
Richard Smithc49bd112011-10-28 17:51:58 +00006286 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006287 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6288 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006289 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006290
Richard Smithc49bd112011-10-28 17:51:58 +00006291 Result = ExprResult.Val.getInt();
6292 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006293}
6294
Jay Foad4ba2a172011-01-12 09:06:06 +00006295bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006296 EvalInfo Info(Ctx, Result);
6297
John McCallefdb83e2010-05-07 21:00:08 +00006298 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006299 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6300 !CheckLValueConstantExpression(Info, getExprLoc(),
6301 Ctx.getLValueReferenceType(getType()), LV))
6302 return false;
6303
Richard Smith1aa0be82012-03-03 22:46:17 +00006304 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006305 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006306}
6307
Richard Smith099e7f62011-12-19 06:19:21 +00006308bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6309 const VarDecl *VD,
6310 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006311 // FIXME: Evaluating initializers for large array and record types can cause
6312 // performance problems. Only do so in C++11 for now.
6313 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006314 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith2d6a5672012-01-14 04:30:29 +00006315 return false;
6316
Richard Smith099e7f62011-12-19 06:19:21 +00006317 Expr::EvalStatus EStatus;
6318 EStatus.Diag = &Notes;
6319
6320 EvalInfo InitInfo(Ctx, EStatus);
6321 InitInfo.setEvaluatingDecl(VD, Value);
6322
6323 LValue LVal;
6324 LVal.set(VD);
6325
Richard Smith51201882011-12-30 21:15:51 +00006326 // C++11 [basic.start.init]p2:
6327 // Variables with static storage duration or thread storage duration shall be
6328 // zero-initialized before any other initialization takes place.
6329 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006330 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006331 !VD->getType()->isReferenceType()) {
6332 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006333 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6334 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006335 return false;
6336 }
6337
Richard Smith83587db2012-02-15 02:18:13 +00006338 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6339 /*AllowNonLiteralTypes=*/true) ||
6340 EStatus.HasSideEffects)
6341 return false;
6342
6343 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6344 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006345}
6346
Richard Smith51f47082011-10-29 00:50:52 +00006347/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6348/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006349bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006350 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006351 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006352}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006353
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006354APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006355 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006356 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006357 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006358 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006359 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006360
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006361 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006362}
John McCalld905f5a2010-05-07 05:32:02 +00006363
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006364 bool Expr::EvalResult::isGlobalLValue() const {
6365 assert(Val.isLValue());
6366 return IsGlobalLValue(Val.getLValueBase());
6367 }
6368
6369
John McCalld905f5a2010-05-07 05:32:02 +00006370/// isIntegerConstantExpr - this recursive routine will test if an expression is
6371/// an integer constant expression.
6372
6373/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6374/// comma, etc
6375///
6376/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6377/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6378/// cast+dereference.
6379
6380// CheckICE - This function does the fundamental ICE checking: the returned
6381// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6382// Note that to reduce code duplication, this helper does no evaluation
6383// itself; the caller checks whether the expression is evaluatable, and
6384// in the rare cases where CheckICE actually cares about the evaluated
6385// value, it calls into Evalute.
6386//
6387// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006388// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006389// 1: This expression is not an ICE, but if it isn't evaluated, it's
6390// a legal subexpression for an ICE. This return value is used to handle
6391// the comma operator in C99 mode.
6392// 2: This expression is not an ICE, and is not a legal subexpression for one.
6393
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006394namespace {
6395
John McCalld905f5a2010-05-07 05:32:02 +00006396struct ICEDiag {
6397 unsigned Val;
6398 SourceLocation Loc;
6399
6400 public:
6401 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6402 ICEDiag() : Val(0) {}
6403};
6404
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006405}
6406
6407static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006408
6409static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6410 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006411 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006412 !EVResult.Val.isInt()) {
6413 return ICEDiag(2, E->getLocStart());
6414 }
6415 return NoDiag();
6416}
6417
6418static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6419 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006420 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006421 return ICEDiag(2, E->getLocStart());
6422 }
6423
6424 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006425#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006426#define STMT(Node, Base) case Expr::Node##Class:
6427#define EXPR(Node, Base)
6428#include "clang/AST/StmtNodes.inc"
6429 case Expr::PredefinedExprClass:
6430 case Expr::FloatingLiteralClass:
6431 case Expr::ImaginaryLiteralClass:
6432 case Expr::StringLiteralClass:
6433 case Expr::ArraySubscriptExprClass:
6434 case Expr::MemberExprClass:
6435 case Expr::CompoundAssignOperatorClass:
6436 case Expr::CompoundLiteralExprClass:
6437 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006438 case Expr::DesignatedInitExprClass:
6439 case Expr::ImplicitValueInitExprClass:
6440 case Expr::ParenListExprClass:
6441 case Expr::VAArgExprClass:
6442 case Expr::AddrLabelExprClass:
6443 case Expr::StmtExprClass:
6444 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006445 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006446 case Expr::CXXDynamicCastExprClass:
6447 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006448 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006449 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006450 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006451 case Expr::CXXThisExprClass:
6452 case Expr::CXXThrowExprClass:
6453 case Expr::CXXNewExprClass:
6454 case Expr::CXXDeleteExprClass:
6455 case Expr::CXXPseudoDestructorExprClass:
6456 case Expr::UnresolvedLookupExprClass:
6457 case Expr::DependentScopeDeclRefExprClass:
6458 case Expr::CXXConstructExprClass:
6459 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006460 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006461 case Expr::CXXTemporaryObjectExprClass:
6462 case Expr::CXXUnresolvedConstructExprClass:
6463 case Expr::CXXDependentScopeMemberExprClass:
6464 case Expr::UnresolvedMemberExprClass:
6465 case Expr::ObjCStringLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00006466 case Expr::ObjCBoxedExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006467 case Expr::ObjCArrayLiteralClass:
6468 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006469 case Expr::ObjCEncodeExprClass:
6470 case Expr::ObjCMessageExprClass:
6471 case Expr::ObjCSelectorExprClass:
6472 case Expr::ObjCProtocolExprClass:
6473 case Expr::ObjCIvarRefExprClass:
6474 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006475 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006476 case Expr::ObjCIsaExprClass:
6477 case Expr::ShuffleVectorExprClass:
6478 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006479 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006480 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006481 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006482 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smith9a4db032012-09-12 00:56:43 +00006483 case Expr::FunctionParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006484 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006485 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006486 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006487 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006488 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006489 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006490 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006491 return ICEDiag(2, E->getLocStart());
6492
Douglas Gregoree8aff02011-01-04 17:33:58 +00006493 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006494 case Expr::GNUNullExprClass:
6495 // GCC considers the GNU __null value to be an integral constant expression.
6496 return NoDiag();
6497
John McCall91a57552011-07-15 05:09:51 +00006498 case Expr::SubstNonTypeTemplateParmExprClass:
6499 return
6500 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6501
John McCalld905f5a2010-05-07 05:32:02 +00006502 case Expr::ParenExprClass:
6503 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006504 case Expr::GenericSelectionExprClass:
6505 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006506 case Expr::IntegerLiteralClass:
6507 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006508 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006509 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006510 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006511 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006512 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006513 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006514 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006515 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006516 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006517 return NoDiag();
6518 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006519 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006520 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6521 // constant expressions, but they can never be ICEs because an ICE cannot
6522 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006523 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006524 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006525 return CheckEvalInICE(E, Ctx);
6526 return ICEDiag(2, E->getLocStart());
6527 }
Richard Smith359c89d2012-02-24 22:12:32 +00006528 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006529 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6530 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006531 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006532 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006533 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006534 // Parameter variables are never constants. Without this check,
6535 // getAnyInitializer() can find a default argument, which leads
6536 // to chaos.
6537 if (isa<ParmVarDecl>(D))
6538 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6539
6540 // C++ 7.1.5.1p2
6541 // A variable of non-volatile const-qualified integral or enumeration
6542 // type initialized by an ICE can be used in ICEs.
6543 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006544 if (!Dcl->getType()->isIntegralOrEnumerationType())
6545 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6546
Richard Smith099e7f62011-12-19 06:19:21 +00006547 const VarDecl *VD;
6548 // Look for a declaration of this variable that has an initializer, and
6549 // check whether it is an ICE.
6550 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6551 return NoDiag();
6552 else
6553 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006554 }
6555 }
6556 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006557 }
John McCalld905f5a2010-05-07 05:32:02 +00006558 case Expr::UnaryOperatorClass: {
6559 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6560 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006561 case UO_PostInc:
6562 case UO_PostDec:
6563 case UO_PreInc:
6564 case UO_PreDec:
6565 case UO_AddrOf:
6566 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006567 // C99 6.6/3 allows increment and decrement within unevaluated
6568 // subexpressions of constant expressions, but they can never be ICEs
6569 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006570 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006571 case UO_Extension:
6572 case UO_LNot:
6573 case UO_Plus:
6574 case UO_Minus:
6575 case UO_Not:
6576 case UO_Real:
6577 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006578 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006579 }
6580
6581 // OffsetOf falls through here.
6582 }
6583 case Expr::OffsetOfExprClass: {
6584 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006585 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006586 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006587 // compliance: we should warn earlier for offsetof expressions with
6588 // array subscripts that aren't ICEs, and if the array subscripts
6589 // are ICEs, the value of the offsetof must be an integer constant.
6590 return CheckEvalInICE(E, Ctx);
6591 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006592 case Expr::UnaryExprOrTypeTraitExprClass: {
6593 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6594 if ((Exp->getKind() == UETT_SizeOf) &&
6595 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006596 return ICEDiag(2, E->getLocStart());
6597 return NoDiag();
6598 }
6599 case Expr::BinaryOperatorClass: {
6600 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6601 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006602 case BO_PtrMemD:
6603 case BO_PtrMemI:
6604 case BO_Assign:
6605 case BO_MulAssign:
6606 case BO_DivAssign:
6607 case BO_RemAssign:
6608 case BO_AddAssign:
6609 case BO_SubAssign:
6610 case BO_ShlAssign:
6611 case BO_ShrAssign:
6612 case BO_AndAssign:
6613 case BO_XorAssign:
6614 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006615 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6616 // constant expressions, but they can never be ICEs because an ICE cannot
6617 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006618 return ICEDiag(2, E->getLocStart());
6619
John McCall2de56d12010-08-25 11:45:40 +00006620 case BO_Mul:
6621 case BO_Div:
6622 case BO_Rem:
6623 case BO_Add:
6624 case BO_Sub:
6625 case BO_Shl:
6626 case BO_Shr:
6627 case BO_LT:
6628 case BO_GT:
6629 case BO_LE:
6630 case BO_GE:
6631 case BO_EQ:
6632 case BO_NE:
6633 case BO_And:
6634 case BO_Xor:
6635 case BO_Or:
6636 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006637 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6638 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006639 if (Exp->getOpcode() == BO_Div ||
6640 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006641 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006642 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006643 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006644 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006645 if (REval == 0)
6646 return ICEDiag(1, E->getLocStart());
6647 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006648 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006649 if (LEval.isMinSignedValue())
6650 return ICEDiag(1, E->getLocStart());
6651 }
6652 }
6653 }
John McCall2de56d12010-08-25 11:45:40 +00006654 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006655 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006656 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6657 // if it isn't evaluated.
6658 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6659 return ICEDiag(1, E->getLocStart());
6660 } else {
6661 // In both C89 and C++, commas in ICEs are illegal.
6662 return ICEDiag(2, E->getLocStart());
6663 }
6664 }
6665 if (LHSResult.Val >= RHSResult.Val)
6666 return LHSResult;
6667 return RHSResult;
6668 }
John McCall2de56d12010-08-25 11:45:40 +00006669 case BO_LAnd:
6670 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006671 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6672 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6673 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6674 // Rare case where the RHS has a comma "side-effect"; we need
6675 // to actually check the condition to see whether the side
6676 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006677 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006678 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006679 return RHSResult;
6680 return NoDiag();
6681 }
6682
6683 if (LHSResult.Val >= RHSResult.Val)
6684 return LHSResult;
6685 return RHSResult;
6686 }
6687 }
6688 }
6689 case Expr::ImplicitCastExprClass:
6690 case Expr::CStyleCastExprClass:
6691 case Expr::CXXFunctionalCastExprClass:
6692 case Expr::CXXStaticCastExprClass:
6693 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006694 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006695 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006696 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006697 if (isa<ExplicitCastExpr>(E)) {
6698 if (const FloatingLiteral *FL
6699 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6700 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6701 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6702 APSInt IgnoredVal(DestWidth, !DestSigned);
6703 bool Ignored;
6704 // If the value does not fit in the destination type, the behavior is
6705 // undefined, so we are not required to treat it as a constant
6706 // expression.
6707 if (FL->getValue().convertToInteger(IgnoredVal,
6708 llvm::APFloat::rmTowardZero,
6709 &Ignored) & APFloat::opInvalidOp)
6710 return ICEDiag(2, E->getLocStart());
6711 return NoDiag();
6712 }
6713 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006714 switch (cast<CastExpr>(E)->getCastKind()) {
6715 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006716 case CK_AtomicToNonAtomic:
6717 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006718 case CK_NoOp:
6719 case CK_IntegralToBoolean:
6720 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006721 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006722 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006723 return ICEDiag(2, E->getLocStart());
6724 }
John McCalld905f5a2010-05-07 05:32:02 +00006725 }
John McCall56ca35d2011-02-17 10:25:35 +00006726 case Expr::BinaryConditionalOperatorClass: {
6727 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6728 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6729 if (CommonResult.Val == 2) return CommonResult;
6730 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6731 if (FalseResult.Val == 2) return FalseResult;
6732 if (CommonResult.Val == 1) return CommonResult;
6733 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006734 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006735 return FalseResult;
6736 }
John McCalld905f5a2010-05-07 05:32:02 +00006737 case Expr::ConditionalOperatorClass: {
6738 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6739 // If the condition (ignoring parens) is a __builtin_constant_p call,
6740 // then only the true side is actually considered in an integer constant
6741 // expression, and it is fully evaluated. This is an important GNU
6742 // extension. See GCC PR38377 for discussion.
6743 if (const CallExpr *CallCE
6744 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006745 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6746 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006747 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006748 if (CondResult.Val == 2)
6749 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006750
Richard Smithf48fdb02011-12-09 22:58:01 +00006751 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6752 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006753
John McCalld905f5a2010-05-07 05:32:02 +00006754 if (TrueResult.Val == 2)
6755 return TrueResult;
6756 if (FalseResult.Val == 2)
6757 return FalseResult;
6758 if (CondResult.Val == 1)
6759 return CondResult;
6760 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6761 return NoDiag();
6762 // Rare case where the diagnostics depend on which side is evaluated
6763 // Note that if we get here, CondResult is 0, and at least one of
6764 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006765 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006766 return FalseResult;
6767 }
6768 return TrueResult;
6769 }
6770 case Expr::CXXDefaultArgExprClass:
6771 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6772 case Expr::ChooseExprClass: {
6773 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6774 }
6775 }
6776
David Blaikie30263482012-01-20 21:50:17 +00006777 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006778}
6779
Richard Smithf48fdb02011-12-09 22:58:01 +00006780/// Evaluate an expression as a C++11 integral constant expression.
6781static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6782 const Expr *E,
6783 llvm::APSInt *Value,
6784 SourceLocation *Loc) {
6785 if (!E->getType()->isIntegralOrEnumerationType()) {
6786 if (Loc) *Loc = E->getExprLoc();
6787 return false;
6788 }
6789
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006790 APValue Result;
6791 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006792 return false;
6793
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006794 assert(Result.isInt() && "pointer cast to int is not an ICE");
6795 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006796 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006797}
6798
Richard Smithdd1f29b2011-12-12 09:28:41 +00006799bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006800 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006801 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6802
John McCalld905f5a2010-05-07 05:32:02 +00006803 ICEDiag d = CheckICE(this, Ctx);
6804 if (d.Val != 0) {
6805 if (Loc) *Loc = d.Loc;
6806 return false;
6807 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006808 return true;
6809}
6810
6811bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6812 SourceLocation *Loc, bool isEvaluated) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006813 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006814 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6815
6816 if (!isIntegerConstantExpr(Ctx, Loc))
6817 return false;
6818 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006819 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006820 return true;
6821}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006822
Richard Smith70488e22012-02-14 21:38:30 +00006823bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6824 return CheckICE(this, Ctx).Val == 0;
6825}
6826
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006827bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6828 SourceLocation *Loc) const {
6829 // We support this checking in C++98 mode in order to diagnose compatibility
6830 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006831 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006832
Richard Smith70488e22012-02-14 21:38:30 +00006833 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006834 Expr::EvalStatus Status;
6835 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6836 Status.Diag = &Diags;
6837 EvalInfo Info(Ctx, Status);
6838
6839 APValue Scratch;
6840 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6841
6842 if (!Diags.empty()) {
6843 IsConstExpr = false;
6844 if (Loc) *Loc = Diags[0].first;
6845 } else if (!IsConstExpr) {
6846 // FIXME: This shouldn't happen.
6847 if (Loc) *Loc = getExprLoc();
6848 }
6849
6850 return IsConstExpr;
6851}
Richard Smith745f5142012-01-27 01:14:48 +00006852
6853bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6854 llvm::SmallVectorImpl<
6855 PartialDiagnosticAt> &Diags) {
6856 // FIXME: It would be useful to check constexpr function templates, but at the
6857 // moment the constant expression evaluator cannot cope with the non-rigorous
6858 // ASTs which we build for dependent expressions.
6859 if (FD->isDependentContext())
6860 return true;
6861
6862 Expr::EvalStatus Status;
6863 Status.Diag = &Diags;
6864
6865 EvalInfo Info(FD->getASTContext(), Status);
6866 Info.CheckingPotentialConstantExpression = true;
6867
6868 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6869 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6870
6871 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6872 // is a temporary being used as the 'this' pointer.
6873 LValue This;
6874 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006875 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006876
Richard Smith745f5142012-01-27 01:14:48 +00006877 ArrayRef<const Expr*> Args;
6878
6879 SourceLocation Loc = FD->getLocation();
6880
Richard Smith1aa0be82012-03-03 22:46:17 +00006881 APValue Scratch;
6882 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006883 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006884 else
Richard Smith745f5142012-01-27 01:14:48 +00006885 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6886 Args, FD->getBody(), Info, Scratch);
6887
6888 return Diags.empty();
6889}