blob: ad5aa54e4830f8d0843f9146c090ee6c23a2e317 [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
956 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
957 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
990 // Allow address constant expressions to be past-the-end pointers. This is
991 // an extension: the standard requires them to point to an object.
992 if (!IsReferenceType)
993 return true;
994
995 // A reference constant expression must refer to an object.
996 if (!Base) {
997 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +0000998 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +0000999 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001000 }
1001
Richard Smithc1c5f272011-12-13 06:39:58 +00001002 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001003 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001004 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001005 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001006 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001007 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001008 }
1009
Richard Smith9a17a682011-11-07 05:07:52 +00001010 return true;
1011}
1012
Richard Smith51201882011-12-30 21:15:51 +00001013/// Check that this core constant expression is of literal type, and if not,
1014/// produce an appropriate diagnostic.
1015static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1016 if (!E->isRValue() || E->getType()->isLiteralType())
1017 return true;
1018
1019 // Prvalue constant expressions must be of literal types.
1020 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001021 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001022 << E->getType();
1023 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001024 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001025 return false;
1026}
1027
Richard Smith47a1eed2011-10-29 20:57:55 +00001028/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001029/// constant expression. If not, report an appropriate diagnostic. Does not
1030/// check that the expression is of literal type.
1031static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1032 QualType Type, const APValue &Value) {
1033 // Core issue 1454: For a literal constant expression of array or class type,
1034 // each subobject of its value shall have been initialized by a constant
1035 // expression.
1036 if (Value.isArray()) {
1037 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1038 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1039 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1040 Value.getArrayInitializedElt(I)))
1041 return false;
1042 }
1043 if (!Value.hasArrayFiller())
1044 return true;
1045 return CheckConstantExpression(Info, DiagLoc, EltTy,
1046 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001047 }
Richard Smith83587db2012-02-15 02:18:13 +00001048 if (Value.isUnion() && Value.getUnionField()) {
1049 return CheckConstantExpression(Info, DiagLoc,
1050 Value.getUnionField()->getType(),
1051 Value.getUnionValue());
1052 }
1053 if (Value.isStruct()) {
1054 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1055 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1056 unsigned BaseIndex = 0;
1057 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1058 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1059 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1060 Value.getStructBase(BaseIndex)))
1061 return false;
1062 }
1063 }
1064 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1065 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001066 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1067 Value.getStructField(I->getFieldIndex())))
Richard Smith83587db2012-02-15 02:18:13 +00001068 return false;
1069 }
1070 }
1071
1072 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001073 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001074 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001075 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1076 }
1077
1078 // Everything else is fine.
1079 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001080}
1081
Richard Smith9e36b532011-10-31 05:11:32 +00001082const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001083 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001084}
1085
1086static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001087 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001088}
1089
Richard Smith65ac5982011-11-01 21:06:14 +00001090static bool IsWeakLValue(const LValue &Value) {
1091 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001092 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001093}
1094
Richard Smith1aa0be82012-03-03 22:46:17 +00001095static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001096 // A null base expression indicates a null pointer. These are always
1097 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001098 if (!Value.getLValueBase()) {
1099 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001100 return true;
1101 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001102
Richard Smithe24f5fc2011-11-17 22:56:20 +00001103 // We have a non-null base. These are generally known to be true, but if it's
1104 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001105 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001106 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001107 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001108}
1109
Richard Smith1aa0be82012-03-03 22:46:17 +00001110static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001111 switch (Val.getKind()) {
1112 case APValue::Uninitialized:
1113 return false;
1114 case APValue::Int:
1115 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001116 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001117 case APValue::Float:
1118 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001119 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001120 case APValue::ComplexInt:
1121 Result = Val.getComplexIntReal().getBoolValue() ||
1122 Val.getComplexIntImag().getBoolValue();
1123 return true;
1124 case APValue::ComplexFloat:
1125 Result = !Val.getComplexFloatReal().isZero() ||
1126 !Val.getComplexFloatImag().isZero();
1127 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001128 case APValue::LValue:
1129 return EvalPointerValueAsBool(Val, Result);
1130 case APValue::MemberPointer:
1131 Result = Val.getMemberPointerDecl();
1132 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001133 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001134 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001135 case APValue::Struct:
1136 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001137 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001138 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001139 }
1140
Richard Smithc49bd112011-10-28 17:51:58 +00001141 llvm_unreachable("unknown APValue kind");
1142}
1143
1144static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1145 EvalInfo &Info) {
1146 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001147 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001148 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001149 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001150 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001151}
1152
Richard Smithc1c5f272011-12-13 06:39:58 +00001153template<typename T>
1154static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1155 const T &SrcValue, QualType DestType) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001156 Info.Diag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001157 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001158 return false;
1159}
1160
1161static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1162 QualType SrcType, const APFloat &Value,
1163 QualType DestType, APSInt &Result) {
1164 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001165 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001166 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001167
Richard Smithc1c5f272011-12-13 06:39:58 +00001168 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001169 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001170 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1171 & APFloat::opInvalidOp)
1172 return HandleOverflow(Info, E, Value, DestType);
1173 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001174}
1175
Richard Smithc1c5f272011-12-13 06:39:58 +00001176static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1177 QualType SrcType, QualType DestType,
1178 APFloat &Result) {
1179 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001180 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001181 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1182 APFloat::rmNearestTiesToEven, &ignored)
1183 & APFloat::opOverflow)
1184 return HandleOverflow(Info, E, Value, DestType);
1185 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001186}
1187
Richard Smithf72fccf2012-01-30 22:27:01 +00001188static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1189 QualType DestType, QualType SrcType,
1190 APSInt &Value) {
1191 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001192 APSInt Result = Value;
1193 // Figure out if this is a truncate, extend or noop cast.
1194 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001195 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001196 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001197 return Result;
1198}
1199
Richard Smithc1c5f272011-12-13 06:39:58 +00001200static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1201 QualType SrcType, const APSInt &Value,
1202 QualType DestType, APFloat &Result) {
1203 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1204 if (Result.convertFromAPInt(Value, Value.isSigned(),
1205 APFloat::rmNearestTiesToEven)
1206 & APFloat::opOverflow)
1207 return HandleOverflow(Info, E, Value, DestType);
1208 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001209}
1210
Eli Friedmane6a24e82011-12-22 03:51:45 +00001211static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1212 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001213 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001214 if (!Evaluate(SVal, Info, E))
1215 return false;
1216 if (SVal.isInt()) {
1217 Res = SVal.getInt();
1218 return true;
1219 }
1220 if (SVal.isFloat()) {
1221 Res = SVal.getFloat().bitcastToAPInt();
1222 return true;
1223 }
1224 if (SVal.isVector()) {
1225 QualType VecTy = E->getType();
1226 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1227 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1228 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1229 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1230 Res = llvm::APInt::getNullValue(VecSize);
1231 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1232 APValue &Elt = SVal.getVectorElt(i);
1233 llvm::APInt EltAsInt;
1234 if (Elt.isInt()) {
1235 EltAsInt = Elt.getInt();
1236 } else if (Elt.isFloat()) {
1237 EltAsInt = Elt.getFloat().bitcastToAPInt();
1238 } else {
1239 // Don't try to handle vectors of anything other than int or float
1240 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001241 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001242 return false;
1243 }
1244 unsigned BaseEltSize = EltAsInt.getBitWidth();
1245 if (BigEndian)
1246 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1247 else
1248 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1249 }
1250 return true;
1251 }
1252 // Give up if the input isn't an int, float, or vector. For example, we
1253 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001254 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001255 return false;
1256}
1257
Richard Smithb4e85ed2012-01-06 16:39:00 +00001258/// Cast an lvalue referring to a base subobject to a derived class, by
1259/// truncating the lvalue's path to the given length.
1260static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1261 const RecordDecl *TruncatedType,
1262 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001263 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001264
1265 // Check we actually point to a derived class object.
1266 if (TruncatedElements == D.Entries.size())
1267 return true;
1268 assert(TruncatedElements >= D.MostDerivedPathLength &&
1269 "not casting to a derived class");
1270 if (!Result.checkSubobject(Info, E, CSK_Derived))
1271 return false;
1272
1273 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001274 const RecordDecl *RD = TruncatedType;
1275 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCall8d59dee2012-05-01 00:38:49 +00001276 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001277 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1278 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001279 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001280 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001281 else
Richard Smith180f4792011-11-10 06:34:14 +00001282 Result.Offset -= Layout.getBaseClassOffset(Base);
1283 RD = Base;
1284 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001285 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001286 return true;
1287}
1288
John McCall8d59dee2012-05-01 00:38:49 +00001289static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001290 const CXXRecordDecl *Derived,
1291 const CXXRecordDecl *Base,
1292 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001293 if (!RL) {
1294 if (Derived->isInvalidDecl()) return false;
1295 RL = &Info.Ctx.getASTRecordLayout(Derived);
1296 }
1297
Richard Smith180f4792011-11-10 06:34:14 +00001298 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001299 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCall8d59dee2012-05-01 00:38:49 +00001300 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001301}
1302
Richard Smithb4e85ed2012-01-06 16:39:00 +00001303static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001304 const CXXRecordDecl *DerivedDecl,
1305 const CXXBaseSpecifier *Base) {
1306 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1307
John McCall8d59dee2012-05-01 00:38:49 +00001308 if (!Base->isVirtual())
1309 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001310
Richard Smithb4e85ed2012-01-06 16:39:00 +00001311 SubobjectDesignator &D = Obj.Designator;
1312 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001313 return false;
1314
Richard Smithb4e85ed2012-01-06 16:39:00 +00001315 // Extract most-derived object and corresponding type.
1316 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1317 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1318 return false;
1319
1320 // Find the virtual base class.
John McCall8d59dee2012-05-01 00:38:49 +00001321 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001322 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1323 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001324 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001325 return true;
1326}
1327
1328/// Update LVal to refer to the given field, which must be a member of the type
1329/// currently described by LVal.
John McCall8d59dee2012-05-01 00:38:49 +00001330static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001331 const FieldDecl *FD,
1332 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001333 if (!RL) {
1334 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001335 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCall8d59dee2012-05-01 00:38:49 +00001336 }
Richard Smith180f4792011-11-10 06:34:14 +00001337
1338 unsigned I = FD->getFieldIndex();
1339 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001340 LVal.addDecl(Info, E, FD);
John McCall8d59dee2012-05-01 00:38:49 +00001341 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001342}
1343
Richard Smithd9b02e72012-01-25 22:15:11 +00001344/// Update LVal to refer to the given indirect field.
John McCall8d59dee2012-05-01 00:38:49 +00001345static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smithd9b02e72012-01-25 22:15:11 +00001346 LValue &LVal,
1347 const IndirectFieldDecl *IFD) {
1348 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1349 CE = IFD->chain_end(); C != CE; ++C)
John McCall8d59dee2012-05-01 00:38:49 +00001350 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1351 return false;
1352 return true;
Richard Smithd9b02e72012-01-25 22:15:11 +00001353}
1354
Richard Smith180f4792011-11-10 06:34:14 +00001355/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001356static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1357 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001358 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1359 // extension.
1360 if (Type->isVoidType() || Type->isFunctionType()) {
1361 Size = CharUnits::One();
1362 return true;
1363 }
1364
1365 if (!Type->isConstantSizeType()) {
1366 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001367 // FIXME: Better diagnostic.
1368 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001369 return false;
1370 }
1371
1372 Size = Info.Ctx.getTypeSizeInChars(Type);
1373 return true;
1374}
1375
1376/// Update a pointer value to model pointer arithmetic.
1377/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001378/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001379/// \param LVal - The pointer value to be updated.
1380/// \param EltTy - The pointee type represented by LVal.
1381/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001382static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1383 LValue &LVal, QualType EltTy,
1384 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001385 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001386 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001387 return false;
1388
1389 // Compute the new offset in the appropriate width.
1390 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001391 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001392 return true;
1393}
1394
Richard Smith86024012012-02-18 22:04:06 +00001395/// Update an lvalue to refer to a component of a complex number.
1396/// \param Info - Information about the ongoing evaluation.
1397/// \param LVal - The lvalue to be updated.
1398/// \param EltTy - The complex number's component type.
1399/// \param Imag - False for the real component, true for the imaginary.
1400static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1401 LValue &LVal, QualType EltTy,
1402 bool Imag) {
1403 if (Imag) {
1404 CharUnits SizeOfComponent;
1405 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1406 return false;
1407 LVal.Offset += SizeOfComponent;
1408 }
1409 LVal.addComplex(Info, E, EltTy, Imag);
1410 return true;
1411}
1412
Richard Smith03f96112011-10-24 17:54:18 +00001413/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001414static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1415 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001416 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001417 // If this is a parameter to an active constexpr function call, perform
1418 // argument substitution.
1419 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001420 // Assume arguments of a potential constant expression are unknown
1421 // constant expressions.
1422 if (Info.CheckingPotentialConstantExpression)
1423 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001424 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001425 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001426 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001427 }
Richard Smith177dce72011-11-01 16:57:24 +00001428 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1429 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001430 }
Richard Smith03f96112011-10-24 17:54:18 +00001431
Richard Smith099e7f62011-12-19 06:19:21 +00001432 // Dig out the initializer, and use the declaration which it's attached to.
1433 const Expr *Init = VD->getAnyInitializer(VD);
1434 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001435 // If we're checking a potential constant expression, the variable could be
1436 // initialized later.
1437 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001438 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001439 return false;
1440 }
1441
Richard Smith180f4792011-11-10 06:34:14 +00001442 // If we're currently evaluating the initializer of this declaration, use that
1443 // in-flight value.
1444 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001445 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001446 return !Result.isUninit();
1447 }
1448
Richard Smith65ac5982011-11-01 21:06:14 +00001449 // Never evaluate the initializer of a weak variable. We can't be sure that
1450 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001451 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001452 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001453 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001454 }
Richard Smith65ac5982011-11-01 21:06:14 +00001455
Richard Smith099e7f62011-12-19 06:19:21 +00001456 // Check that we can fold the initializer. In C++, we will have already done
1457 // this in the cases where it matters for conformance.
1458 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1459 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001460 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001461 Notes.size() + 1) << VD;
1462 Info.Note(VD->getLocation(), diag::note_declared_at);
1463 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001464 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001465 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001466 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001467 Notes.size() + 1) << VD;
1468 Info.Note(VD->getLocation(), diag::note_declared_at);
1469 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001470 }
Richard Smith03f96112011-10-24 17:54:18 +00001471
Richard Smith1aa0be82012-03-03 22:46:17 +00001472 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001473 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001474}
1475
Richard Smithc49bd112011-10-28 17:51:58 +00001476static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001477 Qualifiers Quals = T.getQualifiers();
1478 return Quals.hasConst() && !Quals.hasVolatile();
1479}
1480
Richard Smith59efe262011-11-11 04:05:33 +00001481/// Get the base index of the given base class within an APValue representing
1482/// the given derived class.
1483static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1484 const CXXRecordDecl *Base) {
1485 Base = Base->getCanonicalDecl();
1486 unsigned Index = 0;
1487 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1488 E = Derived->bases_end(); I != E; ++I, ++Index) {
1489 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1490 return Index;
1491 }
1492
1493 llvm_unreachable("base class missing from derived class's bases list");
1494}
1495
Richard Smithfe587202012-04-15 02:50:59 +00001496/// Extract the value of a character from a string literal. CharType is used to
1497/// determine the expected signedness of the result -- a string literal used to
1498/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1499/// of the wrong signedness.
Richard Smithf3908f22012-02-17 03:35:37 +00001500static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smithfe587202012-04-15 02:50:59 +00001501 uint64_t Index, QualType CharType) {
Richard Smithf3908f22012-02-17 03:35:37 +00001502 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1503 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1504 assert(S && "unexpected string literal expression kind");
Richard Smithfe587202012-04-15 02:50:59 +00001505 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smithf3908f22012-02-17 03:35:37 +00001506
1507 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smithfe587202012-04-15 02:50:59 +00001508 CharType->isUnsignedIntegerType());
Richard Smithf3908f22012-02-17 03:35:37 +00001509 if (Index < S->getLength())
1510 Value = S->getCodeUnit(Index);
1511 return Value;
1512}
1513
Richard Smithcc5d4f62011-11-07 09:22:26 +00001514/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001515static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001516 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001517 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001518 if (Sub.Invalid)
1519 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001520 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001521 if (Sub.isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001522 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001523 (unsigned)diag::note_constexpr_read_past_end :
1524 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001525 return false;
1526 }
Richard Smithf64699e2011-11-11 08:28:03 +00001527 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001528 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001529 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1530 // This object might be initialized later.
1531 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001532
Richard Smith0069b842012-03-10 00:28:11 +00001533 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001534 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001535 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001536 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001537 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001538 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001539 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001540 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001541 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001542 // Note, it should not be possible to form a pointer with a valid
1543 // designator which points more than one past the end of the array.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001544 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001545 (unsigned)diag::note_constexpr_read_past_end :
1546 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001547 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001548 }
Richard Smithf3908f22012-02-17 03:35:37 +00001549 // An array object is represented as either an Array APValue or as an
1550 // LValue which refers to a string literal.
1551 if (O->isLValue()) {
1552 assert(I == N - 1 && "extracting subobject of character?");
1553 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001554 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithfe587202012-04-15 02:50:59 +00001555 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smithf3908f22012-02-17 03:35:37 +00001556 return true;
1557 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001558 O = &O->getArrayInitializedElt(Index);
1559 else
1560 O = &O->getArrayFiller();
1561 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001562 } else if (ObjType->isAnyComplexType()) {
1563 // Next subobject is a complex number.
1564 uint64_t Index = Sub.Entries[I].ArrayIndex;
1565 if (Index > 1) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001566 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Richard Smith86024012012-02-18 22:04:06 +00001567 (unsigned)diag::note_constexpr_read_past_end :
1568 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1569 return false;
1570 }
1571 assert(I == N - 1 && "extracting subobject of scalar?");
1572 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001573 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001574 : O->getComplexIntReal());
1575 } else {
1576 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001577 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001578 : O->getComplexFloatReal());
1579 }
1580 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001581 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001582 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001583 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001584 << Field;
1585 Info.Note(Field->getLocation(), diag::note_declared_at);
1586 return false;
1587 }
1588
Richard Smith180f4792011-11-10 06:34:14 +00001589 // Next subobject is a class, struct or union field.
1590 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1591 if (RD->isUnion()) {
1592 const FieldDecl *UnionField = O->getUnionField();
1593 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001594 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001595 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001596 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001597 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001598 }
Richard Smith180f4792011-11-10 06:34:14 +00001599 O = &O->getUnionValue();
1600 } else
1601 O = &O->getStructField(Field->getFieldIndex());
1602 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001603
1604 if (ObjType.isVolatileQualified()) {
1605 if (Info.getLangOpts().CPlusPlus) {
1606 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001607 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001608 << 2 << Field;
1609 Info.Note(Field->getLocation(), diag::note_declared_at);
1610 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001611 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001612 }
1613 return false;
1614 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001615 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001616 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001617 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1618 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1619 O = &O->getStructBase(getBaseIndex(Derived, Base));
1620 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001621 }
Richard Smith180f4792011-11-10 06:34:14 +00001622
Richard Smithf48fdb02011-12-09 22:58:01 +00001623 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001624 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001625 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001626 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001627 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001628 }
1629
Richard Smith0069b842012-03-10 00:28:11 +00001630 // This may look super-stupid, but it serves an important purpose: if we just
1631 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1632 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1633 // object, which is destroyed by Tmp's destructor.
1634 APValue Tmp;
1635 O->swap(Tmp);
1636 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001637 return true;
1638}
1639
Richard Smithf15fda02012-02-02 01:16:57 +00001640/// Find the position where two subobject designators diverge, or equivalently
1641/// the length of the common initial subsequence.
1642static unsigned FindDesignatorMismatch(QualType ObjType,
1643 const SubobjectDesignator &A,
1644 const SubobjectDesignator &B,
1645 bool &WasArrayIndex) {
1646 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1647 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001648 if (!ObjType.isNull() &&
1649 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001650 // Next subobject is an array element.
1651 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1652 WasArrayIndex = true;
1653 return I;
1654 }
Richard Smith86024012012-02-18 22:04:06 +00001655 if (ObjType->isAnyComplexType())
1656 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1657 else
1658 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001659 } else {
1660 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1661 WasArrayIndex = false;
1662 return I;
1663 }
1664 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1665 // Next subobject is a field.
1666 ObjType = FD->getType();
1667 else
1668 // Next subobject is a base class.
1669 ObjType = QualType();
1670 }
1671 }
1672 WasArrayIndex = false;
1673 return I;
1674}
1675
1676/// Determine whether the given subobject designators refer to elements of the
1677/// same array object.
1678static bool AreElementsOfSameArray(QualType ObjType,
1679 const SubobjectDesignator &A,
1680 const SubobjectDesignator &B) {
1681 if (A.Entries.size() != B.Entries.size())
1682 return false;
1683
1684 bool IsArray = A.MostDerivedArraySize != 0;
1685 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1686 // A is a subobject of the array element.
1687 return false;
1688
1689 // If A (and B) designates an array element, the last entry will be the array
1690 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1691 // of length 1' case, and the entire path must match.
1692 bool WasArrayIndex;
1693 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1694 return CommonLength >= A.Entries.size() - IsArray;
1695}
1696
Richard Smith180f4792011-11-10 06:34:14 +00001697/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1698/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1699/// for looking up the glvalue referred to by an entity of reference type.
1700///
1701/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001702/// \param Conv - The expression for which we are performing the conversion.
1703/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001704/// \param Type - The type we expect this conversion to produce, before
1705/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001706/// \param LVal - The glvalue on which we are attempting to perform this action.
1707/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001708static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1709 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001710 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001711 if (LVal.Designator.Invalid)
1712 // A diagnostic will have already been produced.
1713 return false;
1714
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001715 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001716
Richard Smithf48fdb02011-12-09 22:58:01 +00001717 if (!LVal.Base) {
1718 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001719 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001720 return false;
1721 }
1722
Richard Smith83587db2012-02-15 02:18:13 +00001723 CallStackFrame *Frame = 0;
1724 if (LVal.CallIndex) {
1725 Frame = Info.getCallFrame(LVal.CallIndex);
1726 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001727 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001728 NoteLValueLocation(Info, LVal.Base);
1729 return false;
1730 }
1731 }
1732
Richard Smith7098cbd2011-12-21 05:04:46 +00001733 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1734 // is not a constant expression (even if the object is non-volatile). We also
1735 // apply this rule to C++98, in order to conform to the expected 'volatile'
1736 // semantics.
1737 if (Type.isVolatileQualified()) {
1738 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001739 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001740 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001741 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001742 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001743 }
Richard Smithc49bd112011-10-28 17:51:58 +00001744
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001745 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001746 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1747 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001748 // expressions are constant expressions too. Inside constexpr functions,
1749 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001750 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001751 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregord2008e22012-04-06 22:40:38 +00001752 if (VD) {
1753 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1754 VD = VDef;
1755 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001756 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001757 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001758 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001759 }
1760
Richard Smith7098cbd2011-12-21 05:04:46 +00001761 // DR1313: If the object is volatile-qualified but the glvalue was not,
1762 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001763 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001764 if (VT.isVolatileQualified()) {
1765 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001766 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001767 Info.Note(VD->getLocation(), diag::note_declared_at);
1768 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001769 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001770 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001771 return false;
1772 }
1773
1774 if (!isa<ParmVarDecl>(VD)) {
1775 if (VD->isConstexpr()) {
1776 // OK, we can read this variable.
1777 } else if (VT->isIntegralOrEnumerationType()) {
1778 if (!VT.isConstQualified()) {
1779 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001780 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001781 Info.Note(VD->getLocation(), diag::note_declared_at);
1782 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001783 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001784 }
1785 return false;
1786 }
1787 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1788 // We support folding of const floating-point types, in order to make
1789 // static const data members of such types (supported as an extension)
1790 // more useful.
1791 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001792 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001793 Info.Note(VD->getLocation(), diag::note_declared_at);
1794 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001795 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001796 }
1797 } else {
1798 // FIXME: Allow folding of values of any literal type in all languages.
1799 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001800 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001801 Info.Note(VD->getLocation(), diag::note_declared_at);
1802 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001803 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001804 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001805 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001806 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001807 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001808
Richard Smithf48fdb02011-12-09 22:58:01 +00001809 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001810 return false;
1811
Richard Smith47a1eed2011-10-29 20:57:55 +00001812 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001813 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001814
1815 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1816 // conversion. This happens when the declaration and the lvalue should be
1817 // considered synonymous, for instance when initializing an array of char
1818 // from a string literal. Continue as if the initializer lvalue was the
1819 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001820 assert(RVal.getLValueOffset().isZero() &&
1821 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001822 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001823
1824 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1825 Frame = Info.getCallFrame(CallIndex);
1826 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001827 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001828 NoteLValueLocation(Info, RVal.getLValueBase());
1829 return false;
1830 }
1831 } else {
1832 Frame = 0;
1833 }
Richard Smithc49bd112011-10-28 17:51:58 +00001834 }
1835
Richard Smith7098cbd2011-12-21 05:04:46 +00001836 // Volatile temporary objects cannot be read in constant expressions.
1837 if (Base->getType().isVolatileQualified()) {
1838 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001839 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001840 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1841 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001842 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001843 }
1844 return false;
1845 }
1846
Richard Smithcc5d4f62011-11-07 09:22:26 +00001847 if (Frame) {
1848 // If this is a temporary expression with a nontrivial initializer, grab the
1849 // value from the relevant stack frame.
1850 RVal = Frame->Temporaries[Base];
1851 } else if (const CompoundLiteralExpr *CLE
1852 = dyn_cast<CompoundLiteralExpr>(Base)) {
1853 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1854 // initializer until now for such expressions. Such an expression can't be
1855 // an ICE in C, so this only matters for fold.
1856 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1857 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1858 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001859 } else if (isa<StringLiteral>(Base)) {
1860 // We represent a string literal array as an lvalue pointing at the
1861 // corresponding expression, rather than building an array of chars.
1862 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001863 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001864 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001865 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001866 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001867 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001868
Richard Smithf48fdb02011-12-09 22:58:01 +00001869 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1870 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001871}
1872
Richard Smith59efe262011-11-11 04:05:33 +00001873/// Build an lvalue for the object argument of a member function call.
1874static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1875 LValue &This) {
1876 if (Object->getType()->isPointerType())
1877 return EvaluatePointer(Object, This, Info);
1878
1879 if (Object->isGLValue())
1880 return EvaluateLValue(Object, This, Info);
1881
Richard Smithe24f5fc2011-11-17 22:56:20 +00001882 if (Object->getType()->isLiteralType())
1883 return EvaluateTemporary(Object, This, Info);
1884
1885 return false;
1886}
1887
1888/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1889/// lvalue referring to the result.
1890///
1891/// \param Info - Information about the ongoing evaluation.
1892/// \param BO - The member pointer access operation.
1893/// \param LV - Filled in with a reference to the resulting object.
1894/// \param IncludeMember - Specifies whether the member itself is included in
1895/// the resulting LValue subobject designator. This is not possible when
1896/// creating a bound member function.
1897/// \return The field or method declaration to which the member pointer refers,
1898/// or 0 if evaluation fails.
1899static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1900 const BinaryOperator *BO,
1901 LValue &LV,
1902 bool IncludeMember = true) {
1903 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1904
Richard Smith745f5142012-01-27 01:14:48 +00001905 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1906 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001907 return 0;
1908
1909 MemberPtr MemPtr;
1910 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1911 return 0;
1912
1913 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1914 // member value, the behavior is undefined.
1915 if (!MemPtr.getDecl())
1916 return 0;
1917
Richard Smith745f5142012-01-27 01:14:48 +00001918 if (!EvalObjOK)
1919 return 0;
1920
Richard Smithe24f5fc2011-11-17 22:56:20 +00001921 if (MemPtr.isDerivedMember()) {
1922 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001923 // The end of the derived-to-base path for the base object must match the
1924 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001925 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001926 LV.Designator.Entries.size())
1927 return 0;
1928 unsigned PathLengthToMember =
1929 LV.Designator.Entries.size() - MemPtr.Path.size();
1930 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1931 const CXXRecordDecl *LVDecl = getAsBaseClass(
1932 LV.Designator.Entries[PathLengthToMember + I]);
1933 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1934 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1935 return 0;
1936 }
1937
1938 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001939 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1940 PathLengthToMember))
1941 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001942 } else if (!MemPtr.Path.empty()) {
1943 // Extend the LValue path with the member pointer's path.
1944 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1945 MemPtr.Path.size() + IncludeMember);
1946
1947 // Walk down to the appropriate base class.
1948 QualType LVType = BO->getLHS()->getType();
1949 if (const PointerType *PT = LVType->getAs<PointerType>())
1950 LVType = PT->getPointeeType();
1951 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1952 assert(RD && "member pointer access on non-class-type expression");
1953 // The first class in the path is that of the lvalue.
1954 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1955 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCall8d59dee2012-05-01 00:38:49 +00001956 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1957 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001958 RD = Base;
1959 }
1960 // Finally cast to the class containing the member.
John McCall8d59dee2012-05-01 00:38:49 +00001961 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1962 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001963 }
1964
1965 // Add the member. Note that we cannot build bound member functions here.
1966 if (IncludeMember) {
John McCall8d59dee2012-05-01 00:38:49 +00001967 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
1968 if (!HandleLValueMember(Info, BO, LV, FD))
1969 return 0;
1970 } else if (const IndirectFieldDecl *IFD =
1971 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
1972 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
1973 return 0;
1974 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00001975 llvm_unreachable("can't construct reference to bound member function");
John McCall8d59dee2012-05-01 00:38:49 +00001976 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001977 }
1978
1979 return MemPtr.getDecl();
1980}
1981
1982/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1983/// the provided lvalue, which currently refers to the base object.
1984static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1985 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001986 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001987 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001988 return false;
1989
Richard Smithb4e85ed2012-01-06 16:39:00 +00001990 QualType TargetQT = E->getType();
1991 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1992 TargetQT = PT->getPointeeType();
1993
1994 // Check this cast lands within the final derived-to-base subobject path.
1995 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001996 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00001997 << D.MostDerivedType << TargetQT;
1998 return false;
1999 }
2000
Richard Smithe24f5fc2011-11-17 22:56:20 +00002001 // Check the type of the final cast. We don't need to check the path,
2002 // since a cast can only be formed if the path is unique.
2003 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002004 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2005 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002006 if (NewEntriesSize == D.MostDerivedPathLength)
2007 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2008 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002009 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002010 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002011 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002012 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002013 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002014 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002015
2016 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002017 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002018}
2019
Mike Stumpc4c90452009-10-27 22:09:17 +00002020namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002021enum EvalStmtResult {
2022 /// Evaluation failed.
2023 ESR_Failed,
2024 /// Hit a 'return' statement.
2025 ESR_Returned,
2026 /// Evaluation succeeded.
2027 ESR_Succeeded
2028};
2029}
2030
2031// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002032static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002033 const Stmt *S) {
2034 switch (S->getStmtClass()) {
2035 default:
2036 return ESR_Failed;
2037
2038 case Stmt::NullStmtClass:
2039 case Stmt::DeclStmtClass:
2040 return ESR_Succeeded;
2041
Richard Smithc1c5f272011-12-13 06:39:58 +00002042 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002043 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002044 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002045 return ESR_Failed;
2046 return ESR_Returned;
2047 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002048
2049 case Stmt::CompoundStmtClass: {
2050 const CompoundStmt *CS = cast<CompoundStmt>(S);
2051 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2052 BE = CS->body_end(); BI != BE; ++BI) {
2053 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2054 if (ESR != ESR_Succeeded)
2055 return ESR;
2056 }
2057 return ESR_Succeeded;
2058 }
2059 }
2060}
2061
Richard Smith61802452011-12-22 02:22:31 +00002062/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2063/// default constructor. If so, we'll fold it whether or not it's marked as
2064/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2065/// so we need special handling.
2066static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002067 const CXXConstructorDecl *CD,
2068 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002069 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2070 return false;
2071
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002072 // Value-initialization does not call a trivial default constructor, so such a
2073 // call is a core constant expression whether or not the constructor is
2074 // constexpr.
2075 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002076 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002077 // FIXME: If DiagDecl is an implicitly-declared special member function,
2078 // we should be much more explicit about why it's not constexpr.
2079 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2080 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2081 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002082 } else {
2083 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2084 }
2085 }
2086 return true;
2087}
2088
Richard Smithc1c5f272011-12-13 06:39:58 +00002089/// CheckConstexprFunction - Check that a function can be called in a constant
2090/// expression.
2091static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2092 const FunctionDecl *Declaration,
2093 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002094 // Potential constant expressions can contain calls to declared, but not yet
2095 // defined, constexpr functions.
2096 if (Info.CheckingPotentialConstantExpression && !Definition &&
2097 Declaration->isConstexpr())
2098 return false;
2099
Richard Smithc1c5f272011-12-13 06:39:58 +00002100 // Can we evaluate this function call?
2101 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2102 return true;
2103
2104 if (Info.getLangOpts().CPlusPlus0x) {
2105 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002106 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2107 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002108 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2109 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2110 << DiagDecl;
2111 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2112 } else {
2113 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2114 }
2115 return false;
2116}
2117
Richard Smith180f4792011-11-10 06:34:14 +00002118namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002119typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002120}
2121
2122/// EvaluateArgs - Evaluate the arguments to a function call.
2123static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2124 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002125 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002126 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002127 I != E; ++I) {
2128 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2129 // If we're checking for a potential constant expression, evaluate all
2130 // initializers even if some of them fail.
2131 if (!Info.keepEvaluatingAfterFailure())
2132 return false;
2133 Success = false;
2134 }
2135 }
2136 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002137}
2138
Richard Smithd0dccea2011-10-28 22:34:42 +00002139/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002140static bool HandleFunctionCall(SourceLocation CallLoc,
2141 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002142 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002143 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002144 ArgVector ArgValues(Args.size());
2145 if (!EvaluateArgs(Args, ArgValues, Info))
2146 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002147
Richard Smith745f5142012-01-27 01:14:48 +00002148 if (!Info.CheckCallLimit(CallLoc))
2149 return false;
2150
2151 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002152 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2153}
2154
Richard Smith180f4792011-11-10 06:34:14 +00002155/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002156static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002157 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002158 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002159 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002160 ArgVector ArgValues(Args.size());
2161 if (!EvaluateArgs(Args, ArgValues, Info))
2162 return false;
2163
Richard Smith745f5142012-01-27 01:14:48 +00002164 if (!Info.CheckCallLimit(CallLoc))
2165 return false;
2166
Richard Smith86c3ae42012-02-13 03:54:03 +00002167 const CXXRecordDecl *RD = Definition->getParent();
2168 if (RD->getNumVBases()) {
2169 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2170 return false;
2171 }
2172
Richard Smith745f5142012-01-27 01:14:48 +00002173 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002174
2175 // If it's a delegating constructor, just delegate.
2176 if (Definition->isDelegatingConstructor()) {
2177 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002178 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002179 }
2180
Richard Smith610a60c2012-01-10 04:32:03 +00002181 // For a trivial copy or move constructor, perform an APValue copy. This is
2182 // essential for unions, where the operations performed by the constructor
2183 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002184 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002185 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2186 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002187 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002188 RHS.setFrom(Info.Ctx, ArgValues[0]);
2189 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2190 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002191 }
2192
2193 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002194 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002195 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2196 std::distance(RD->field_begin(), RD->field_end()));
2197
John McCall8d59dee2012-05-01 00:38:49 +00002198 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00002199 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2200
Richard Smith745f5142012-01-27 01:14:48 +00002201 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002202 unsigned BasesSeen = 0;
2203#ifndef NDEBUG
2204 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2205#endif
2206 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2207 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002208 LValue Subobject = This;
2209 APValue *Value = &Result;
2210
2211 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002212 if ((*I)->isBaseInitializer()) {
2213 QualType BaseType((*I)->getBaseClass(), 0);
2214#ifndef NDEBUG
2215 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002216 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002217 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2218 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2219 "base class initializers not in expected order");
2220 ++BaseIt;
2221#endif
John McCall8d59dee2012-05-01 00:38:49 +00002222 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2223 BaseType->getAsCXXRecordDecl(), &Layout))
2224 return false;
Richard Smith745f5142012-01-27 01:14:48 +00002225 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002226 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCall8d59dee2012-05-01 00:38:49 +00002227 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2228 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002229 if (RD->isUnion()) {
2230 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002231 Value = &Result.getUnionValue();
2232 } else {
2233 Value = &Result.getStructField(FD->getFieldIndex());
2234 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002235 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002236 // Walk the indirect field decl's chain to find the object to initialize,
2237 // and make sure we've initialized every step along it.
2238 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2239 CE = IFD->chain_end();
2240 C != CE; ++C) {
2241 FieldDecl *FD = cast<FieldDecl>(*C);
2242 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2243 // Switch the union field if it differs. This happens if we had
2244 // preceding zero-initialization, and we're now initializing a union
2245 // subobject other than the first.
2246 // FIXME: In this case, the values of the other subobjects are
2247 // specified, since zero-initialization sets all padding bits to zero.
2248 if (Value->isUninit() ||
2249 (Value->isUnion() && Value->getUnionField() != FD)) {
2250 if (CD->isUnion())
2251 *Value = APValue(FD);
2252 else
2253 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2254 std::distance(CD->field_begin(), CD->field_end()));
2255 }
John McCall8d59dee2012-05-01 00:38:49 +00002256 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2257 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002258 if (CD->isUnion())
2259 Value = &Value->getUnionValue();
2260 else
2261 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002262 }
Richard Smith180f4792011-11-10 06:34:14 +00002263 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002264 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002265 }
Richard Smith745f5142012-01-27 01:14:48 +00002266
Richard Smith83587db2012-02-15 02:18:13 +00002267 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2268 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002269 ? CCEK_Constant : CCEK_MemberInit)) {
2270 // If we're checking for a potential constant expression, evaluate all
2271 // initializers even if some of them fail.
2272 if (!Info.keepEvaluatingAfterFailure())
2273 return false;
2274 Success = false;
2275 }
Richard Smith180f4792011-11-10 06:34:14 +00002276 }
2277
Richard Smith745f5142012-01-27 01:14:48 +00002278 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002279}
2280
Richard Smithd0dccea2011-10-28 22:34:42 +00002281namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002282class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002283 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002284 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002285public:
2286
Richard Smith1e12c592011-10-16 21:26:27 +00002287 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002288
2289 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002290 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002291 return true;
2292 }
2293
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002294 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2295 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002296 return Visit(E->getResultExpr());
2297 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002298 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002299 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002300 return true;
2301 return false;
2302 }
John McCallf85e1932011-06-15 23:02:42 +00002303 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002304 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002305 return true;
2306 return false;
2307 }
John McCallf85e1932011-06-15 23:02:42 +00002308
Mike Stumpc4c90452009-10-27 22:09:17 +00002309 // We don't want to evaluate BlockExprs multiple times, as they generate
2310 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002311 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2312 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2313 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002314 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002315 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2316 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2317 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2318 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2319 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2320 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002321 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002322 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002323 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002324 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002325 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002326 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2327 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2328 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2329 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002330 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002331 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2332 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2333 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2334 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2335 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002336 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002337 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002338 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002339 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002340 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002341
2342 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002343 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002344 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2345 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002346 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002347 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002348 return false;
2349 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002350
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002351 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002352};
2353
Mike Stumpc4c90452009-10-27 22:09:17 +00002354} // end anonymous namespace
2355
Eli Friedman4efaa272008-11-12 09:44:48 +00002356//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002357// Generic Evaluation
2358//===----------------------------------------------------------------------===//
2359namespace {
2360
Richard Smithf48fdb02011-12-09 22:58:01 +00002361// FIXME: RetTy is always bool. Remove it.
2362template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002363class ExprEvaluatorBase
2364 : public ConstStmtVisitor<Derived, RetTy> {
2365private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002366 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002367 return static_cast<Derived*>(this)->Success(V, E);
2368 }
Richard Smith51201882011-12-30 21:15:51 +00002369 RetTy DerivedZeroInitialization(const Expr *E) {
2370 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002371 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002372
Richard Smith74e1ad92012-02-16 02:46:34 +00002373 // Check whether a conditional operator with a non-constant condition is a
2374 // potential constant expression. If neither arm is a potential constant
2375 // expression, then the conditional operator is not either.
2376 template<typename ConditionalOperator>
2377 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2378 assert(Info.CheckingPotentialConstantExpression);
2379
2380 // Speculatively evaluate both arms.
2381 {
2382 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2383 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2384
2385 StmtVisitorTy::Visit(E->getFalseExpr());
2386 if (Diag.empty())
2387 return;
2388
2389 Diag.clear();
2390 StmtVisitorTy::Visit(E->getTrueExpr());
2391 if (Diag.empty())
2392 return;
2393 }
2394
2395 Error(E, diag::note_constexpr_conditional_never_const);
2396 }
2397
2398
2399 template<typename ConditionalOperator>
2400 bool HandleConditionalOperator(const ConditionalOperator *E) {
2401 bool BoolResult;
2402 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2403 if (Info.CheckingPotentialConstantExpression)
2404 CheckPotentialConstantConditional(E);
2405 return false;
2406 }
2407
2408 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2409 return StmtVisitorTy::Visit(EvalExpr);
2410 }
2411
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002412protected:
2413 EvalInfo &Info;
2414 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2415 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2416
Richard Smithdd1f29b2011-12-12 09:28:41 +00002417 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002418 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002419 }
2420
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002421 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2422
2423public:
2424 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2425
2426 EvalInfo &getEvalInfo() { return Info; }
2427
Richard Smithf48fdb02011-12-09 22:58:01 +00002428 /// Report an evaluation error. This should only be called when an error is
2429 /// first discovered. When propagating an error, just return false.
2430 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002431 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002432 return false;
2433 }
2434 bool Error(const Expr *E) {
2435 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2436 }
2437
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002438 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002439 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002440 }
2441 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002442 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002443 }
2444
2445 RetTy VisitParenExpr(const ParenExpr *E)
2446 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2447 RetTy VisitUnaryExtension(const UnaryOperator *E)
2448 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2449 RetTy VisitUnaryPlus(const UnaryOperator *E)
2450 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2451 RetTy VisitChooseExpr(const ChooseExpr *E)
2452 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2453 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2454 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002455 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2456 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002457 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2458 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002459 // We cannot create any objects for which cleanups are required, so there is
2460 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2461 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2462 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002463
Richard Smithc216a012011-12-12 12:46:16 +00002464 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2465 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2466 return static_cast<Derived*>(this)->VisitCastExpr(E);
2467 }
2468 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2469 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2470 return static_cast<Derived*>(this)->VisitCastExpr(E);
2471 }
2472
Richard Smithe24f5fc2011-11-17 22:56:20 +00002473 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2474 switch (E->getOpcode()) {
2475 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002476 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002477
2478 case BO_Comma:
2479 VisitIgnoredValue(E->getLHS());
2480 return StmtVisitorTy::Visit(E->getRHS());
2481
2482 case BO_PtrMemD:
2483 case BO_PtrMemI: {
2484 LValue Obj;
2485 if (!HandleMemberPointerAccess(Info, E, Obj))
2486 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002487 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002488 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002489 return false;
2490 return DerivedSuccess(Result, E);
2491 }
2492 }
2493 }
2494
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002495 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002496 // Evaluate and cache the common expression. We treat it as a temporary,
2497 // even though it's not quite the same thing.
2498 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2499 Info, E->getCommon()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002500 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002501
Richard Smith74e1ad92012-02-16 02:46:34 +00002502 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002503 }
2504
2505 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002506 bool IsBcpCall = false;
2507 // If the condition (ignoring parens) is a __builtin_constant_p call,
2508 // the result is a constant expression if it can be folded without
2509 // side-effects. This is an important GNU extension. See GCC PR38377
2510 // for discussion.
2511 if (const CallExpr *CallCE =
2512 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2513 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2514 IsBcpCall = true;
2515
2516 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2517 // constant expression; we can't check whether it's potentially foldable.
2518 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2519 return false;
2520
2521 FoldConstant Fold(Info);
2522
Richard Smith74e1ad92012-02-16 02:46:34 +00002523 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002524 return false;
2525
2526 if (IsBcpCall)
2527 Fold.Fold(Info);
2528
2529 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002530 }
2531
2532 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002533 APValue &Value = Info.CurrentCall->Temporaries[E];
2534 if (Value.isUninit()) {
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002535 const Expr *Source = E->getSourceExpr();
2536 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002537 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002538 if (Source == E) { // sanity checking.
2539 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002540 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002541 }
2542 return StmtVisitorTy::Visit(Source);
2543 }
Richard Smithe92b1f42012-06-26 08:12:11 +00002544 return DerivedSuccess(Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002545 }
Richard Smithf10d9172011-10-11 21:43:33 +00002546
Richard Smithd0dccea2011-10-28 22:34:42 +00002547 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002548 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002549 QualType CalleeType = Callee->getType();
2550
Richard Smithd0dccea2011-10-28 22:34:42 +00002551 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002552 LValue *This = 0, ThisVal;
2553 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002554 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002555
Richard Smith59efe262011-11-11 04:05:33 +00002556 // Extract function decl and 'this' pointer from the callee.
2557 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002558 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002559 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2560 // Explicit bound member calls, such as x.f() or p->g();
2561 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002562 return false;
2563 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002564 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002565 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002566 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2567 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002568 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2569 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002570 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002571 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002572 return Error(Callee);
2573
2574 FD = dyn_cast<FunctionDecl>(Member);
2575 if (!FD)
2576 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002577 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002578 LValue Call;
2579 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002580 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002581
Richard Smithb4e85ed2012-01-06 16:39:00 +00002582 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002583 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002584 FD = dyn_cast_or_null<FunctionDecl>(
2585 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002586 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002587 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002588
2589 // Overloaded operator calls to member functions are represented as normal
2590 // calls with '*this' as the first argument.
2591 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2592 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002593 // FIXME: When selecting an implicit conversion for an overloaded
2594 // operator delete, we sometimes try to evaluate calls to conversion
2595 // operators without a 'this' parameter!
2596 if (Args.empty())
2597 return Error(E);
2598
Richard Smith59efe262011-11-11 04:05:33 +00002599 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2600 return false;
2601 This = &ThisVal;
2602 Args = Args.slice(1);
2603 }
2604
2605 // Don't call function pointers which have been cast to some other type.
2606 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002607 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002608 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002609 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002610
Richard Smithb04035a2012-02-01 02:39:43 +00002611 if (This && !This->checkSubobject(Info, E, CSK_This))
2612 return false;
2613
Richard Smith86c3ae42012-02-13 03:54:03 +00002614 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2615 // calls to such functions in constant expressions.
2616 if (This && !HasQualifier &&
2617 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2618 return Error(E, diag::note_constexpr_virtual_call);
2619
Richard Smithc1c5f272011-12-13 06:39:58 +00002620 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002621 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002622 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002623
Richard Smithc1c5f272011-12-13 06:39:58 +00002624 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002625 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2626 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002627 return false;
2628
Richard Smith83587db2012-02-15 02:18:13 +00002629 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002630 }
2631
Richard Smithc49bd112011-10-28 17:51:58 +00002632 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2633 return StmtVisitorTy::Visit(E->getInitializer());
2634 }
Richard Smithf10d9172011-10-11 21:43:33 +00002635 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002636 if (E->getNumInits() == 0)
2637 return DerivedZeroInitialization(E);
2638 if (E->getNumInits() == 1)
2639 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002640 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002641 }
2642 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002643 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002644 }
2645 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002646 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002647 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002648 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002649 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002650 }
Richard Smithf10d9172011-10-11 21:43:33 +00002651
Richard Smith180f4792011-11-10 06:34:14 +00002652 /// A member expression where the object is a prvalue is itself a prvalue.
2653 RetTy VisitMemberExpr(const MemberExpr *E) {
2654 assert(!E->isArrow() && "missing call to bound member function?");
2655
Richard Smith1aa0be82012-03-03 22:46:17 +00002656 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002657 if (!Evaluate(Val, Info, E->getBase()))
2658 return false;
2659
2660 QualType BaseTy = E->getBase()->getType();
2661
2662 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002663 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002664 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2665 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2666 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2667
Richard Smithb4e85ed2012-01-06 16:39:00 +00002668 SubobjectDesignator Designator(BaseTy);
2669 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002670
Richard Smithf48fdb02011-12-09 22:58:01 +00002671 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002672 DerivedSuccess(Val, E);
2673 }
2674
Richard Smithc49bd112011-10-28 17:51:58 +00002675 RetTy VisitCastExpr(const CastExpr *E) {
2676 switch (E->getCastKind()) {
2677 default:
2678 break;
2679
David Chisnall7a7ee302012-01-16 17:27:18 +00002680 case CK_AtomicToNonAtomic:
2681 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002682 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002683 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002684 return StmtVisitorTy::Visit(E->getSubExpr());
2685
2686 case CK_LValueToRValue: {
2687 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002688 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2689 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002690 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002691 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2692 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2693 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002694 return false;
2695 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002696 }
2697 }
2698
Richard Smithf48fdb02011-12-09 22:58:01 +00002699 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002700 }
2701
Richard Smith8327fad2011-10-24 18:44:57 +00002702 /// Visit a value which is evaluated, but whose value is ignored.
2703 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002704 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002705 if (!Evaluate(Scratch, Info, E))
2706 Info.EvalStatus.HasSideEffects = true;
2707 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002708};
2709
2710}
2711
2712//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002713// Common base class for lvalue and temporary evaluation.
2714//===----------------------------------------------------------------------===//
2715namespace {
2716template<class Derived>
2717class LValueExprEvaluatorBase
2718 : public ExprEvaluatorBase<Derived, bool> {
2719protected:
2720 LValue &Result;
2721 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2722 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2723
2724 bool Success(APValue::LValueBase B) {
2725 Result.set(B);
2726 return true;
2727 }
2728
2729public:
2730 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2731 ExprEvaluatorBaseTy(Info), Result(Result) {}
2732
Richard Smith1aa0be82012-03-03 22:46:17 +00002733 bool Success(const APValue &V, const Expr *E) {
2734 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002735 return true;
2736 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002737
Richard Smithe24f5fc2011-11-17 22:56:20 +00002738 bool VisitMemberExpr(const MemberExpr *E) {
2739 // Handle non-static data members.
2740 QualType BaseTy;
2741 if (E->isArrow()) {
2742 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2743 return false;
2744 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002745 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002746 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002747 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2748 return false;
2749 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002750 } else {
2751 if (!this->Visit(E->getBase()))
2752 return false;
2753 BaseTy = E->getBase()->getType();
2754 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002755
Richard Smithd9b02e72012-01-25 22:15:11 +00002756 const ValueDecl *MD = E->getMemberDecl();
2757 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2758 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2759 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2760 (void)BaseTy;
John McCall8d59dee2012-05-01 00:38:49 +00002761 if (!HandleLValueMember(this->Info, E, Result, FD))
2762 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002763 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCall8d59dee2012-05-01 00:38:49 +00002764 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2765 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002766 } else
2767 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002768
Richard Smithd9b02e72012-01-25 22:15:11 +00002769 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002770 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002771 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002772 RefValue))
2773 return false;
2774 return Success(RefValue, E);
2775 }
2776 return true;
2777 }
2778
2779 bool VisitBinaryOperator(const BinaryOperator *E) {
2780 switch (E->getOpcode()) {
2781 default:
2782 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2783
2784 case BO_PtrMemD:
2785 case BO_PtrMemI:
2786 return HandleMemberPointerAccess(this->Info, E, Result);
2787 }
2788 }
2789
2790 bool VisitCastExpr(const CastExpr *E) {
2791 switch (E->getCastKind()) {
2792 default:
2793 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2794
2795 case CK_DerivedToBase:
2796 case CK_UncheckedDerivedToBase: {
2797 if (!this->Visit(E->getSubExpr()))
2798 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002799
2800 // Now figure out the necessary offset to add to the base LV to get from
2801 // the derived class to the base class.
2802 QualType Type = E->getSubExpr()->getType();
2803
2804 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2805 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002806 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002807 *PathI))
2808 return false;
2809 Type = (*PathI)->getType();
2810 }
2811
2812 return true;
2813 }
2814 }
2815 }
2816};
2817}
2818
2819//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002820// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002821//
2822// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2823// function designators (in C), decl references to void objects (in C), and
2824// temporaries (if building with -Wno-address-of-temporary).
2825//
2826// LValue evaluation produces values comprising a base expression of one of the
2827// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002828// - Declarations
2829// * VarDecl
2830// * FunctionDecl
2831// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002832// * CompoundLiteralExpr in C
2833// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002834// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002835// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002836// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002837// * ObjCEncodeExpr
2838// * AddrLabelExpr
2839// * BlockExpr
2840// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002841// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002842// * Any Expr, with a CallIndex indicating the function in which the temporary
2843// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002844// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002845//===----------------------------------------------------------------------===//
2846namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002847class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002848 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002849public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002850 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2851 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002852
Richard Smithc49bd112011-10-28 17:51:58 +00002853 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2854
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002855 bool VisitDeclRefExpr(const DeclRefExpr *E);
2856 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002857 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002858 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2859 bool VisitMemberExpr(const MemberExpr *E);
2860 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2861 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002862 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichete275a182012-04-16 04:08:35 +00002863 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002864 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2865 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002866 bool VisitUnaryReal(const UnaryOperator *E);
2867 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002868
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002869 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002870 switch (E->getCastKind()) {
2871 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002872 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002873
Eli Friedmandb924222011-10-11 00:13:24 +00002874 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002875 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002876 if (!Visit(E->getSubExpr()))
2877 return false;
2878 Result.Designator.setInvalid();
2879 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002880
Richard Smithe24f5fc2011-11-17 22:56:20 +00002881 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002882 if (!Visit(E->getSubExpr()))
2883 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002884 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002885 }
2886 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002887};
2888} // end anonymous namespace
2889
Richard Smithc49bd112011-10-28 17:51:58 +00002890/// Evaluate an expression as an lvalue. This can be legitimately called on
2891/// expressions which are not glvalues, in a few cases:
2892/// * function designators in C,
2893/// * "extern void" objects,
2894/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002895static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002896 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2897 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2898 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002899 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002900}
2901
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002902bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002903 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2904 return Success(FD);
2905 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002906 return VisitVarDecl(E, VD);
2907 return Error(E);
2908}
Richard Smith436c8892011-10-24 23:14:33 +00002909
Richard Smithc49bd112011-10-28 17:51:58 +00002910bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002911 if (!VD->getType()->isReferenceType()) {
2912 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002913 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002914 return true;
2915 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002916 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002917 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002918
Richard Smith1aa0be82012-03-03 22:46:17 +00002919 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002920 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2921 return false;
2922 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002923}
2924
Richard Smithbd552ef2011-10-31 05:52:43 +00002925bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2926 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002927 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002928 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002929 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2930
Richard Smith83587db2012-02-15 02:18:13 +00002931 Result.set(E, Info.CurrentCall->Index);
2932 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2933 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002934 }
2935
2936 // Materialization of an lvalue temporary occurs when we need to force a copy
2937 // (for instance, if it's a bitfield).
2938 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2939 if (!Visit(E->GetTemporaryExpr()))
2940 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002941 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002942 Info.CurrentCall->Temporaries[E]))
2943 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002944 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002945 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002946}
2947
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002948bool
2949LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002950 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2951 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2952 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002953 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002954}
2955
Richard Smith47d21452011-12-27 12:18:28 +00002956bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2957 if (E->isTypeOperand())
2958 return Success(E);
2959 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2960 if (RD && RD->isPolymorphic()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002961 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith47d21452011-12-27 12:18:28 +00002962 << E->getExprOperand()->getType()
2963 << E->getExprOperand()->getSourceRange();
2964 return false;
2965 }
2966 return Success(E);
2967}
2968
Francois Pichete275a182012-04-16 04:08:35 +00002969bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2970 return Success(E);
2971}
2972
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002973bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002974 // Handle static data members.
2975 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2976 VisitIgnoredValue(E->getBase());
2977 return VisitVarDecl(E, VD);
2978 }
2979
Richard Smithd0dccea2011-10-28 22:34:42 +00002980 // Handle static member functions.
2981 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2982 if (MD->isStatic()) {
2983 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002984 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002985 }
2986 }
2987
Richard Smith180f4792011-11-10 06:34:14 +00002988 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002989 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002990}
2991
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002992bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002993 // FIXME: Deal with vectors as array subscript bases.
2994 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002995 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002996
Anders Carlsson3068d112008-11-16 19:01:22 +00002997 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002998 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002999
Anders Carlsson3068d112008-11-16 19:01:22 +00003000 APSInt Index;
3001 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003002 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003003 int64_t IndexValue
3004 = Index.isSigned() ? Index.getSExtValue()
3005 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003006
Richard Smithb4e85ed2012-01-06 16:39:00 +00003007 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003008}
Eli Friedman4efaa272008-11-12 09:44:48 +00003009
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003010bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003011 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003012}
3013
Richard Smith86024012012-02-18 22:04:06 +00003014bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3015 if (!Visit(E->getSubExpr()))
3016 return false;
3017 // __real is a no-op on scalar lvalues.
3018 if (E->getSubExpr()->getType()->isAnyComplexType())
3019 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3020 return true;
3021}
3022
3023bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3024 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3025 "lvalue __imag__ on scalar?");
3026 if (!Visit(E->getSubExpr()))
3027 return false;
3028 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3029 return true;
3030}
3031
Eli Friedman4efaa272008-11-12 09:44:48 +00003032//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003033// Pointer Evaluation
3034//===----------------------------------------------------------------------===//
3035
Anders Carlssonc754aa62008-07-08 05:13:58 +00003036namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003037class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003038 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003039 LValue &Result;
3040
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003041 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003042 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003043 return true;
3044 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003045public:
Mike Stump1eb44332009-09-09 15:08:12 +00003046
John McCallefdb83e2010-05-07 21:00:08 +00003047 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003048 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003049
Richard Smith1aa0be82012-03-03 22:46:17 +00003050 bool Success(const APValue &V, const Expr *E) {
3051 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003052 return true;
3053 }
Richard Smith51201882011-12-30 21:15:51 +00003054 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003055 return Success((Expr*)0);
3056 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003057
John McCallefdb83e2010-05-07 21:00:08 +00003058 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003059 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003060 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003061 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003062 { return Success(E); }
Patrick Beardeb382ec2012-04-19 00:25:12 +00003063 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003064 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003065 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003066 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003067 bool VisitCallExpr(const CallExpr *E);
3068 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003069 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003070 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003071 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003072 }
Richard Smith180f4792011-11-10 06:34:14 +00003073 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3074 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003075 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003076 Result = *Info.CurrentCall->This;
3077 return true;
3078 }
John McCall56ca35d2011-02-17 10:25:35 +00003079
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003080 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003081};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003082} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003083
John McCallefdb83e2010-05-07 21:00:08 +00003084static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003085 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003086 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003087}
3088
John McCallefdb83e2010-05-07 21:00:08 +00003089bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003090 if (E->getOpcode() != BO_Add &&
3091 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003092 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003093
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003094 const Expr *PExp = E->getLHS();
3095 const Expr *IExp = E->getRHS();
3096 if (IExp->getType()->isPointerType())
3097 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003098
Richard Smith745f5142012-01-27 01:14:48 +00003099 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3100 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003101 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003102
John McCallefdb83e2010-05-07 21:00:08 +00003103 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003104 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003105 return false;
3106 int64_t AdditionalOffset
3107 = Offset.isSigned() ? Offset.getSExtValue()
3108 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003109 if (E->getOpcode() == BO_Sub)
3110 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003111
Richard Smith180f4792011-11-10 06:34:14 +00003112 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003113 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3114 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003115}
Eli Friedman4efaa272008-11-12 09:44:48 +00003116
John McCallefdb83e2010-05-07 21:00:08 +00003117bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3118 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003119}
Mike Stump1eb44332009-09-09 15:08:12 +00003120
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003121bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3122 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003123
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003124 switch (E->getCastKind()) {
3125 default:
3126 break;
3127
John McCall2de56d12010-08-25 11:45:40 +00003128 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003129 case CK_CPointerToObjCPointerCast:
3130 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003131 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003132 if (!Visit(SubExpr))
3133 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003134 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3135 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3136 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003137 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003138 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003139 if (SubExpr->getType()->isVoidPointerType())
3140 CCEDiag(E, diag::note_constexpr_invalid_cast)
3141 << 3 << SubExpr->getType();
3142 else
3143 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3144 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003145 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003146
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003147 case CK_DerivedToBase:
3148 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003149 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003150 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003151 if (!Result.Base && Result.Offset.isZero())
3152 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003153
Richard Smith180f4792011-11-10 06:34:14 +00003154 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003155 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003156 QualType Type =
3157 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003158
Richard Smith180f4792011-11-10 06:34:14 +00003159 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003160 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003161 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3162 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003163 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003164 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003165 }
3166
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003167 return true;
3168 }
3169
Richard Smithe24f5fc2011-11-17 22:56:20 +00003170 case CK_BaseToDerived:
3171 if (!Visit(E->getSubExpr()))
3172 return false;
3173 if (!Result.Base && Result.Offset.isZero())
3174 return true;
3175 return HandleBaseToDerivedCast(Info, E, Result);
3176
Richard Smith47a1eed2011-10-29 20:57:55 +00003177 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003178 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003179 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003180
John McCall2de56d12010-08-25 11:45:40 +00003181 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003182 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3183
Richard Smith1aa0be82012-03-03 22:46:17 +00003184 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003185 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003186 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003187
John McCallefdb83e2010-05-07 21:00:08 +00003188 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003189 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3190 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003191 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003192 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003193 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003194 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003195 return true;
3196 } else {
3197 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003198 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003199 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003200 }
3201 }
John McCall2de56d12010-08-25 11:45:40 +00003202 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003203 if (SubExpr->isGLValue()) {
3204 if (!EvaluateLValue(SubExpr, Result, Info))
3205 return false;
3206 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003207 Result.set(SubExpr, Info.CurrentCall->Index);
3208 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3209 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003210 return false;
3211 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003212 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003213 if (const ConstantArrayType *CAT
3214 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3215 Result.addArray(Info, E, CAT);
3216 else
3217 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003218 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003219
John McCall2de56d12010-08-25 11:45:40 +00003220 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003221 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003222 }
3223
Richard Smithc49bd112011-10-28 17:51:58 +00003224 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003225}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003226
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003227bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003228 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003229 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003230
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003231 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003232}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003233
3234//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003235// Member Pointer Evaluation
3236//===----------------------------------------------------------------------===//
3237
3238namespace {
3239class MemberPointerExprEvaluator
3240 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3241 MemberPtr &Result;
3242
3243 bool Success(const ValueDecl *D) {
3244 Result = MemberPtr(D);
3245 return true;
3246 }
3247public:
3248
3249 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3250 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3251
Richard Smith1aa0be82012-03-03 22:46:17 +00003252 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003253 Result.setFrom(V);
3254 return true;
3255 }
Richard Smith51201882011-12-30 21:15:51 +00003256 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003257 return Success((const ValueDecl*)0);
3258 }
3259
3260 bool VisitCastExpr(const CastExpr *E);
3261 bool VisitUnaryAddrOf(const UnaryOperator *E);
3262};
3263} // end anonymous namespace
3264
3265static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3266 EvalInfo &Info) {
3267 assert(E->isRValue() && E->getType()->isMemberPointerType());
3268 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3269}
3270
3271bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3272 switch (E->getCastKind()) {
3273 default:
3274 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3275
3276 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003277 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003278 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003279
3280 case CK_BaseToDerivedMemberPointer: {
3281 if (!Visit(E->getSubExpr()))
3282 return false;
3283 if (E->path_empty())
3284 return true;
3285 // Base-to-derived member pointer casts store the path in derived-to-base
3286 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3287 // the wrong end of the derived->base arc, so stagger the path by one class.
3288 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3289 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3290 PathI != PathE; ++PathI) {
3291 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3292 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3293 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003294 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003295 }
3296 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3297 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003298 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003299 return true;
3300 }
3301
3302 case CK_DerivedToBaseMemberPointer:
3303 if (!Visit(E->getSubExpr()))
3304 return false;
3305 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3306 PathE = E->path_end(); PathI != PathE; ++PathI) {
3307 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3308 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3309 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003310 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003311 }
3312 return true;
3313 }
3314}
3315
3316bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3317 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3318 // member can be formed.
3319 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3320}
3321
3322//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003323// Record Evaluation
3324//===----------------------------------------------------------------------===//
3325
3326namespace {
3327 class RecordExprEvaluator
3328 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3329 const LValue &This;
3330 APValue &Result;
3331 public:
3332
3333 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3334 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3335
Richard Smith1aa0be82012-03-03 22:46:17 +00003336 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003337 Result = V;
3338 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003339 }
Richard Smith51201882011-12-30 21:15:51 +00003340 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003341
Richard Smith59efe262011-11-11 04:05:33 +00003342 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003343 bool VisitInitListExpr(const InitListExpr *E);
3344 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3345 };
3346}
3347
Richard Smith51201882011-12-30 21:15:51 +00003348/// Perform zero-initialization on an object of non-union class type.
3349/// C++11 [dcl.init]p5:
3350/// To zero-initialize an object or reference of type T means:
3351/// [...]
3352/// -- if T is a (possibly cv-qualified) non-union class type,
3353/// each non-static data member and each base-class subobject is
3354/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003355static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3356 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003357 const LValue &This, APValue &Result) {
3358 assert(!RD->isUnion() && "Expected non-union class type");
3359 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3360 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3361 std::distance(RD->field_begin(), RD->field_end()));
3362
John McCall8d59dee2012-05-01 00:38:49 +00003363 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003364 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3365
3366 if (CD) {
3367 unsigned Index = 0;
3368 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003369 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003370 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3371 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003372 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3373 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003374 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003375 Result.getStructBase(Index)))
3376 return false;
3377 }
3378 }
3379
Richard Smithb4e85ed2012-01-06 16:39:00 +00003380 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3381 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003382 // -- if T is a reference type, no initialization is performed.
David Blaikie262bc182012-04-30 02:36:29 +00003383 if (I->getType()->isReferenceType())
Richard Smith51201882011-12-30 21:15:51 +00003384 continue;
3385
3386 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003387 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003388 return false;
Richard Smith51201882011-12-30 21:15:51 +00003389
David Blaikie262bc182012-04-30 02:36:29 +00003390 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003391 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003392 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003393 return false;
3394 }
3395
3396 return true;
3397}
3398
3399bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3400 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003401 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003402 if (RD->isUnion()) {
3403 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3404 // object's first non-static named data member is zero-initialized
3405 RecordDecl::field_iterator I = RD->field_begin();
3406 if (I == RD->field_end()) {
3407 Result = APValue((const FieldDecl*)0);
3408 return true;
3409 }
3410
3411 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003412 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCall8d59dee2012-05-01 00:38:49 +00003413 return false;
David Blaikie581deb32012-06-06 20:45:41 +00003414 Result = APValue(*I);
David Blaikie262bc182012-04-30 02:36:29 +00003415 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003416 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003417 }
3418
Richard Smithce582fe2012-02-17 00:44:16 +00003419 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003420 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003421 return false;
3422 }
3423
Richard Smithb4e85ed2012-01-06 16:39:00 +00003424 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003425}
3426
Richard Smith59efe262011-11-11 04:05:33 +00003427bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3428 switch (E->getCastKind()) {
3429 default:
3430 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3431
3432 case CK_ConstructorConversion:
3433 return Visit(E->getSubExpr());
3434
3435 case CK_DerivedToBase:
3436 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003437 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003438 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003439 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003440 if (!DerivedObject.isStruct())
3441 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003442
3443 // Derived-to-base rvalue conversion: just slice off the derived part.
3444 APValue *Value = &DerivedObject;
3445 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3446 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3447 PathE = E->path_end(); PathI != PathE; ++PathI) {
3448 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3449 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3450 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3451 RD = Base;
3452 }
3453 Result = *Value;
3454 return true;
3455 }
3456 }
3457}
3458
Richard Smith180f4792011-11-10 06:34:14 +00003459bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003460 // Cannot constant-evaluate std::initializer_list inits.
3461 if (E->initializesStdInitializerList())
3462 return false;
3463
Richard Smith180f4792011-11-10 06:34:14 +00003464 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003465 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00003466 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3467
3468 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003469 const FieldDecl *Field = E->getInitializedFieldInUnion();
3470 Result = APValue(Field);
3471 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003472 return true;
Richard Smithec789162012-01-12 18:54:33 +00003473
3474 // If the initializer list for a union does not contain any elements, the
3475 // first element of the union is value-initialized.
3476 ImplicitValueInitExpr VIE(Field->getType());
3477 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3478
Richard Smith180f4792011-11-10 06:34:14 +00003479 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003480 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3481 return false;
Richard Smith83587db2012-02-15 02:18:13 +00003482 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003483 }
3484
3485 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3486 "initializer list for class with base classes");
3487 Result = APValue(APValue::UninitStruct(), 0,
3488 std::distance(RD->field_begin(), RD->field_end()));
3489 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003490 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003491 for (RecordDecl::field_iterator Field = RD->field_begin(),
3492 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3493 // Anonymous bit-fields are not considered members of the class for
3494 // purposes of aggregate initialization.
3495 if (Field->isUnnamedBitfield())
3496 continue;
3497
3498 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003499
Richard Smith745f5142012-01-27 01:14:48 +00003500 bool HaveInit = ElementNo < E->getNumInits();
3501
3502 // FIXME: Diagnostics here should point to the end of the initializer
3503 // list, not the start.
John McCall8d59dee2012-05-01 00:38:49 +00003504 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie581deb32012-06-06 20:45:41 +00003505 Subobject, *Field, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003506 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003507
3508 // Perform an implicit value-initialization for members beyond the end of
3509 // the initializer list.
3510 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3511
Richard Smith83587db2012-02-15 02:18:13 +00003512 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003513 Result.getStructField(Field->getFieldIndex()),
Richard Smith745f5142012-01-27 01:14:48 +00003514 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3515 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003516 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003517 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003518 }
3519 }
3520
Richard Smith745f5142012-01-27 01:14:48 +00003521 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003522}
3523
3524bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3525 const CXXConstructorDecl *FD = E->getConstructor();
John McCall1de9d7d2012-04-26 18:10:01 +00003526 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3527
Richard Smith51201882011-12-30 21:15:51 +00003528 bool ZeroInit = E->requiresZeroInitialization();
3529 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003530 // If we've already performed zero-initialization, we're already done.
3531 if (!Result.isUninit())
3532 return true;
3533
Richard Smith51201882011-12-30 21:15:51 +00003534 if (ZeroInit)
3535 return ZeroInitialization(E);
3536
Richard Smith61802452011-12-22 02:22:31 +00003537 const CXXRecordDecl *RD = FD->getParent();
3538 if (RD->isUnion())
3539 Result = APValue((FieldDecl*)0);
3540 else
3541 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3542 std::distance(RD->field_begin(), RD->field_end()));
3543 return true;
3544 }
3545
Richard Smith180f4792011-11-10 06:34:14 +00003546 const FunctionDecl *Definition = 0;
3547 FD->getBody(Definition);
3548
Richard Smithc1c5f272011-12-13 06:39:58 +00003549 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3550 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003551
Richard Smith610a60c2012-01-10 04:32:03 +00003552 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003553 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003554 if (const MaterializeTemporaryExpr *ME
3555 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3556 return Visit(ME->GetTemporaryExpr());
3557
Richard Smith51201882011-12-30 21:15:51 +00003558 if (ZeroInit && !ZeroInitialization(E))
3559 return false;
3560
Richard Smith180f4792011-11-10 06:34:14 +00003561 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003562 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003563 cast<CXXConstructorDecl>(Definition), Info,
3564 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003565}
3566
3567static bool EvaluateRecord(const Expr *E, const LValue &This,
3568 APValue &Result, EvalInfo &Info) {
3569 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003570 "can't evaluate expression as a record rvalue");
3571 return RecordExprEvaluator(Info, This, Result).Visit(E);
3572}
3573
3574//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003575// Temporary Evaluation
3576//
3577// Temporaries are represented in the AST as rvalues, but generally behave like
3578// lvalues. The full-object of which the temporary is a subobject is implicitly
3579// materialized so that a reference can bind to it.
3580//===----------------------------------------------------------------------===//
3581namespace {
3582class TemporaryExprEvaluator
3583 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3584public:
3585 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3586 LValueExprEvaluatorBaseTy(Info, Result) {}
3587
3588 /// Visit an expression which constructs the value of this temporary.
3589 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003590 Result.set(E, Info.CurrentCall->Index);
3591 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003592 }
3593
3594 bool VisitCastExpr(const CastExpr *E) {
3595 switch (E->getCastKind()) {
3596 default:
3597 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3598
3599 case CK_ConstructorConversion:
3600 return VisitConstructExpr(E->getSubExpr());
3601 }
3602 }
3603 bool VisitInitListExpr(const InitListExpr *E) {
3604 return VisitConstructExpr(E);
3605 }
3606 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3607 return VisitConstructExpr(E);
3608 }
3609 bool VisitCallExpr(const CallExpr *E) {
3610 return VisitConstructExpr(E);
3611 }
3612};
3613} // end anonymous namespace
3614
3615/// Evaluate an expression of record type as a temporary.
3616static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003617 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003618 return TemporaryExprEvaluator(Info, Result).Visit(E);
3619}
3620
3621//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003622// Vector Evaluation
3623//===----------------------------------------------------------------------===//
3624
3625namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003626 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003627 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3628 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003629 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003630
Richard Smith07fc6572011-10-22 21:10:00 +00003631 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3632 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003633
Richard Smith07fc6572011-10-22 21:10:00 +00003634 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3635 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3636 // FIXME: remove this APValue copy.
3637 Result = APValue(V.data(), V.size());
3638 return true;
3639 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003640 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003641 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003642 Result = V;
3643 return true;
3644 }
Richard Smith51201882011-12-30 21:15:51 +00003645 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003646
Richard Smith07fc6572011-10-22 21:10:00 +00003647 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003648 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003649 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003650 bool VisitInitListExpr(const InitListExpr *E);
3651 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003652 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003653 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003654 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003655 };
3656} // end anonymous namespace
3657
3658static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003659 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003660 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003661}
3662
Richard Smith07fc6572011-10-22 21:10:00 +00003663bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3664 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003665 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003666
Richard Smithd62ca372011-12-06 22:44:34 +00003667 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003668 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003669
Eli Friedman46a52322011-03-25 00:43:55 +00003670 switch (E->getCastKind()) {
3671 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003672 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003673 if (SETy->isIntegerType()) {
3674 APSInt IntResult;
3675 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003676 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003677 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003678 } else if (SETy->isRealFloatingType()) {
3679 APFloat F(0.0);
3680 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003681 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003682 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003683 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003684 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003685 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003686
3687 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003688 SmallVector<APValue, 4> Elts(NElts, Val);
3689 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003690 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003691 case CK_BitCast: {
3692 // Evaluate the operand into an APInt we can extract from.
3693 llvm::APInt SValInt;
3694 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3695 return false;
3696 // Extract the elements
3697 QualType EltTy = VTy->getElementType();
3698 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3699 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3700 SmallVector<APValue, 4> Elts;
3701 if (EltTy->isRealFloatingType()) {
3702 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3703 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3704 unsigned FloatEltSize = EltSize;
3705 if (&Sem == &APFloat::x87DoubleExtended)
3706 FloatEltSize = 80;
3707 for (unsigned i = 0; i < NElts; i++) {
3708 llvm::APInt Elt;
3709 if (BigEndian)
3710 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3711 else
3712 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3713 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3714 }
3715 } else if (EltTy->isIntegerType()) {
3716 for (unsigned i = 0; i < NElts; i++) {
3717 llvm::APInt Elt;
3718 if (BigEndian)
3719 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3720 else
3721 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3722 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3723 }
3724 } else {
3725 return Error(E);
3726 }
3727 return Success(Elts, E);
3728 }
Eli Friedman46a52322011-03-25 00:43:55 +00003729 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003730 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003731 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003732}
3733
Richard Smith07fc6572011-10-22 21:10:00 +00003734bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003735VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003736 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003737 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003738 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003739
Nate Begeman59b5da62009-01-18 03:20:47 +00003740 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003741 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003742
Eli Friedman3edd5a92012-01-03 23:24:20 +00003743 // The number of initializers can be less than the number of
3744 // vector elements. For OpenCL, this can be due to nested vector
3745 // initialization. For GCC compatibility, missing trailing elements
3746 // should be initialized with zeroes.
3747 unsigned CountInits = 0, CountElts = 0;
3748 while (CountElts < NumElements) {
3749 // Handle nested vector initialization.
3750 if (CountInits < NumInits
3751 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3752 APValue v;
3753 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3754 return Error(E);
3755 unsigned vlen = v.getVectorLength();
3756 for (unsigned j = 0; j < vlen; j++)
3757 Elements.push_back(v.getVectorElt(j));
3758 CountElts += vlen;
3759 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003760 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003761 if (CountInits < NumInits) {
3762 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003763 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003764 } else // trailing integer zero.
3765 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3766 Elements.push_back(APValue(sInt));
3767 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003768 } else {
3769 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003770 if (CountInits < NumInits) {
3771 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003772 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003773 } else // trailing float zero.
3774 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3775 Elements.push_back(APValue(f));
3776 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003777 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003778 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003779 }
Richard Smith07fc6572011-10-22 21:10:00 +00003780 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003781}
3782
Richard Smith07fc6572011-10-22 21:10:00 +00003783bool
Richard Smith51201882011-12-30 21:15:51 +00003784VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003785 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003786 QualType EltTy = VT->getElementType();
3787 APValue ZeroElement;
3788 if (EltTy->isIntegerType())
3789 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3790 else
3791 ZeroElement =
3792 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3793
Chris Lattner5f9e2722011-07-23 10:55:15 +00003794 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003795 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003796}
3797
Richard Smith07fc6572011-10-22 21:10:00 +00003798bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003799 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003800 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003801}
3802
Nate Begeman59b5da62009-01-18 03:20:47 +00003803//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003804// Array Evaluation
3805//===----------------------------------------------------------------------===//
3806
3807namespace {
3808 class ArrayExprEvaluator
3809 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003810 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003811 APValue &Result;
3812 public:
3813
Richard Smith180f4792011-11-10 06:34:14 +00003814 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3815 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003816
3817 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003818 assert((V.isArray() || V.isLValue()) &&
3819 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003820 Result = V;
3821 return true;
3822 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003823
Richard Smith51201882011-12-30 21:15:51 +00003824 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003825 const ConstantArrayType *CAT =
3826 Info.Ctx.getAsConstantArrayType(E->getType());
3827 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003828 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003829
3830 Result = APValue(APValue::UninitArray(), 0,
3831 CAT->getSize().getZExtValue());
3832 if (!Result.hasArrayFiller()) return true;
3833
Richard Smith51201882011-12-30 21:15:51 +00003834 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003835 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003836 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003837 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003838 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003839 }
3840
Richard Smithcc5d4f62011-11-07 09:22:26 +00003841 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003842 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003843 };
3844} // end anonymous namespace
3845
Richard Smith180f4792011-11-10 06:34:14 +00003846static bool EvaluateArray(const Expr *E, const LValue &This,
3847 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003848 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003849 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003850}
3851
3852bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3853 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3854 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003855 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003856
Richard Smith974c5f92011-12-22 01:07:19 +00003857 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3858 // an appropriately-typed string literal enclosed in braces.
Richard Smithfe587202012-04-15 02:50:59 +00003859 if (E->isStringLiteralInit()) {
Richard Smith974c5f92011-12-22 01:07:19 +00003860 LValue LV;
3861 if (!EvaluateLValue(E->getInit(0), LV, Info))
3862 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003863 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003864 LV.moveInto(Val);
3865 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003866 }
3867
Richard Smith745f5142012-01-27 01:14:48 +00003868 bool Success = true;
3869
Richard Smithde31aa72012-07-07 22:48:24 +00003870 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
3871 "zero-initialized array shouldn't have any initialized elts");
3872 APValue Filler;
3873 if (Result.isArray() && Result.hasArrayFiller())
3874 Filler = Result.getArrayFiller();
3875
Richard Smithcc5d4f62011-11-07 09:22:26 +00003876 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3877 CAT->getSize().getZExtValue());
Richard Smithde31aa72012-07-07 22:48:24 +00003878
3879 // If the array was previously zero-initialized, preserve the
3880 // zero-initialized values.
3881 if (!Filler.isUninit()) {
3882 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
3883 Result.getArrayInitializedElt(I) = Filler;
3884 if (Result.hasArrayFiller())
3885 Result.getArrayFiller() = Filler;
3886 }
3887
Richard Smith180f4792011-11-10 06:34:14 +00003888 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003889 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003890 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003891 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003892 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003893 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3894 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003895 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3896 CAT->getElementType(), 1)) {
3897 if (!Info.keepEvaluatingAfterFailure())
3898 return false;
3899 Success = false;
3900 }
Richard Smith180f4792011-11-10 06:34:14 +00003901 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003902
Richard Smith745f5142012-01-27 01:14:48 +00003903 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003904 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003905 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3906 // but sometimes does:
3907 // struct S { constexpr S() : p(&p) {} void *p; };
3908 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003909 return EvaluateInPlace(Result.getArrayFiller(), Info,
3910 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003911}
3912
Richard Smithe24f5fc2011-11-17 22:56:20 +00003913bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smithde31aa72012-07-07 22:48:24 +00003914 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3915 // but sometimes does:
3916 // struct S { constexpr S() : p(&p) {} void *p; };
3917 // S s[10];
3918 LValue Subobject = This;
3919
3920 APValue *Value = &Result;
3921 bool HadZeroInit = true;
Richard Smitha4334df2012-07-10 22:12:55 +00003922 QualType ElemTy = E->getType();
3923 while (const ConstantArrayType *CAT =
3924 Info.Ctx.getAsConstantArrayType(ElemTy)) {
Richard Smithde31aa72012-07-07 22:48:24 +00003925 Subobject.addArray(Info, E, CAT);
3926 HadZeroInit &= !Value->isUninit();
3927 if (!HadZeroInit)
3928 *Value = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3929 if (!Value->hasArrayFiller())
3930 return true;
Richard Smithde31aa72012-07-07 22:48:24 +00003931 Value = &Value->getArrayFiller();
Richard Smitha4334df2012-07-10 22:12:55 +00003932 ElemTy = CAT->getElementType();
Richard Smithde31aa72012-07-07 22:48:24 +00003933 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00003934
Richard Smitha4334df2012-07-10 22:12:55 +00003935 if (!ElemTy->isRecordType())
3936 return Error(E);
3937
Richard Smithe24f5fc2011-11-17 22:56:20 +00003938 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003939
Richard Smith51201882011-12-30 21:15:51 +00003940 bool ZeroInit = E->requiresZeroInitialization();
3941 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003942 if (HadZeroInit)
3943 return true;
3944
Richard Smith51201882011-12-30 21:15:51 +00003945 if (ZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003946 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003947 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003948 }
3949
Richard Smith61802452011-12-22 02:22:31 +00003950 const CXXRecordDecl *RD = FD->getParent();
3951 if (RD->isUnion())
Richard Smithde31aa72012-07-07 22:48:24 +00003952 *Value = APValue((FieldDecl*)0);
Richard Smith61802452011-12-22 02:22:31 +00003953 else
Richard Smithde31aa72012-07-07 22:48:24 +00003954 *Value =
Richard Smith61802452011-12-22 02:22:31 +00003955 APValue(APValue::UninitStruct(), RD->getNumBases(),
3956 std::distance(RD->field_begin(), RD->field_end()));
3957 return true;
3958 }
3959
Richard Smithe24f5fc2011-11-17 22:56:20 +00003960 const FunctionDecl *Definition = 0;
3961 FD->getBody(Definition);
3962
Richard Smithc1c5f272011-12-13 06:39:58 +00003963 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3964 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003965
Richard Smithec789162012-01-12 18:54:33 +00003966 if (ZeroInit && !HadZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003967 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003968 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003969 return false;
3970 }
3971
Richard Smithe24f5fc2011-11-17 22:56:20 +00003972 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003973 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003974 cast<CXXConstructorDecl>(Definition),
Richard Smithde31aa72012-07-07 22:48:24 +00003975 Info, *Value);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003976}
3977
Richard Smithcc5d4f62011-11-07 09:22:26 +00003978//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003979// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003980//
3981// As a GNU extension, we support casting pointers to sufficiently-wide integer
3982// types and back in constant folding. Integer values are thus represented
3983// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003984//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003985
3986namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003987class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003988 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003989 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003990public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003991 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003992 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003993
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003994 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003995 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003996 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003997 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003998 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003999 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004000 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004001 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004002 return true;
4003 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004004 bool Success(const llvm::APSInt &SI, const Expr *E) {
4005 return Success(SI, E, Result);
4006 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004007
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004008 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004009 assert(E->getType()->isIntegralOrEnumerationType() &&
4010 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004011 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004012 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004013 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00004014 Result.getInt().setIsUnsigned(
4015 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00004016 return true;
4017 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004018 bool Success(const llvm::APInt &I, const Expr *E) {
4019 return Success(I, E, Result);
4020 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004021
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004022 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004023 assert(E->getType()->isIntegralOrEnumerationType() &&
4024 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00004025 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00004026 return true;
4027 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004028 bool Success(uint64_t Value, const Expr *E) {
4029 return Success(Value, E, Result);
4030 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00004031
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004032 bool Success(CharUnits Size, const Expr *E) {
4033 return Success(Size.getQuantity(), E);
4034 }
4035
Richard Smith1aa0be82012-03-03 22:46:17 +00004036 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00004037 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00004038 Result = V;
4039 return true;
4040 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004041 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004042 }
Mike Stump1eb44332009-09-09 15:08:12 +00004043
Richard Smith51201882011-12-30 21:15:51 +00004044 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004045
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004046 //===--------------------------------------------------------------------===//
4047 // Visitor Methods
4048 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004049
Chris Lattner4c4867e2008-07-12 00:38:25 +00004050 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004051 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004052 }
4053 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004054 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004055 }
Eli Friedman04309752009-11-24 05:28:59 +00004056
4057 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4058 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004059 if (CheckReferencedDecl(E, E->getDecl()))
4060 return true;
4061
4062 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004063 }
4064 bool VisitMemberExpr(const MemberExpr *E) {
4065 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004066 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004067 return true;
4068 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004069
4070 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004071 }
4072
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004073 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004074 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004075 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004076 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004077
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004078 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004079 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004080
Anders Carlsson3068d112008-11-16 19:01:22 +00004081 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004082 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004083 }
Mike Stump1eb44332009-09-09 15:08:12 +00004084
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004085 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4086 return Success(E->getValue(), E);
4087 }
4088
Richard Smithf10d9172011-10-11 21:43:33 +00004089 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004090 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004091 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004092 }
4093
Sebastian Redl64b45f72009-01-05 20:52:13 +00004094 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004095 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004096 }
4097
Francois Pichet6ad6f282010-12-07 00:08:36 +00004098 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4099 return Success(E->getValue(), E);
4100 }
4101
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004102 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4103 return Success(E->getValue(), E);
4104 }
4105
John Wiegley21ff2e52011-04-28 00:16:57 +00004106 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4107 return Success(E->getValue(), E);
4108 }
4109
John Wiegley55262202011-04-25 06:54:41 +00004110 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4111 return Success(E->getValue(), E);
4112 }
4113
Eli Friedman722c7172009-02-28 03:59:05 +00004114 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004115 bool VisitUnaryImag(const UnaryOperator *E);
4116
Sebastian Redl295995c2010-09-10 20:55:47 +00004117 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004118 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004119
Chris Lattnerfcee0012008-07-11 21:24:13 +00004120private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004121 CharUnits GetAlignOfExpr(const Expr *E);
4122 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004123 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004124 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004125 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004126};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004127} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004128
Richard Smithc49bd112011-10-28 17:51:58 +00004129/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4130/// produce either the integer value or a pointer.
4131///
4132/// GCC has a heinous extension which folds casts between pointer types and
4133/// pointer-sized integral types. We support this by allowing the evaluation of
4134/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4135/// Some simple arithmetic on such values is supported (they are treated much
4136/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004137static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004138 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004139 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004140 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004141}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004142
Richard Smithf48fdb02011-12-09 22:58:01 +00004143static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004144 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004145 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004146 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004147 if (!Val.isInt()) {
4148 // FIXME: It would be better to produce the diagnostic for casting
4149 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004150 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004151 return false;
4152 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004153 Result = Val.getInt();
4154 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004155}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004156
Richard Smithf48fdb02011-12-09 22:58:01 +00004157/// Check whether the given declaration can be directly converted to an integral
4158/// rvalue. If not, no diagnostic is produced; there are other things we can
4159/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004160bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004161 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004162 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004163 // Check for signedness/width mismatches between E type and ECD value.
4164 bool SameSign = (ECD->getInitVal().isSigned()
4165 == E->getType()->isSignedIntegerOrEnumerationType());
4166 bool SameWidth = (ECD->getInitVal().getBitWidth()
4167 == Info.Ctx.getIntWidth(E->getType()));
4168 if (SameSign && SameWidth)
4169 return Success(ECD->getInitVal(), E);
4170 else {
4171 // Get rid of mismatch (otherwise Success assertions will fail)
4172 // by computing a new value matching the type of E.
4173 llvm::APSInt Val = ECD->getInitVal();
4174 if (!SameSign)
4175 Val.setIsSigned(!ECD->getInitVal().isSigned());
4176 if (!SameWidth)
4177 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4178 return Success(Val, E);
4179 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004180 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004181 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004182}
4183
Chris Lattnera4d55d82008-10-06 06:40:35 +00004184/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4185/// as GCC.
4186static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4187 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004188 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004189 enum gcc_type_class {
4190 no_type_class = -1,
4191 void_type_class, integer_type_class, char_type_class,
4192 enumeral_type_class, boolean_type_class,
4193 pointer_type_class, reference_type_class, offset_type_class,
4194 real_type_class, complex_type_class,
4195 function_type_class, method_type_class,
4196 record_type_class, union_type_class,
4197 array_type_class, string_type_class,
4198 lang_type_class
4199 };
Mike Stump1eb44332009-09-09 15:08:12 +00004200
4201 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004202 // ideal, however it is what gcc does.
4203 if (E->getNumArgs() == 0)
4204 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004205
Chris Lattnera4d55d82008-10-06 06:40:35 +00004206 QualType ArgTy = E->getArg(0)->getType();
4207 if (ArgTy->isVoidType())
4208 return void_type_class;
4209 else if (ArgTy->isEnumeralType())
4210 return enumeral_type_class;
4211 else if (ArgTy->isBooleanType())
4212 return boolean_type_class;
4213 else if (ArgTy->isCharType())
4214 return string_type_class; // gcc doesn't appear to use char_type_class
4215 else if (ArgTy->isIntegerType())
4216 return integer_type_class;
4217 else if (ArgTy->isPointerType())
4218 return pointer_type_class;
4219 else if (ArgTy->isReferenceType())
4220 return reference_type_class;
4221 else if (ArgTy->isRealType())
4222 return real_type_class;
4223 else if (ArgTy->isComplexType())
4224 return complex_type_class;
4225 else if (ArgTy->isFunctionType())
4226 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004227 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004228 return record_type_class;
4229 else if (ArgTy->isUnionType())
4230 return union_type_class;
4231 else if (ArgTy->isArrayType())
4232 return array_type_class;
4233 else if (ArgTy->isUnionType())
4234 return union_type_class;
4235 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004236 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004237}
4238
Richard Smith80d4b552011-12-28 19:48:30 +00004239/// EvaluateBuiltinConstantPForLValue - Determine the result of
4240/// __builtin_constant_p when applied to the given lvalue.
4241///
4242/// An lvalue is only "constant" if it is a pointer or reference to the first
4243/// character of a string literal.
4244template<typename LValue>
4245static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004246 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004247 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4248}
4249
4250/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4251/// GCC as we can manage.
4252static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4253 QualType ArgType = Arg->getType();
4254
4255 // __builtin_constant_p always has one operand. The rules which gcc follows
4256 // are not precisely documented, but are as follows:
4257 //
4258 // - If the operand is of integral, floating, complex or enumeration type,
4259 // and can be folded to a known value of that type, it returns 1.
4260 // - If the operand and can be folded to a pointer to the first character
4261 // of a string literal (or such a pointer cast to an integral type), it
4262 // returns 1.
4263 //
4264 // Otherwise, it returns 0.
4265 //
4266 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4267 // its support for this does not currently work.
4268 if (ArgType->isIntegralOrEnumerationType()) {
4269 Expr::EvalResult Result;
4270 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4271 return false;
4272
4273 APValue &V = Result.Val;
4274 if (V.getKind() == APValue::Int)
4275 return true;
4276
4277 return EvaluateBuiltinConstantPForLValue(V);
4278 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4279 return Arg->isEvaluatable(Ctx);
4280 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4281 LValue LV;
4282 Expr::EvalStatus Status;
4283 EvalInfo Info(Ctx, Status);
4284 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4285 : EvaluatePointer(Arg, LV, Info)) &&
4286 !Status.HasSideEffects)
4287 return EvaluateBuiltinConstantPForLValue(LV);
4288 }
4289
4290 // Anything else isn't considered to be sufficiently constant.
4291 return false;
4292}
4293
John McCall42c8f872010-05-10 23:27:23 +00004294/// Retrieves the "underlying object type" of the given expression,
4295/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004296QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4297 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4298 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004299 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004300 } else if (const Expr *E = B.get<const Expr*>()) {
4301 if (isa<CompoundLiteralExpr>(E))
4302 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004303 }
4304
4305 return QualType();
4306}
4307
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004308bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004309 LValue Base;
Richard Smithc6794852012-05-23 04:13:20 +00004310
4311 {
4312 // The operand of __builtin_object_size is never evaluated for side-effects.
4313 // If there are any, but we can determine the pointed-to object anyway, then
4314 // ignore the side-effects.
4315 SpeculativeEvaluationRAII SpeculativeEval(Info);
4316 if (!EvaluatePointer(E->getArg(0), Base, Info))
4317 return false;
4318 }
John McCall42c8f872010-05-10 23:27:23 +00004319
4320 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004321 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004322
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004323 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004324 if (T.isNull() ||
4325 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004326 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004327 T->isVariablyModifiedType() ||
4328 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004329 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004330
4331 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4332 CharUnits Offset = Base.getLValueOffset();
4333
4334 if (!Offset.isNegative() && Offset <= Size)
4335 Size -= Offset;
4336 else
4337 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004338 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004339}
4340
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004341bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00004342 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004343 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004344 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004345
4346 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004347 if (TryEvaluateBuiltinObjectSize(E))
4348 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004349
Eric Christopherb2aaf512010-01-19 22:58:35 +00004350 // If evaluating the argument has side-effects we can't determine
Richard Smithc6794852012-05-23 04:13:20 +00004351 // the size of the object and lower it to unknown now. CodeGen relies on
4352 // us to handle all cases where the expression has side-effects.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004353 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004354 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004355 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004356 return Success(0, E);
4357 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004358
Richard Smithc6794852012-05-23 04:13:20 +00004359 // Expression had no side effects, but we couldn't statically determine the
4360 // size of the referenced object.
Richard Smithf48fdb02011-12-09 22:58:01 +00004361 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004362 }
4363
Chris Lattner019f4e82008-10-06 05:28:25 +00004364 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004365 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004366
Richard Smith80d4b552011-12-28 19:48:30 +00004367 case Builtin::BI__builtin_constant_p:
4368 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004369
Chris Lattner21fb98e2009-09-23 06:06:36 +00004370 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004371 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004372 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004373 return Success(Operand, E);
4374 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004375
4376 case Builtin::BI__builtin_expect:
4377 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004378
Douglas Gregor5726d402010-09-10 06:27:15 +00004379 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004380 // A call to strlen is not a constant expression.
4381 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004382 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004383 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4384 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004385 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004386 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004387 case Builtin::BI__builtin_strlen:
4388 // As an extension, we support strlen() and __builtin_strlen() as constant
4389 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004390 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004391 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4392 // The string literal may have embedded null characters. Find the first
4393 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004394 StringRef Str = S->getString();
4395 StringRef::size_type Pos = Str.find(0);
4396 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004397 Str = Str.substr(0, Pos);
4398
4399 return Success(Str.size(), E);
4400 }
4401
Richard Smithf48fdb02011-12-09 22:58:01 +00004402 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004403
Richard Smith2c39d712012-04-13 00:45:38 +00004404 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00004405 case Builtin::BI__atomic_is_lock_free:
4406 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00004407 APSInt SizeVal;
4408 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4409 return false;
4410
4411 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4412 // of two less than the maximum inline atomic width, we know it is
4413 // lock-free. If the size isn't a power of two, or greater than the
4414 // maximum alignment where we promote atomics, we know it is not lock-free
4415 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4416 // the answer can only be determined at runtime; for example, 16-byte
4417 // atomics have lock-free implementations on some, but not all,
4418 // x86-64 processors.
4419
4420 // Check power-of-two.
4421 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00004422 if (Size.isPowerOfTwo()) {
4423 // Check against inlining width.
4424 unsigned InlineWidthBits =
4425 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4426 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4427 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4428 Size == CharUnits::One() ||
4429 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4430 Expr::NPC_NeverValueDependent))
4431 // OK, we will inline appropriately-aligned operations of this size,
4432 // and _Atomic(T) is appropriately-aligned.
4433 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004434
Richard Smith2c39d712012-04-13 00:45:38 +00004435 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4436 castAs<PointerType>()->getPointeeType();
4437 if (!PointeeType->isIncompleteType() &&
4438 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4439 // OK, we will inline operations on this object.
4440 return Success(1, E);
4441 }
4442 }
4443 }
Eli Friedman454b57a2011-10-17 21:44:23 +00004444
Richard Smith2c39d712012-04-13 00:45:38 +00004445 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4446 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004447 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004448 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004449}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004450
Richard Smith625b8072011-10-31 01:37:14 +00004451static bool HasSameBase(const LValue &A, const LValue &B) {
4452 if (!A.getLValueBase())
4453 return !B.getLValueBase();
4454 if (!B.getLValueBase())
4455 return false;
4456
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004457 if (A.getLValueBase().getOpaqueValue() !=
4458 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004459 const Decl *ADecl = GetLValueBaseDecl(A);
4460 if (!ADecl)
4461 return false;
4462 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004463 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004464 return false;
4465 }
4466
4467 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004468 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004469}
4470
Richard Smith7b48a292012-02-01 05:53:12 +00004471/// Perform the given integer operation, which is known to need at most BitWidth
4472/// bits, and check for overflow in the original type (if that type was not an
4473/// unsigned type).
4474template<typename Operation>
4475static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4476 const APSInt &LHS, const APSInt &RHS,
4477 unsigned BitWidth, Operation Op) {
4478 if (LHS.isUnsigned())
4479 return Op(LHS, RHS);
4480
4481 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4482 APSInt Result = Value.trunc(LHS.getBitWidth());
4483 if (Result.extend(BitWidth) != Value)
4484 HandleOverflow(Info, E, Value, E->getType());
4485 return Result;
4486}
4487
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004488namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004489
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004490/// \brief Data recursive integer evaluator of certain binary operators.
4491///
4492/// We use a data recursive algorithm for binary operators so that we are able
4493/// to handle extreme cases of chained binary operators without causing stack
4494/// overflow.
4495class DataRecursiveIntBinOpEvaluator {
4496 struct EvalResult {
4497 APValue Val;
4498 bool Failed;
4499
4500 EvalResult() : Failed(false) { }
4501
4502 void swap(EvalResult &RHS) {
4503 Val.swap(RHS.Val);
4504 Failed = RHS.Failed;
4505 RHS.Failed = false;
4506 }
4507 };
4508
4509 struct Job {
4510 const Expr *E;
4511 EvalResult LHSResult; // meaningful only for binary operator expression.
4512 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4513
4514 Job() : StoredInfo(0) { }
4515 void startSpeculativeEval(EvalInfo &Info) {
4516 OldEvalStatus = Info.EvalStatus;
4517 Info.EvalStatus.Diag = 0;
4518 StoredInfo = &Info;
4519 }
4520 ~Job() {
4521 if (StoredInfo) {
4522 StoredInfo->EvalStatus = OldEvalStatus;
4523 }
4524 }
4525 private:
4526 EvalInfo *StoredInfo; // non-null if status changed.
4527 Expr::EvalStatus OldEvalStatus;
4528 };
4529
4530 SmallVector<Job, 16> Queue;
4531
4532 IntExprEvaluator &IntEval;
4533 EvalInfo &Info;
4534 APValue &FinalResult;
4535
4536public:
4537 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4538 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4539
4540 /// \brief True if \param E is a binary operator that we are going to handle
4541 /// data recursively.
4542 /// We handle binary operators that are comma, logical, or that have operands
4543 /// with integral or enumeration type.
4544 static bool shouldEnqueue(const BinaryOperator *E) {
4545 return E->getOpcode() == BO_Comma ||
4546 E->isLogicalOp() ||
4547 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4548 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004549 }
4550
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004551 bool Traverse(const BinaryOperator *E) {
4552 enqueue(E);
4553 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004554 while (!Queue.empty())
4555 process(PrevResult);
4556
4557 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004558
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004559 FinalResult.swap(PrevResult.Val);
4560 return true;
4561 }
4562
4563private:
4564 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4565 return IntEval.Success(Value, E, Result);
4566 }
4567 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4568 return IntEval.Success(Value, E, Result);
4569 }
4570 bool Error(const Expr *E) {
4571 return IntEval.Error(E);
4572 }
4573 bool Error(const Expr *E, diag::kind D) {
4574 return IntEval.Error(E, D);
4575 }
4576
4577 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4578 return Info.CCEDiag(E, D);
4579 }
4580
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004581 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4582 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004583 bool &SuppressRHSDiags);
4584
4585 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4586 const BinaryOperator *E, APValue &Result);
4587
4588 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4589 Result.Failed = !Evaluate(Result.Val, Info, E);
4590 if (Result.Failed)
4591 Result.Val = APValue();
4592 }
4593
Richard Trieub7783052012-03-21 23:30:30 +00004594 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004595
4596 void enqueue(const Expr *E) {
4597 E = E->IgnoreParens();
4598 Queue.resize(Queue.size()+1);
4599 Queue.back().E = E;
4600 Queue.back().Kind = Job::AnyExprKind;
4601 }
4602};
4603
4604}
4605
4606bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004607 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004608 bool &SuppressRHSDiags) {
4609 if (E->getOpcode() == BO_Comma) {
4610 // Ignore LHS but note if we could not evaluate it.
4611 if (LHSResult.Failed)
4612 Info.EvalStatus.HasSideEffects = true;
4613 return true;
4614 }
4615
4616 if (E->isLogicalOp()) {
4617 bool lhsResult;
4618 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004619 // We were able to evaluate the LHS, see if we can get away with not
4620 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004621 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004622 Success(lhsResult, E, LHSResult.Val);
4623 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004624 }
4625 } else {
4626 // Since we weren't able to evaluate the left hand side, it
4627 // must have had side effects.
4628 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004629
4630 // We can't evaluate the LHS; however, sometimes the result
4631 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4632 // Don't ignore RHS and suppress diagnostics from this arm.
4633 SuppressRHSDiags = true;
4634 }
4635
4636 return true;
4637 }
4638
4639 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4640 E->getRHS()->getType()->isIntegralOrEnumerationType());
4641
4642 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004643 return false; // Ignore RHS;
4644
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004645 return true;
4646}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004647
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004648bool DataRecursiveIntBinOpEvaluator::
4649 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4650 const BinaryOperator *E, APValue &Result) {
4651 if (E->getOpcode() == BO_Comma) {
4652 if (RHSResult.Failed)
4653 return false;
4654 Result = RHSResult.Val;
4655 return true;
4656 }
4657
4658 if (E->isLogicalOp()) {
4659 bool lhsResult, rhsResult;
4660 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4661 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4662
4663 if (LHSIsOK) {
4664 if (RHSIsOK) {
4665 if (E->getOpcode() == BO_LOr)
4666 return Success(lhsResult || rhsResult, E, Result);
4667 else
4668 return Success(lhsResult && rhsResult, E, Result);
4669 }
4670 } else {
4671 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004672 // We can't evaluate the LHS; however, sometimes the result
4673 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4674 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004675 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004676 }
4677 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004678
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004679 return false;
4680 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004681
4682 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4683 E->getRHS()->getType()->isIntegralOrEnumerationType());
4684
4685 if (LHSResult.Failed || RHSResult.Failed)
4686 return false;
4687
4688 const APValue &LHSVal = LHSResult.Val;
4689 const APValue &RHSVal = RHSResult.Val;
4690
4691 // Handle cases like (unsigned long)&a + 4.
4692 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4693 Result = LHSVal;
4694 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4695 RHSVal.getInt().getZExtValue());
4696 if (E->getOpcode() == BO_Add)
4697 Result.getLValueOffset() += AdditionalOffset;
4698 else
4699 Result.getLValueOffset() -= AdditionalOffset;
4700 return true;
4701 }
4702
4703 // Handle cases like 4 + (unsigned long)&a
4704 if (E->getOpcode() == BO_Add &&
4705 RHSVal.isLValue() && LHSVal.isInt()) {
4706 Result = RHSVal;
4707 Result.getLValueOffset() += CharUnits::fromQuantity(
4708 LHSVal.getInt().getZExtValue());
4709 return true;
4710 }
4711
4712 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4713 // Handle (intptr_t)&&A - (intptr_t)&&B.
4714 if (!LHSVal.getLValueOffset().isZero() ||
4715 !RHSVal.getLValueOffset().isZero())
4716 return false;
4717 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4718 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4719 if (!LHSExpr || !RHSExpr)
4720 return false;
4721 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4722 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4723 if (!LHSAddrExpr || !RHSAddrExpr)
4724 return false;
4725 // Make sure both labels come from the same function.
4726 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4727 RHSAddrExpr->getLabel()->getDeclContext())
4728 return false;
4729 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4730 return true;
4731 }
4732
4733 // All the following cases expect both operands to be an integer
4734 if (!LHSVal.isInt() || !RHSVal.isInt())
4735 return Error(E);
4736
4737 const APSInt &LHS = LHSVal.getInt();
4738 APSInt RHS = RHSVal.getInt();
4739
4740 switch (E->getOpcode()) {
4741 default:
4742 return Error(E);
4743 case BO_Mul:
4744 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4745 LHS.getBitWidth() * 2,
4746 std::multiplies<APSInt>()), E,
4747 Result);
4748 case BO_Add:
4749 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4750 LHS.getBitWidth() + 1,
4751 std::plus<APSInt>()), E, Result);
4752 case BO_Sub:
4753 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4754 LHS.getBitWidth() + 1,
4755 std::minus<APSInt>()), E, Result);
4756 case BO_And: return Success(LHS & RHS, E, Result);
4757 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4758 case BO_Or: return Success(LHS | RHS, E, Result);
4759 case BO_Div:
4760 case BO_Rem:
4761 if (RHS == 0)
4762 return Error(E, diag::note_expr_divide_by_zero);
4763 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4764 // not actually undefined behavior in C++11 due to a language defect.
4765 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4766 LHS.isSigned() && LHS.isMinSignedValue())
4767 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4768 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4769 Result);
4770 case BO_Shl: {
4771 // During constant-folding, a negative shift is an opposite shift. Such
4772 // a shift is not a constant expression.
4773 if (RHS.isSigned() && RHS.isNegative()) {
4774 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4775 RHS = -RHS;
4776 goto shift_right;
4777 }
4778
4779 shift_left:
4780 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4781 // the shifted type.
4782 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4783 if (SA != RHS) {
4784 CCEDiag(E, diag::note_constexpr_large_shift)
4785 << RHS << E->getType() << LHS.getBitWidth();
4786 } else if (LHS.isSigned()) {
4787 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4788 // operand, and must not overflow the corresponding unsigned type.
4789 if (LHS.isNegative())
4790 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4791 else if (LHS.countLeadingZeros() < SA)
4792 CCEDiag(E, diag::note_constexpr_lshift_discards);
4793 }
4794
4795 return Success(LHS << SA, E, Result);
4796 }
4797 case BO_Shr: {
4798 // During constant-folding, a negative shift is an opposite shift. Such a
4799 // shift is not a constant expression.
4800 if (RHS.isSigned() && RHS.isNegative()) {
4801 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4802 RHS = -RHS;
4803 goto shift_left;
4804 }
4805
4806 shift_right:
4807 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4808 // shifted type.
4809 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4810 if (SA != RHS)
4811 CCEDiag(E, diag::note_constexpr_large_shift)
4812 << RHS << E->getType() << LHS.getBitWidth();
4813
4814 return Success(LHS >> SA, E, Result);
4815 }
4816
4817 case BO_LT: return Success(LHS < RHS, E, Result);
4818 case BO_GT: return Success(LHS > RHS, E, Result);
4819 case BO_LE: return Success(LHS <= RHS, E, Result);
4820 case BO_GE: return Success(LHS >= RHS, E, Result);
4821 case BO_EQ: return Success(LHS == RHS, E, Result);
4822 case BO_NE: return Success(LHS != RHS, E, Result);
4823 }
4824}
4825
Richard Trieub7783052012-03-21 23:30:30 +00004826void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004827 Job &job = Queue.back();
4828
4829 switch (job.Kind) {
4830 case Job::AnyExprKind: {
4831 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4832 if (shouldEnqueue(Bop)) {
4833 job.Kind = Job::BinOpKind;
4834 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004835 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004836 }
4837 }
4838
4839 EvaluateExpr(job.E, Result);
4840 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004841 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004842 }
4843
4844 case Job::BinOpKind: {
4845 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004846 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004847 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004848 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004849 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004850 }
4851 if (SuppressRHSDiags)
4852 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004853 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004854 job.Kind = Job::BinOpVisitedLHSKind;
4855 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004856 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004857 }
4858
4859 case Job::BinOpVisitedLHSKind: {
4860 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4861 EvalResult RHS;
4862 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004863 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004864 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004865 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004866 }
4867 }
4868
4869 llvm_unreachable("Invalid Job::Kind!");
4870}
4871
4872bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4873 if (E->isAssignmentOp())
4874 return Error(E);
4875
4876 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4877 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004878
Anders Carlsson286f85e2008-11-16 07:17:21 +00004879 QualType LHSTy = E->getLHS()->getType();
4880 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004881
4882 if (LHSTy->isAnyComplexType()) {
4883 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004884 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004885
Richard Smith745f5142012-01-27 01:14:48 +00004886 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4887 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004888 return false;
4889
Richard Smith745f5142012-01-27 01:14:48 +00004890 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004891 return false;
4892
4893 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004894 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004895 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004896 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004897 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4898
John McCall2de56d12010-08-25 11:45:40 +00004899 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004900 return Success((CR_r == APFloat::cmpEqual &&
4901 CR_i == APFloat::cmpEqual), E);
4902 else {
John McCall2de56d12010-08-25 11:45:40 +00004903 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004904 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004905 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004906 CR_r == APFloat::cmpLessThan ||
4907 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004908 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004909 CR_i == APFloat::cmpLessThan ||
4910 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004911 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004912 } else {
John McCall2de56d12010-08-25 11:45:40 +00004913 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004914 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4915 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4916 else {
John McCall2de56d12010-08-25 11:45:40 +00004917 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004918 "Invalid compex comparison.");
4919 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4920 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4921 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004922 }
4923 }
Mike Stump1eb44332009-09-09 15:08:12 +00004924
Anders Carlsson286f85e2008-11-16 07:17:21 +00004925 if (LHSTy->isRealFloatingType() &&
4926 RHSTy->isRealFloatingType()) {
4927 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004928
Richard Smith745f5142012-01-27 01:14:48 +00004929 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4930 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004931 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004932
Richard Smith745f5142012-01-27 01:14:48 +00004933 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004934 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004935
Anders Carlsson286f85e2008-11-16 07:17:21 +00004936 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004937
Anders Carlsson286f85e2008-11-16 07:17:21 +00004938 switch (E->getOpcode()) {
4939 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004940 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004941 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004942 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004943 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004944 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004945 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004946 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004947 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004948 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004949 E);
John McCall2de56d12010-08-25 11:45:40 +00004950 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004951 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004952 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004953 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004954 || CR == APFloat::cmpLessThan
4955 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004956 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004957 }
Mike Stump1eb44332009-09-09 15:08:12 +00004958
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004959 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004960 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004961 LValue LHSValue, RHSValue;
4962
4963 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4964 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004965 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004966
Richard Smith745f5142012-01-27 01:14:48 +00004967 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004968 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004969
Richard Smith625b8072011-10-31 01:37:14 +00004970 // Reject differing bases from the normal codepath; we special-case
4971 // comparisons to null.
4972 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004973 if (E->getOpcode() == BO_Sub) {
4974 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004975 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4976 return false;
4977 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4978 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4979 if (!LHSExpr || !RHSExpr)
4980 return false;
4981 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4982 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4983 if (!LHSAddrExpr || !RHSAddrExpr)
4984 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004985 // Make sure both labels come from the same function.
4986 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4987 RHSAddrExpr->getLabel()->getDeclContext())
4988 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004989 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004990 return true;
4991 }
Richard Smith9e36b532011-10-31 05:11:32 +00004992 // Inequalities and subtractions between unrelated pointers have
4993 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004994 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004995 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004996 // A constant address may compare equal to the address of a symbol.
4997 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004998 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004999 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
5000 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00005001 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00005002 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00005003 // distinct addresses. In clang, the result of such a comparison is
5004 // unspecified, so it is not a constant expression. However, we do know
5005 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00005006 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
5007 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00005008 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00005009 // We can't tell whether weak symbols will end up pointing to the same
5010 // object.
5011 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00005012 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00005013 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00005014 // (Note that clang defaults to -fmerge-all-constants, which can
5015 // lead to inconsistent results for comparisons involving the address
5016 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00005017 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00005018 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005019
Richard Smith15efc4d2012-02-01 08:10:20 +00005020 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5021 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5022
Richard Smithf15fda02012-02-02 01:16:57 +00005023 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5024 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5025
John McCall2de56d12010-08-25 11:45:40 +00005026 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00005027 // C++11 [expr.add]p6:
5028 // Unless both pointers point to elements of the same array object, or
5029 // one past the last element of the array object, the behavior is
5030 // undefined.
5031 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5032 !AreElementsOfSameArray(getType(LHSValue.Base),
5033 LHSDesignator, RHSDesignator))
5034 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5035
Chris Lattner4992bdd2010-04-20 17:13:14 +00005036 QualType Type = E->getLHS()->getType();
5037 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00005038
Richard Smith180f4792011-11-10 06:34:14 +00005039 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00005040 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00005041 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00005042
Richard Smith15efc4d2012-02-01 08:10:20 +00005043 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5044 // and produce incorrect results when it overflows. Such behavior
5045 // appears to be non-conforming, but is common, so perhaps we should
5046 // assume the standard intended for such cases to be undefined behavior
5047 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00005048
Richard Smith15efc4d2012-02-01 08:10:20 +00005049 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5050 // overflow in the final conversion to ptrdiff_t.
5051 APSInt LHS(
5052 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5053 APSInt RHS(
5054 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5055 APSInt ElemSize(
5056 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5057 APSInt TrueResult = (LHS - RHS) / ElemSize;
5058 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5059
5060 if (Result.extend(65) != TrueResult)
5061 HandleOverflow(Info, E, TrueResult, E->getType());
5062 return Success(Result, E);
5063 }
Richard Smith82f28582012-01-31 06:41:30 +00005064
5065 // C++11 [expr.rel]p3:
5066 // Pointers to void (after pointer conversions) can be compared, with a
5067 // result defined as follows: If both pointers represent the same
5068 // address or are both the null pointer value, the result is true if the
5069 // operator is <= or >= and false otherwise; otherwise the result is
5070 // unspecified.
5071 // We interpret this as applying to pointers to *cv* void.
5072 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005073 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005074 CCEDiag(E, diag::note_constexpr_void_comparison);
5075
Richard Smithf15fda02012-02-02 01:16:57 +00005076 // C++11 [expr.rel]p2:
5077 // - If two pointers point to non-static data members of the same object,
5078 // or to subobjects or array elements fo such members, recursively, the
5079 // pointer to the later declared member compares greater provided the
5080 // two members have the same access control and provided their class is
5081 // not a union.
5082 // [...]
5083 // - Otherwise pointer comparisons are unspecified.
5084 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5085 E->isRelationalOp()) {
5086 bool WasArrayIndex;
5087 unsigned Mismatch =
5088 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5089 RHSDesignator, WasArrayIndex);
5090 // At the point where the designators diverge, the comparison has a
5091 // specified value if:
5092 // - we are comparing array indices
5093 // - we are comparing fields of a union, or fields with the same access
5094 // Otherwise, the result is unspecified and thus the comparison is not a
5095 // constant expression.
5096 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5097 Mismatch < RHSDesignator.Entries.size()) {
5098 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5099 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5100 if (!LF && !RF)
5101 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5102 else if (!LF)
5103 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5104 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5105 << RF->getParent() << RF;
5106 else if (!RF)
5107 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5108 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5109 << LF->getParent() << LF;
5110 else if (!LF->getParent()->isUnion() &&
5111 LF->getAccess() != RF->getAccess())
5112 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5113 << LF << LF->getAccess() << RF << RF->getAccess()
5114 << LF->getParent();
5115 }
5116 }
5117
Eli Friedmana3169882012-04-16 04:30:08 +00005118 // The comparison here must be unsigned, and performed with the same
5119 // width as the pointer.
Eli Friedmana3169882012-04-16 04:30:08 +00005120 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5121 uint64_t CompareLHS = LHSOffset.getQuantity();
5122 uint64_t CompareRHS = RHSOffset.getQuantity();
5123 assert(PtrSize <= 64 && "Unexpected pointer width");
5124 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5125 CompareLHS &= Mask;
5126 CompareRHS &= Mask;
5127
Eli Friedman28503762012-04-16 19:23:57 +00005128 // If there is a base and this is a relational operator, we can only
5129 // compare pointers within the object in question; otherwise, the result
5130 // depends on where the object is located in memory.
5131 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5132 QualType BaseTy = getType(LHSValue.Base);
5133 if (BaseTy->isIncompleteType())
5134 return Error(E);
5135 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5136 uint64_t OffsetLimit = Size.getQuantity();
5137 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5138 return Error(E);
5139 }
5140
Richard Smith625b8072011-10-31 01:37:14 +00005141 switch (E->getOpcode()) {
5142 default: llvm_unreachable("missing comparison operator");
Eli Friedmana3169882012-04-16 04:30:08 +00005143 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5144 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5145 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5146 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5147 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5148 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005149 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005150 }
5151 }
Richard Smithb02e4622012-02-01 01:42:44 +00005152
5153 if (LHSTy->isMemberPointerType()) {
5154 assert(E->isEqualityOp() && "unexpected member pointer operation");
5155 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5156
5157 MemberPtr LHSValue, RHSValue;
5158
5159 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5160 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5161 return false;
5162
5163 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5164 return false;
5165
5166 // C++11 [expr.eq]p2:
5167 // If both operands are null, they compare equal. Otherwise if only one is
5168 // null, they compare unequal.
5169 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5170 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5171 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5172 }
5173
5174 // Otherwise if either is a pointer to a virtual member function, the
5175 // result is unspecified.
5176 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5177 if (MD->isVirtual())
5178 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5179 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5180 if (MD->isVirtual())
5181 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5182
5183 // Otherwise they compare equal if and only if they would refer to the
5184 // same member of the same most derived object or the same subobject if
5185 // they were dereferenced with a hypothetical object of the associated
5186 // class type.
5187 bool Equal = LHSValue == RHSValue;
5188 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5189 }
5190
Richard Smith26f2cac2012-02-14 22:35:28 +00005191 if (LHSTy->isNullPtrType()) {
5192 assert(E->isComparisonOp() && "unexpected nullptr operation");
5193 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5194 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5195 // are compared, the result is true of the operator is <=, >= or ==, and
5196 // false otherwise.
5197 BinaryOperator::Opcode Opcode = E->getOpcode();
5198 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5199 }
5200
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005201 assert((!LHSTy->isIntegralOrEnumerationType() ||
5202 !RHSTy->isIntegralOrEnumerationType()) &&
5203 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5204 // We can't continue from here for non-integral types.
5205 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005206}
5207
Ken Dyck8b752f12010-01-27 17:10:57 +00005208CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005209 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5210 // result shall be the alignment of the referenced type."
5211 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5212 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005213
5214 // __alignof is defined to return the preferred alignment.
5215 return Info.Ctx.toCharUnitsFromBits(
5216 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005217}
5218
Ken Dyck8b752f12010-01-27 17:10:57 +00005219CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005220 E = E->IgnoreParens();
5221
5222 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005223 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005224 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005225 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5226 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005227
Chris Lattneraf707ab2009-01-24 21:53:27 +00005228 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005229 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5230 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005231
Chris Lattnere9feb472009-01-24 21:09:06 +00005232 return GetAlignOfType(E->getType());
5233}
5234
5235
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005236/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5237/// a result as the expression's type.
5238bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5239 const UnaryExprOrTypeTraitExpr *E) {
5240 switch(E->getKind()) {
5241 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005242 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005243 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005244 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005245 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005246 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005247
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005248 case UETT_VecStep: {
5249 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005250
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005251 if (Ty->isVectorType()) {
5252 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005253
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005254 // The vec_step built-in functions that take a 3-component
5255 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5256 if (n == 3)
5257 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005258
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005259 return Success(n, E);
5260 } else
5261 return Success(1, E);
5262 }
5263
5264 case UETT_SizeOf: {
5265 QualType SrcTy = E->getTypeOfArgument();
5266 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5267 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005268 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5269 SrcTy = Ref->getPointeeType();
5270
Richard Smith180f4792011-11-10 06:34:14 +00005271 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005272 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005273 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005274 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005275 }
5276 }
5277
5278 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005279}
5280
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005281bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005282 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005283 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005284 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005285 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005286 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005287 for (unsigned i = 0; i != n; ++i) {
5288 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5289 switch (ON.getKind()) {
5290 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005291 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005292 APSInt IdxResult;
5293 if (!EvaluateInteger(Idx, IdxResult, Info))
5294 return false;
5295 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5296 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005297 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005298 CurrentType = AT->getElementType();
5299 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5300 Result += IdxResult.getSExtValue() * ElementSize;
5301 break;
5302 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005303
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005304 case OffsetOfExpr::OffsetOfNode::Field: {
5305 FieldDecl *MemberDecl = ON.getField();
5306 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005307 if (!RT)
5308 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005309 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005310 if (RD->isInvalidDecl()) return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005311 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005312 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005313 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005314 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005315 CurrentType = MemberDecl->getType().getNonReferenceType();
5316 break;
5317 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005318
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005319 case OffsetOfExpr::OffsetOfNode::Identifier:
5320 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005321
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005322 case OffsetOfExpr::OffsetOfNode::Base: {
5323 CXXBaseSpecifier *BaseSpec = ON.getBase();
5324 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005325 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005326
5327 // Find the layout of the class whose base we are looking into.
5328 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005329 if (!RT)
5330 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005331 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005332 if (RD->isInvalidDecl()) return false;
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005333 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5334
5335 // Find the base class itself.
5336 CurrentType = BaseSpec->getType();
5337 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5338 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005339 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005340
5341 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005342 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005343 break;
5344 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005345 }
5346 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005347 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005348}
5349
Chris Lattnerb542afe2008-07-11 19:10:17 +00005350bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005351 switch (E->getOpcode()) {
5352 default:
5353 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5354 // See C99 6.6p3.
5355 return Error(E);
5356 case UO_Extension:
5357 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5358 // If so, we could clear the diagnostic ID.
5359 return Visit(E->getSubExpr());
5360 case UO_Plus:
5361 // The result is just the value.
5362 return Visit(E->getSubExpr());
5363 case UO_Minus: {
5364 if (!Visit(E->getSubExpr()))
5365 return false;
5366 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005367 const APSInt &Value = Result.getInt();
5368 if (Value.isSigned() && Value.isMinSignedValue())
5369 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5370 E->getType());
5371 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005372 }
5373 case UO_Not: {
5374 if (!Visit(E->getSubExpr()))
5375 return false;
5376 if (!Result.isInt()) return Error(E);
5377 return Success(~Result.getInt(), E);
5378 }
5379 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005380 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005381 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005382 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005383 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005384 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005385 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005386}
Mike Stump1eb44332009-09-09 15:08:12 +00005387
Chris Lattner732b2232008-07-12 01:15:53 +00005388/// HandleCast - This is used to evaluate implicit or explicit casts where the
5389/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005390bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5391 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005392 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005393 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005394
Eli Friedman46a52322011-03-25 00:43:55 +00005395 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005396 case CK_BaseToDerived:
5397 case CK_DerivedToBase:
5398 case CK_UncheckedDerivedToBase:
5399 case CK_Dynamic:
5400 case CK_ToUnion:
5401 case CK_ArrayToPointerDecay:
5402 case CK_FunctionToPointerDecay:
5403 case CK_NullToPointer:
5404 case CK_NullToMemberPointer:
5405 case CK_BaseToDerivedMemberPointer:
5406 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005407 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005408 case CK_ConstructorConversion:
5409 case CK_IntegralToPointer:
5410 case CK_ToVoid:
5411 case CK_VectorSplat:
5412 case CK_IntegralToFloating:
5413 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005414 case CK_CPointerToObjCPointerCast:
5415 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005416 case CK_AnyPointerToBlockPointerCast:
5417 case CK_ObjCObjectLValueCast:
5418 case CK_FloatingRealToComplex:
5419 case CK_FloatingComplexToReal:
5420 case CK_FloatingComplexCast:
5421 case CK_FloatingComplexToIntegralComplex:
5422 case CK_IntegralRealToComplex:
5423 case CK_IntegralComplexCast:
5424 case CK_IntegralComplexToFloatingComplex:
5425 llvm_unreachable("invalid cast kind for integral value");
5426
Eli Friedmane50c2972011-03-25 19:07:11 +00005427 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005428 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005429 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005430 case CK_ARCProduceObject:
5431 case CK_ARCConsumeObject:
5432 case CK_ARCReclaimReturnedObject:
5433 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005434 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005435 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005436
Richard Smith7d580a42012-01-17 21:17:26 +00005437 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005438 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005439 case CK_AtomicToNonAtomic:
5440 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005441 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005442 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005443
5444 case CK_MemberPointerToBoolean:
5445 case CK_PointerToBoolean:
5446 case CK_IntegralToBoolean:
5447 case CK_FloatingToBoolean:
5448 case CK_FloatingComplexToBoolean:
5449 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005450 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005451 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005452 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005453 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005454 }
5455
Eli Friedman46a52322011-03-25 00:43:55 +00005456 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005457 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005458 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005459
Eli Friedmanbe265702009-02-20 01:15:07 +00005460 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005461 // Allow casts of address-of-label differences if they are no-ops
5462 // or narrowing. (The narrowing case isn't actually guaranteed to
5463 // be constant-evaluatable except in some narrow cases which are hard
5464 // to detect here. We let it through on the assumption the user knows
5465 // what they are doing.)
5466 if (Result.isAddrLabelDiff())
5467 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005468 // Only allow casts of lvalues if they are lossless.
5469 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5470 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005471
Richard Smithf72fccf2012-01-30 22:27:01 +00005472 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5473 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005474 }
Mike Stump1eb44332009-09-09 15:08:12 +00005475
Eli Friedman46a52322011-03-25 00:43:55 +00005476 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005477 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5478
John McCallefdb83e2010-05-07 21:00:08 +00005479 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005480 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005481 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005482
Daniel Dunbardd211642009-02-19 22:24:01 +00005483 if (LV.getLValueBase()) {
5484 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005485 // FIXME: Allow a larger integer size than the pointer size, and allow
5486 // narrowing back down to pointer width in subsequent integral casts.
5487 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005488 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005489 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005490
Richard Smithb755a9d2011-11-16 07:18:12 +00005491 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005492 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005493 return true;
5494 }
5495
Ken Dycka7305832010-01-15 12:37:54 +00005496 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5497 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005498 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005499 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005500
Eli Friedman46a52322011-03-25 00:43:55 +00005501 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005502 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005503 if (!EvaluateComplex(SubExpr, C, Info))
5504 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005505 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005506 }
Eli Friedman2217c872009-02-22 11:46:18 +00005507
Eli Friedman46a52322011-03-25 00:43:55 +00005508 case CK_FloatingToIntegral: {
5509 APFloat F(0.0);
5510 if (!EvaluateFloat(SubExpr, F, Info))
5511 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005512
Richard Smithc1c5f272011-12-13 06:39:58 +00005513 APSInt Value;
5514 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5515 return false;
5516 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005517 }
5518 }
Mike Stump1eb44332009-09-09 15:08:12 +00005519
Eli Friedman46a52322011-03-25 00:43:55 +00005520 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005521}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005522
Eli Friedman722c7172009-02-28 03:59:05 +00005523bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5524 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005525 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005526 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5527 return false;
5528 if (!LV.isComplexInt())
5529 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005530 return Success(LV.getComplexIntReal(), E);
5531 }
5532
5533 return Visit(E->getSubExpr());
5534}
5535
Eli Friedman664a1042009-02-27 04:45:43 +00005536bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005537 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005538 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005539 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5540 return false;
5541 if (!LV.isComplexInt())
5542 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005543 return Success(LV.getComplexIntImag(), E);
5544 }
5545
Richard Smith8327fad2011-10-24 18:44:57 +00005546 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005547 return Success(0, E);
5548}
5549
Douglas Gregoree8aff02011-01-04 17:33:58 +00005550bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5551 return Success(E->getPackLength(), E);
5552}
5553
Sebastian Redl295995c2010-09-10 20:55:47 +00005554bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5555 return Success(E->getValue(), E);
5556}
5557
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005558//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005559// Float Evaluation
5560//===----------------------------------------------------------------------===//
5561
5562namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005563class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005564 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005565 APFloat &Result;
5566public:
5567 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005568 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005569
Richard Smith1aa0be82012-03-03 22:46:17 +00005570 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005571 Result = V.getFloat();
5572 return true;
5573 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005574
Richard Smith51201882011-12-30 21:15:51 +00005575 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005576 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5577 return true;
5578 }
5579
Chris Lattner019f4e82008-10-06 05:28:25 +00005580 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005581
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005582 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005583 bool VisitBinaryOperator(const BinaryOperator *E);
5584 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005585 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005586
John McCallabd3a852010-05-07 22:08:54 +00005587 bool VisitUnaryReal(const UnaryOperator *E);
5588 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005589
Richard Smith51201882011-12-30 21:15:51 +00005590 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005591};
5592} // end anonymous namespace
5593
5594static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005595 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005596 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005597}
5598
Jay Foad4ba2a172011-01-12 09:06:06 +00005599static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005600 QualType ResultTy,
5601 const Expr *Arg,
5602 bool SNaN,
5603 llvm::APFloat &Result) {
5604 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5605 if (!S) return false;
5606
5607 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5608
5609 llvm::APInt fill;
5610
5611 // Treat empty strings as if they were zero.
5612 if (S->getString().empty())
5613 fill = llvm::APInt(32, 0);
5614 else if (S->getString().getAsInteger(0, fill))
5615 return false;
5616
5617 if (SNaN)
5618 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5619 else
5620 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5621 return true;
5622}
5623
Chris Lattner019f4e82008-10-06 05:28:25 +00005624bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005625 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005626 default:
5627 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5628
Chris Lattner019f4e82008-10-06 05:28:25 +00005629 case Builtin::BI__builtin_huge_val:
5630 case Builtin::BI__builtin_huge_valf:
5631 case Builtin::BI__builtin_huge_vall:
5632 case Builtin::BI__builtin_inf:
5633 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005634 case Builtin::BI__builtin_infl: {
5635 const llvm::fltSemantics &Sem =
5636 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005637 Result = llvm::APFloat::getInf(Sem);
5638 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005639 }
Mike Stump1eb44332009-09-09 15:08:12 +00005640
John McCalldb7b72a2010-02-28 13:00:19 +00005641 case Builtin::BI__builtin_nans:
5642 case Builtin::BI__builtin_nansf:
5643 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005644 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5645 true, Result))
5646 return Error(E);
5647 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005648
Chris Lattner9e621712008-10-06 06:31:58 +00005649 case Builtin::BI__builtin_nan:
5650 case Builtin::BI__builtin_nanf:
5651 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005652 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005653 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005654 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5655 false, Result))
5656 return Error(E);
5657 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005658
5659 case Builtin::BI__builtin_fabs:
5660 case Builtin::BI__builtin_fabsf:
5661 case Builtin::BI__builtin_fabsl:
5662 if (!EvaluateFloat(E->getArg(0), Result, Info))
5663 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005664
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005665 if (Result.isNegative())
5666 Result.changeSign();
5667 return true;
5668
Mike Stump1eb44332009-09-09 15:08:12 +00005669 case Builtin::BI__builtin_copysign:
5670 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005671 case Builtin::BI__builtin_copysignl: {
5672 APFloat RHS(0.);
5673 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5674 !EvaluateFloat(E->getArg(1), RHS, Info))
5675 return false;
5676 Result.copySign(RHS);
5677 return true;
5678 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005679 }
5680}
5681
John McCallabd3a852010-05-07 22:08:54 +00005682bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005683 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5684 ComplexValue CV;
5685 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5686 return false;
5687 Result = CV.FloatReal;
5688 return true;
5689 }
5690
5691 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005692}
5693
5694bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005695 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5696 ComplexValue CV;
5697 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5698 return false;
5699 Result = CV.FloatImag;
5700 return true;
5701 }
5702
Richard Smith8327fad2011-10-24 18:44:57 +00005703 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005704 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5705 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005706 return true;
5707}
5708
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005709bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005710 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005711 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005712 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005713 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005714 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005715 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5716 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005717 Result.changeSign();
5718 return true;
5719 }
5720}
Chris Lattner019f4e82008-10-06 05:28:25 +00005721
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005722bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005723 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5724 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005725
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005726 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005727 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5728 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005729 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005730 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005731 return false;
5732
5733 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005734 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005735 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005736 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005737 break;
John McCall2de56d12010-08-25 11:45:40 +00005738 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005739 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005740 break;
John McCall2de56d12010-08-25 11:45:40 +00005741 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005742 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005743 break;
John McCall2de56d12010-08-25 11:45:40 +00005744 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005745 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005746 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005747 }
Richard Smith7b48a292012-02-01 05:53:12 +00005748
5749 if (Result.isInfinity() || Result.isNaN())
5750 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5751 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005752}
5753
5754bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5755 Result = E->getValue();
5756 return true;
5757}
5758
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005759bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5760 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005761
Eli Friedman2a523ee2011-03-25 00:54:52 +00005762 switch (E->getCastKind()) {
5763 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005764 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005765
5766 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005767 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005768 return EvaluateInteger(SubExpr, IntResult, Info) &&
5769 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5770 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005771 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005772
5773 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005774 if (!Visit(SubExpr))
5775 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005776 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5777 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005778 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005779
Eli Friedman2a523ee2011-03-25 00:54:52 +00005780 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005781 ComplexValue V;
5782 if (!EvaluateComplex(SubExpr, V, Info))
5783 return false;
5784 Result = V.getComplexFloatReal();
5785 return true;
5786 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005787 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005788}
5789
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005790//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005791// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005792//===----------------------------------------------------------------------===//
5793
5794namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005795class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005796 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005797 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005798
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005799public:
John McCallf4cf1a12010-05-07 17:22:02 +00005800 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005801 : ExprEvaluatorBaseTy(info), Result(Result) {}
5802
Richard Smith1aa0be82012-03-03 22:46:17 +00005803 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005804 Result.setFrom(V);
5805 return true;
5806 }
Mike Stump1eb44332009-09-09 15:08:12 +00005807
Eli Friedman7ead5c72012-01-10 04:58:17 +00005808 bool ZeroInitialization(const Expr *E);
5809
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005810 //===--------------------------------------------------------------------===//
5811 // Visitor Methods
5812 //===--------------------------------------------------------------------===//
5813
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005814 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005815 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005816 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005817 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005818 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005819};
5820} // end anonymous namespace
5821
John McCallf4cf1a12010-05-07 17:22:02 +00005822static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5823 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005824 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005825 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005826}
5827
Eli Friedman7ead5c72012-01-10 04:58:17 +00005828bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005829 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005830 if (ElemTy->isRealFloatingType()) {
5831 Result.makeComplexFloat();
5832 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5833 Result.FloatReal = Zero;
5834 Result.FloatImag = Zero;
5835 } else {
5836 Result.makeComplexInt();
5837 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5838 Result.IntReal = Zero;
5839 Result.IntImag = Zero;
5840 }
5841 return true;
5842}
5843
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005844bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5845 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005846
5847 if (SubExpr->getType()->isRealFloatingType()) {
5848 Result.makeComplexFloat();
5849 APFloat &Imag = Result.FloatImag;
5850 if (!EvaluateFloat(SubExpr, Imag, Info))
5851 return false;
5852
5853 Result.FloatReal = APFloat(Imag.getSemantics());
5854 return true;
5855 } else {
5856 assert(SubExpr->getType()->isIntegerType() &&
5857 "Unexpected imaginary literal.");
5858
5859 Result.makeComplexInt();
5860 APSInt &Imag = Result.IntImag;
5861 if (!EvaluateInteger(SubExpr, Imag, Info))
5862 return false;
5863
5864 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5865 return true;
5866 }
5867}
5868
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005869bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005870
John McCall8786da72010-12-14 17:51:41 +00005871 switch (E->getCastKind()) {
5872 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005873 case CK_BaseToDerived:
5874 case CK_DerivedToBase:
5875 case CK_UncheckedDerivedToBase:
5876 case CK_Dynamic:
5877 case CK_ToUnion:
5878 case CK_ArrayToPointerDecay:
5879 case CK_FunctionToPointerDecay:
5880 case CK_NullToPointer:
5881 case CK_NullToMemberPointer:
5882 case CK_BaseToDerivedMemberPointer:
5883 case CK_DerivedToBaseMemberPointer:
5884 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005885 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005886 case CK_ConstructorConversion:
5887 case CK_IntegralToPointer:
5888 case CK_PointerToIntegral:
5889 case CK_PointerToBoolean:
5890 case CK_ToVoid:
5891 case CK_VectorSplat:
5892 case CK_IntegralCast:
5893 case CK_IntegralToBoolean:
5894 case CK_IntegralToFloating:
5895 case CK_FloatingToIntegral:
5896 case CK_FloatingToBoolean:
5897 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005898 case CK_CPointerToObjCPointerCast:
5899 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005900 case CK_AnyPointerToBlockPointerCast:
5901 case CK_ObjCObjectLValueCast:
5902 case CK_FloatingComplexToReal:
5903 case CK_FloatingComplexToBoolean:
5904 case CK_IntegralComplexToReal:
5905 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005906 case CK_ARCProduceObject:
5907 case CK_ARCConsumeObject:
5908 case CK_ARCReclaimReturnedObject:
5909 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005910 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005911 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005912
John McCall8786da72010-12-14 17:51:41 +00005913 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005914 case CK_AtomicToNonAtomic:
5915 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005916 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005917 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005918
5919 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005920 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005921 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005922 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005923
5924 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005925 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005926 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005927 return false;
5928
John McCall8786da72010-12-14 17:51:41 +00005929 Result.makeComplexFloat();
5930 Result.FloatImag = APFloat(Real.getSemantics());
5931 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005932 }
5933
John McCall8786da72010-12-14 17:51:41 +00005934 case CK_FloatingComplexCast: {
5935 if (!Visit(E->getSubExpr()))
5936 return false;
5937
5938 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5939 QualType From
5940 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5941
Richard Smithc1c5f272011-12-13 06:39:58 +00005942 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5943 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005944 }
5945
5946 case CK_FloatingComplexToIntegralComplex: {
5947 if (!Visit(E->getSubExpr()))
5948 return false;
5949
5950 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5951 QualType From
5952 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5953 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005954 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5955 To, Result.IntReal) &&
5956 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5957 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005958 }
5959
5960 case CK_IntegralRealToComplex: {
5961 APSInt &Real = Result.IntReal;
5962 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5963 return false;
5964
5965 Result.makeComplexInt();
5966 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5967 return true;
5968 }
5969
5970 case CK_IntegralComplexCast: {
5971 if (!Visit(E->getSubExpr()))
5972 return false;
5973
5974 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5975 QualType From
5976 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5977
Richard Smithf72fccf2012-01-30 22:27:01 +00005978 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5979 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005980 return true;
5981 }
5982
5983 case CK_IntegralComplexToFloatingComplex: {
5984 if (!Visit(E->getSubExpr()))
5985 return false;
5986
5987 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5988 QualType From
5989 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5990 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005991 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5992 To, Result.FloatReal) &&
5993 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5994 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005995 }
5996 }
5997
5998 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005999}
6000
John McCallf4cf1a12010-05-07 17:22:02 +00006001bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006002 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00006003 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
6004
Richard Smith745f5142012-01-27 01:14:48 +00006005 bool LHSOK = Visit(E->getLHS());
6006 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00006007 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00006008
John McCallf4cf1a12010-05-07 17:22:02 +00006009 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00006010 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00006011 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006012
Daniel Dunbar3f279872009-01-29 01:32:56 +00006013 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
6014 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006015 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00006016 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00006017 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006018 if (Result.isComplexFloat()) {
6019 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6020 APFloat::rmNearestTiesToEven);
6021 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6022 APFloat::rmNearestTiesToEven);
6023 } else {
6024 Result.getComplexIntReal() += RHS.getComplexIntReal();
6025 Result.getComplexIntImag() += RHS.getComplexIntImag();
6026 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00006027 break;
John McCall2de56d12010-08-25 11:45:40 +00006028 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00006029 if (Result.isComplexFloat()) {
6030 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6031 APFloat::rmNearestTiesToEven);
6032 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6033 APFloat::rmNearestTiesToEven);
6034 } else {
6035 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6036 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6037 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00006038 break;
John McCall2de56d12010-08-25 11:45:40 +00006039 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00006040 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00006041 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00006042 APFloat &LHS_r = LHS.getComplexFloatReal();
6043 APFloat &LHS_i = LHS.getComplexFloatImag();
6044 APFloat &RHS_r = RHS.getComplexFloatReal();
6045 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00006046
Daniel Dunbar3f279872009-01-29 01:32:56 +00006047 APFloat Tmp = LHS_r;
6048 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6049 Result.getComplexFloatReal() = Tmp;
6050 Tmp = LHS_i;
6051 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6052 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6053
6054 Tmp = LHS_r;
6055 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6056 Result.getComplexFloatImag() = Tmp;
6057 Tmp = LHS_i;
6058 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6059 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6060 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00006061 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00006062 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006063 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6064 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00006065 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006066 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6067 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6068 }
6069 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006070 case BO_Div:
6071 if (Result.isComplexFloat()) {
6072 ComplexValue LHS = Result;
6073 APFloat &LHS_r = LHS.getComplexFloatReal();
6074 APFloat &LHS_i = LHS.getComplexFloatImag();
6075 APFloat &RHS_r = RHS.getComplexFloatReal();
6076 APFloat &RHS_i = RHS.getComplexFloatImag();
6077 APFloat &Res_r = Result.getComplexFloatReal();
6078 APFloat &Res_i = Result.getComplexFloatImag();
6079
6080 APFloat Den = RHS_r;
6081 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6082 APFloat Tmp = RHS_i;
6083 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6084 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6085
6086 Res_r = LHS_r;
6087 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6088 Tmp = LHS_i;
6089 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6090 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6091 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6092
6093 Res_i = LHS_i;
6094 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6095 Tmp = LHS_r;
6096 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6097 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6098 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6099 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006100 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6101 return Error(E, diag::note_expr_divide_by_zero);
6102
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006103 ComplexValue LHS = Result;
6104 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6105 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6106 Result.getComplexIntReal() =
6107 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6108 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6109 Result.getComplexIntImag() =
6110 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6111 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6112 }
6113 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006114 }
6115
John McCallf4cf1a12010-05-07 17:22:02 +00006116 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006117}
6118
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006119bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6120 // Get the operand value into 'Result'.
6121 if (!Visit(E->getSubExpr()))
6122 return false;
6123
6124 switch (E->getOpcode()) {
6125 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006126 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006127 case UO_Extension:
6128 return true;
6129 case UO_Plus:
6130 // The result is always just the subexpr.
6131 return true;
6132 case UO_Minus:
6133 if (Result.isComplexFloat()) {
6134 Result.getComplexFloatReal().changeSign();
6135 Result.getComplexFloatImag().changeSign();
6136 }
6137 else {
6138 Result.getComplexIntReal() = -Result.getComplexIntReal();
6139 Result.getComplexIntImag() = -Result.getComplexIntImag();
6140 }
6141 return true;
6142 case UO_Not:
6143 if (Result.isComplexFloat())
6144 Result.getComplexFloatImag().changeSign();
6145 else
6146 Result.getComplexIntImag() = -Result.getComplexIntImag();
6147 return true;
6148 }
6149}
6150
Eli Friedman7ead5c72012-01-10 04:58:17 +00006151bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6152 if (E->getNumInits() == 2) {
6153 if (E->getType()->isComplexType()) {
6154 Result.makeComplexFloat();
6155 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6156 return false;
6157 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6158 return false;
6159 } else {
6160 Result.makeComplexInt();
6161 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6162 return false;
6163 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6164 return false;
6165 }
6166 return true;
6167 }
6168 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6169}
6170
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006171//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006172// Void expression evaluation, primarily for a cast to void on the LHS of a
6173// comma operator
6174//===----------------------------------------------------------------------===//
6175
6176namespace {
6177class VoidExprEvaluator
6178 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6179public:
6180 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6181
Richard Smith1aa0be82012-03-03 22:46:17 +00006182 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006183
6184 bool VisitCastExpr(const CastExpr *E) {
6185 switch (E->getCastKind()) {
6186 default:
6187 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6188 case CK_ToVoid:
6189 VisitIgnoredValue(E->getSubExpr());
6190 return true;
6191 }
6192 }
6193};
6194} // end anonymous namespace
6195
6196static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6197 assert(E->isRValue() && E->getType()->isVoidType());
6198 return VoidExprEvaluator(Info).Visit(E);
6199}
6200
6201//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006202// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006203//===----------------------------------------------------------------------===//
6204
Richard Smith1aa0be82012-03-03 22:46:17 +00006205static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006206 // In C, function designators are not lvalues, but we evaluate them as if they
6207 // are.
6208 if (E->isGLValue() || E->getType()->isFunctionType()) {
6209 LValue LV;
6210 if (!EvaluateLValue(E, LV, Info))
6211 return false;
6212 LV.moveInto(Result);
6213 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006214 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006215 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006216 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006217 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006218 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006219 } else if (E->getType()->hasPointerRepresentation()) {
6220 LValue LV;
6221 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006222 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006223 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006224 } else if (E->getType()->isRealFloatingType()) {
6225 llvm::APFloat F(0.0);
6226 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006227 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006228 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006229 } else if (E->getType()->isAnyComplexType()) {
6230 ComplexValue C;
6231 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006232 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006233 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006234 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006235 MemberPtr P;
6236 if (!EvaluateMemberPointer(E, P, Info))
6237 return false;
6238 P.moveInto(Result);
6239 return true;
Richard Smith51201882011-12-30 21:15:51 +00006240 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006241 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006242 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006243 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006244 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006245 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006246 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006247 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006248 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006249 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6250 return false;
6251 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006252 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006253 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006254 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006255 << E->getType();
6256 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00006257 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006258 if (!EvaluateVoid(E, Info))
6259 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006260 } else if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006261 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006262 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006263 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006264 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006265 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006266 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006267
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006268 return true;
6269}
6270
Richard Smith83587db2012-02-15 02:18:13 +00006271/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6272/// cases, the in-place evaluation is essential, since later initializers for
6273/// an object can indirectly refer to subobjects which were initialized earlier.
6274static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6275 const Expr *E, CheckConstantExpressionKind CCEK,
6276 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006277 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006278 return false;
6279
6280 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006281 // Evaluate arrays and record types in-place, so that later initializers can
6282 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006283 if (E->getType()->isArrayType())
6284 return EvaluateArray(E, This, Result, Info);
6285 else if (E->getType()->isRecordType())
6286 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006287 }
6288
6289 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006290 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006291}
6292
Richard Smithf48fdb02011-12-09 22:58:01 +00006293/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6294/// lvalue-to-rvalue cast if it is an lvalue.
6295static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006296 if (!CheckLiteralType(Info, E))
6297 return false;
6298
Richard Smith1aa0be82012-03-03 22:46:17 +00006299 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006300 return false;
6301
6302 if (E->isGLValue()) {
6303 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006304 LV.setFrom(Info.Ctx, Result);
6305 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006306 return false;
6307 }
6308
Richard Smith1aa0be82012-03-03 22:46:17 +00006309 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006310 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006311}
Richard Smithc49bd112011-10-28 17:51:58 +00006312
Richard Smith51f47082011-10-29 00:50:52 +00006313/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006314/// any crazy technique (that has nothing to do with language standards) that
6315/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006316/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6317/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006318bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006319 // Fast-path evaluations of integer literals, since we sometimes see files
6320 // containing vast quantities of these.
6321 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6322 Result.Val = APValue(APSInt(L->getValue(),
6323 L->getType()->isUnsignedIntegerType()));
6324 return true;
6325 }
6326
Richard Smith2d6a5672012-01-14 04:30:29 +00006327 // FIXME: Evaluating values of large array and record types can cause
6328 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006329 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006330 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006331 return false;
6332
Richard Smithf48fdb02011-12-09 22:58:01 +00006333 EvalInfo Info(Ctx, Result);
6334 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006335}
6336
Jay Foad4ba2a172011-01-12 09:06:06 +00006337bool Expr::EvaluateAsBooleanCondition(bool &Result,
6338 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006339 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006340 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006341 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006342}
6343
Richard Smith80d4b552011-12-28 19:48:30 +00006344bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6345 SideEffectsKind AllowSideEffects) const {
6346 if (!getType()->isIntegralOrEnumerationType())
6347 return false;
6348
Richard Smithc49bd112011-10-28 17:51:58 +00006349 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006350 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6351 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006352 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006353
Richard Smithc49bd112011-10-28 17:51:58 +00006354 Result = ExprResult.Val.getInt();
6355 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006356}
6357
Jay Foad4ba2a172011-01-12 09:06:06 +00006358bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006359 EvalInfo Info(Ctx, Result);
6360
John McCallefdb83e2010-05-07 21:00:08 +00006361 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006362 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6363 !CheckLValueConstantExpression(Info, getExprLoc(),
6364 Ctx.getLValueReferenceType(getType()), LV))
6365 return false;
6366
Richard Smith1aa0be82012-03-03 22:46:17 +00006367 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006368 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006369}
6370
Richard Smith099e7f62011-12-19 06:19:21 +00006371bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6372 const VarDecl *VD,
6373 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006374 // FIXME: Evaluating initializers for large array and record types can cause
6375 // performance problems. Only do so in C++11 for now.
6376 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006377 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith2d6a5672012-01-14 04:30:29 +00006378 return false;
6379
Richard Smith099e7f62011-12-19 06:19:21 +00006380 Expr::EvalStatus EStatus;
6381 EStatus.Diag = &Notes;
6382
6383 EvalInfo InitInfo(Ctx, EStatus);
6384 InitInfo.setEvaluatingDecl(VD, Value);
6385
6386 LValue LVal;
6387 LVal.set(VD);
6388
Richard Smith51201882011-12-30 21:15:51 +00006389 // C++11 [basic.start.init]p2:
6390 // Variables with static storage duration or thread storage duration shall be
6391 // zero-initialized before any other initialization takes place.
6392 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006393 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006394 !VD->getType()->isReferenceType()) {
6395 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006396 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6397 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006398 return false;
6399 }
6400
Richard Smith83587db2012-02-15 02:18:13 +00006401 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6402 /*AllowNonLiteralTypes=*/true) ||
6403 EStatus.HasSideEffects)
6404 return false;
6405
6406 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6407 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006408}
6409
Richard Smith51f47082011-10-29 00:50:52 +00006410/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6411/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006412bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006413 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006414 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006415}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006416
Jay Foad4ba2a172011-01-12 09:06:06 +00006417bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006418 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006419}
6420
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006421APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006422 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006423 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006424 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006425 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006426 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006427
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006428 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006429}
John McCalld905f5a2010-05-07 05:32:02 +00006430
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006431 bool Expr::EvalResult::isGlobalLValue() const {
6432 assert(Val.isLValue());
6433 return IsGlobalLValue(Val.getLValueBase());
6434 }
6435
6436
John McCalld905f5a2010-05-07 05:32:02 +00006437/// isIntegerConstantExpr - this recursive routine will test if an expression is
6438/// an integer constant expression.
6439
6440/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6441/// comma, etc
6442///
6443/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6444/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6445/// cast+dereference.
6446
6447// CheckICE - This function does the fundamental ICE checking: the returned
6448// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6449// Note that to reduce code duplication, this helper does no evaluation
6450// itself; the caller checks whether the expression is evaluatable, and
6451// in the rare cases where CheckICE actually cares about the evaluated
6452// value, it calls into Evalute.
6453//
6454// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006455// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006456// 1: This expression is not an ICE, but if it isn't evaluated, it's
6457// a legal subexpression for an ICE. This return value is used to handle
6458// the comma operator in C99 mode.
6459// 2: This expression is not an ICE, and is not a legal subexpression for one.
6460
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006461namespace {
6462
John McCalld905f5a2010-05-07 05:32:02 +00006463struct ICEDiag {
6464 unsigned Val;
6465 SourceLocation Loc;
6466
6467 public:
6468 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6469 ICEDiag() : Val(0) {}
6470};
6471
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006472}
6473
6474static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006475
6476static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6477 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006478 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006479 !EVResult.Val.isInt()) {
6480 return ICEDiag(2, E->getLocStart());
6481 }
6482 return NoDiag();
6483}
6484
6485static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6486 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006487 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006488 return ICEDiag(2, E->getLocStart());
6489 }
6490
6491 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006492#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006493#define STMT(Node, Base) case Expr::Node##Class:
6494#define EXPR(Node, Base)
6495#include "clang/AST/StmtNodes.inc"
6496 case Expr::PredefinedExprClass:
6497 case Expr::FloatingLiteralClass:
6498 case Expr::ImaginaryLiteralClass:
6499 case Expr::StringLiteralClass:
6500 case Expr::ArraySubscriptExprClass:
6501 case Expr::MemberExprClass:
6502 case Expr::CompoundAssignOperatorClass:
6503 case Expr::CompoundLiteralExprClass:
6504 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006505 case Expr::DesignatedInitExprClass:
6506 case Expr::ImplicitValueInitExprClass:
6507 case Expr::ParenListExprClass:
6508 case Expr::VAArgExprClass:
6509 case Expr::AddrLabelExprClass:
6510 case Expr::StmtExprClass:
6511 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006512 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006513 case Expr::CXXDynamicCastExprClass:
6514 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006515 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006516 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006517 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006518 case Expr::CXXThisExprClass:
6519 case Expr::CXXThrowExprClass:
6520 case Expr::CXXNewExprClass:
6521 case Expr::CXXDeleteExprClass:
6522 case Expr::CXXPseudoDestructorExprClass:
6523 case Expr::UnresolvedLookupExprClass:
6524 case Expr::DependentScopeDeclRefExprClass:
6525 case Expr::CXXConstructExprClass:
6526 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006527 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006528 case Expr::CXXTemporaryObjectExprClass:
6529 case Expr::CXXUnresolvedConstructExprClass:
6530 case Expr::CXXDependentScopeMemberExprClass:
6531 case Expr::UnresolvedMemberExprClass:
6532 case Expr::ObjCStringLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00006533 case Expr::ObjCBoxedExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006534 case Expr::ObjCArrayLiteralClass:
6535 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006536 case Expr::ObjCEncodeExprClass:
6537 case Expr::ObjCMessageExprClass:
6538 case Expr::ObjCSelectorExprClass:
6539 case Expr::ObjCProtocolExprClass:
6540 case Expr::ObjCIvarRefExprClass:
6541 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006542 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006543 case Expr::ObjCIsaExprClass:
6544 case Expr::ShuffleVectorExprClass:
6545 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006546 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006547 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006548 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006549 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006550 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006551 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006552 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006553 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006554 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006555 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006556 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006557 return ICEDiag(2, E->getLocStart());
6558
Douglas Gregoree8aff02011-01-04 17:33:58 +00006559 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006560 case Expr::GNUNullExprClass:
6561 // GCC considers the GNU __null value to be an integral constant expression.
6562 return NoDiag();
6563
John McCall91a57552011-07-15 05:09:51 +00006564 case Expr::SubstNonTypeTemplateParmExprClass:
6565 return
6566 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6567
John McCalld905f5a2010-05-07 05:32:02 +00006568 case Expr::ParenExprClass:
6569 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006570 case Expr::GenericSelectionExprClass:
6571 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006572 case Expr::IntegerLiteralClass:
6573 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006574 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006575 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006576 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006577 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006578 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006579 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006580 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006581 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006582 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006583 return NoDiag();
6584 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006585 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006586 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6587 // constant expressions, but they can never be ICEs because an ICE cannot
6588 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006589 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006590 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006591 return CheckEvalInICE(E, Ctx);
6592 return ICEDiag(2, E->getLocStart());
6593 }
Richard Smith359c89d2012-02-24 22:12:32 +00006594 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006595 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6596 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006597 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006598 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006599 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006600 // Parameter variables are never constants. Without this check,
6601 // getAnyInitializer() can find a default argument, which leads
6602 // to chaos.
6603 if (isa<ParmVarDecl>(D))
6604 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6605
6606 // C++ 7.1.5.1p2
6607 // A variable of non-volatile const-qualified integral or enumeration
6608 // type initialized by an ICE can be used in ICEs.
6609 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006610 if (!Dcl->getType()->isIntegralOrEnumerationType())
6611 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6612
Richard Smith099e7f62011-12-19 06:19:21 +00006613 const VarDecl *VD;
6614 // Look for a declaration of this variable that has an initializer, and
6615 // check whether it is an ICE.
6616 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6617 return NoDiag();
6618 else
6619 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006620 }
6621 }
6622 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006623 }
John McCalld905f5a2010-05-07 05:32:02 +00006624 case Expr::UnaryOperatorClass: {
6625 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6626 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006627 case UO_PostInc:
6628 case UO_PostDec:
6629 case UO_PreInc:
6630 case UO_PreDec:
6631 case UO_AddrOf:
6632 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006633 // C99 6.6/3 allows increment and decrement within unevaluated
6634 // subexpressions of constant expressions, but they can never be ICEs
6635 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006636 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006637 case UO_Extension:
6638 case UO_LNot:
6639 case UO_Plus:
6640 case UO_Minus:
6641 case UO_Not:
6642 case UO_Real:
6643 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006644 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006645 }
6646
6647 // OffsetOf falls through here.
6648 }
6649 case Expr::OffsetOfExprClass: {
6650 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006651 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006652 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006653 // compliance: we should warn earlier for offsetof expressions with
6654 // array subscripts that aren't ICEs, and if the array subscripts
6655 // are ICEs, the value of the offsetof must be an integer constant.
6656 return CheckEvalInICE(E, Ctx);
6657 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006658 case Expr::UnaryExprOrTypeTraitExprClass: {
6659 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6660 if ((Exp->getKind() == UETT_SizeOf) &&
6661 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006662 return ICEDiag(2, E->getLocStart());
6663 return NoDiag();
6664 }
6665 case Expr::BinaryOperatorClass: {
6666 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6667 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006668 case BO_PtrMemD:
6669 case BO_PtrMemI:
6670 case BO_Assign:
6671 case BO_MulAssign:
6672 case BO_DivAssign:
6673 case BO_RemAssign:
6674 case BO_AddAssign:
6675 case BO_SubAssign:
6676 case BO_ShlAssign:
6677 case BO_ShrAssign:
6678 case BO_AndAssign:
6679 case BO_XorAssign:
6680 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006681 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6682 // constant expressions, but they can never be ICEs because an ICE cannot
6683 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006684 return ICEDiag(2, E->getLocStart());
6685
John McCall2de56d12010-08-25 11:45:40 +00006686 case BO_Mul:
6687 case BO_Div:
6688 case BO_Rem:
6689 case BO_Add:
6690 case BO_Sub:
6691 case BO_Shl:
6692 case BO_Shr:
6693 case BO_LT:
6694 case BO_GT:
6695 case BO_LE:
6696 case BO_GE:
6697 case BO_EQ:
6698 case BO_NE:
6699 case BO_And:
6700 case BO_Xor:
6701 case BO_Or:
6702 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006703 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6704 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006705 if (Exp->getOpcode() == BO_Div ||
6706 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006707 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006708 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006709 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006710 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006711 if (REval == 0)
6712 return ICEDiag(1, E->getLocStart());
6713 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006714 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006715 if (LEval.isMinSignedValue())
6716 return ICEDiag(1, E->getLocStart());
6717 }
6718 }
6719 }
John McCall2de56d12010-08-25 11:45:40 +00006720 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006721 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006722 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6723 // if it isn't evaluated.
6724 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6725 return ICEDiag(1, E->getLocStart());
6726 } else {
6727 // In both C89 and C++, commas in ICEs are illegal.
6728 return ICEDiag(2, E->getLocStart());
6729 }
6730 }
6731 if (LHSResult.Val >= RHSResult.Val)
6732 return LHSResult;
6733 return RHSResult;
6734 }
John McCall2de56d12010-08-25 11:45:40 +00006735 case BO_LAnd:
6736 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006737 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6738 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6739 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6740 // Rare case where the RHS has a comma "side-effect"; we need
6741 // to actually check the condition to see whether the side
6742 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006743 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006744 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006745 return RHSResult;
6746 return NoDiag();
6747 }
6748
6749 if (LHSResult.Val >= RHSResult.Val)
6750 return LHSResult;
6751 return RHSResult;
6752 }
6753 }
6754 }
6755 case Expr::ImplicitCastExprClass:
6756 case Expr::CStyleCastExprClass:
6757 case Expr::CXXFunctionalCastExprClass:
6758 case Expr::CXXStaticCastExprClass:
6759 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006760 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006761 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006762 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006763 if (isa<ExplicitCastExpr>(E)) {
6764 if (const FloatingLiteral *FL
6765 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6766 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6767 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6768 APSInt IgnoredVal(DestWidth, !DestSigned);
6769 bool Ignored;
6770 // If the value does not fit in the destination type, the behavior is
6771 // undefined, so we are not required to treat it as a constant
6772 // expression.
6773 if (FL->getValue().convertToInteger(IgnoredVal,
6774 llvm::APFloat::rmTowardZero,
6775 &Ignored) & APFloat::opInvalidOp)
6776 return ICEDiag(2, E->getLocStart());
6777 return NoDiag();
6778 }
6779 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006780 switch (cast<CastExpr>(E)->getCastKind()) {
6781 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006782 case CK_AtomicToNonAtomic:
6783 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006784 case CK_NoOp:
6785 case CK_IntegralToBoolean:
6786 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006787 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006788 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006789 return ICEDiag(2, E->getLocStart());
6790 }
John McCalld905f5a2010-05-07 05:32:02 +00006791 }
John McCall56ca35d2011-02-17 10:25:35 +00006792 case Expr::BinaryConditionalOperatorClass: {
6793 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6794 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6795 if (CommonResult.Val == 2) return CommonResult;
6796 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6797 if (FalseResult.Val == 2) return FalseResult;
6798 if (CommonResult.Val == 1) return CommonResult;
6799 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006800 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006801 return FalseResult;
6802 }
John McCalld905f5a2010-05-07 05:32:02 +00006803 case Expr::ConditionalOperatorClass: {
6804 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6805 // If the condition (ignoring parens) is a __builtin_constant_p call,
6806 // then only the true side is actually considered in an integer constant
6807 // expression, and it is fully evaluated. This is an important GNU
6808 // extension. See GCC PR38377 for discussion.
6809 if (const CallExpr *CallCE
6810 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006811 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6812 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006813 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006814 if (CondResult.Val == 2)
6815 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006816
Richard Smithf48fdb02011-12-09 22:58:01 +00006817 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6818 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006819
John McCalld905f5a2010-05-07 05:32:02 +00006820 if (TrueResult.Val == 2)
6821 return TrueResult;
6822 if (FalseResult.Val == 2)
6823 return FalseResult;
6824 if (CondResult.Val == 1)
6825 return CondResult;
6826 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6827 return NoDiag();
6828 // Rare case where the diagnostics depend on which side is evaluated
6829 // Note that if we get here, CondResult is 0, and at least one of
6830 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006831 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006832 return FalseResult;
6833 }
6834 return TrueResult;
6835 }
6836 case Expr::CXXDefaultArgExprClass:
6837 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6838 case Expr::ChooseExprClass: {
6839 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6840 }
6841 }
6842
David Blaikie30263482012-01-20 21:50:17 +00006843 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006844}
6845
Richard Smithf48fdb02011-12-09 22:58:01 +00006846/// Evaluate an expression as a C++11 integral constant expression.
6847static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6848 const Expr *E,
6849 llvm::APSInt *Value,
6850 SourceLocation *Loc) {
6851 if (!E->getType()->isIntegralOrEnumerationType()) {
6852 if (Loc) *Loc = E->getExprLoc();
6853 return false;
6854 }
6855
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006856 APValue Result;
6857 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006858 return false;
6859
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006860 assert(Result.isInt() && "pointer cast to int is not an ICE");
6861 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006862 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006863}
6864
Richard Smithdd1f29b2011-12-12 09:28:41 +00006865bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006866 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006867 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6868
John McCalld905f5a2010-05-07 05:32:02 +00006869 ICEDiag d = CheckICE(this, Ctx);
6870 if (d.Val != 0) {
6871 if (Loc) *Loc = d.Loc;
6872 return false;
6873 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006874 return true;
6875}
6876
6877bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6878 SourceLocation *Loc, bool isEvaluated) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006879 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006880 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6881
6882 if (!isIntegerConstantExpr(Ctx, Loc))
6883 return false;
6884 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006885 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006886 return true;
6887}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006888
Richard Smith70488e22012-02-14 21:38:30 +00006889bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6890 return CheckICE(this, Ctx).Val == 0;
6891}
6892
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006893bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6894 SourceLocation *Loc) const {
6895 // We support this checking in C++98 mode in order to diagnose compatibility
6896 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006897 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006898
Richard Smith70488e22012-02-14 21:38:30 +00006899 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006900 Expr::EvalStatus Status;
6901 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6902 Status.Diag = &Diags;
6903 EvalInfo Info(Ctx, Status);
6904
6905 APValue Scratch;
6906 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6907
6908 if (!Diags.empty()) {
6909 IsConstExpr = false;
6910 if (Loc) *Loc = Diags[0].first;
6911 } else if (!IsConstExpr) {
6912 // FIXME: This shouldn't happen.
6913 if (Loc) *Loc = getExprLoc();
6914 }
6915
6916 return IsConstExpr;
6917}
Richard Smith745f5142012-01-27 01:14:48 +00006918
6919bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6920 llvm::SmallVectorImpl<
6921 PartialDiagnosticAt> &Diags) {
6922 // FIXME: It would be useful to check constexpr function templates, but at the
6923 // moment the constant expression evaluator cannot cope with the non-rigorous
6924 // ASTs which we build for dependent expressions.
6925 if (FD->isDependentContext())
6926 return true;
6927
6928 Expr::EvalStatus Status;
6929 Status.Diag = &Diags;
6930
6931 EvalInfo Info(FD->getASTContext(), Status);
6932 Info.CheckingPotentialConstantExpression = true;
6933
6934 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6935 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6936
6937 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6938 // is a temporary being used as the 'this' pointer.
6939 LValue This;
6940 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006941 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006942
Richard Smith745f5142012-01-27 01:14:48 +00006943 ArrayRef<const Expr*> Args;
6944
6945 SourceLocation Loc = FD->getLocation();
6946
Richard Smith1aa0be82012-03-03 22:46:17 +00006947 APValue Scratch;
6948 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006949 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006950 else
Richard Smith745f5142012-01-27 01:14:48 +00006951 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6952 Args, FD->getBody(), Info, Scratch);
6953
6954 return Diags.empty();
6955}