blob: 9965e1288b3bad7b006ed1904648e7b77c39a62f [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"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.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"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump4572bab2009-05-30 03:56:50 +000048#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000049#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000050
Anders Carlssonc44eec62008-07-03 04:20:39 +000051using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000054
Richard Smith83587db2012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCallf4cf1a12010-05-07 17:22:02 +000057namespace {
Richard Smith180f4792011-11-10 06:34:14 +000058 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000061
Richard Smith83587db2012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
66 return B.get<const Expr*>()->getType();
67 }
68
Richard Smith180f4792011-11-10 06:34:14 +000069 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000070 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000071 static
Richard Smithf15fda02012-02-02 01:16:57 +000072 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000073 APValue::BaseOrMemberType Value;
74 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000075 return Value;
76 }
77
78 /// Get an LValue path entry, which is known to not be an array index, as a
79 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000080 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000081 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000082 }
83 /// Get an LValue path entry, which is known to not be an array index, as a
84 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000085 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000086 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000087 }
88 /// Determine whether this LValue path entry for a base class names a virtual
89 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000090 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000091 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000092 }
93
Richard Smithb4e85ed2012-01-06 16:39:00 +000094 /// Find the path length and type of the most-derived subobject in the given
95 /// path, and find the size of the containing array, if any.
96 static
97 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
98 ArrayRef<APValue::LValuePathEntry> Path,
99 uint64_t &ArraySize, QualType &Type) {
100 unsigned MostDerivedLength = 0;
101 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000102 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000103 if (Type->isArrayType()) {
104 const ConstantArrayType *CAT =
105 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
106 Type = CAT->getElementType();
107 ArraySize = CAT->getSize().getZExtValue();
108 MostDerivedLength = I + 1;
Richard Smith86024012012-02-18 22:04:06 +0000109 } else if (Type->isAnyComplexType()) {
110 const ComplexType *CT = Type->castAs<ComplexType>();
111 Type = CT->getElementType();
112 ArraySize = 2;
113 MostDerivedLength = I + 1;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000114 } else if (const FieldDecl *FD = getAsField(Path[I])) {
115 Type = FD->getType();
116 ArraySize = 0;
117 MostDerivedLength = I + 1;
118 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000119 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000120 ArraySize = 0;
121 }
Richard Smith9a17a682011-11-07 05:07:52 +0000122 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000123 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000124 }
125
Richard Smithb4e85ed2012-01-06 16:39:00 +0000126 // The order of this enum is important for diagnostics.
127 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000128 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith86024012012-02-18 22:04:06 +0000129 CSK_This, CSK_Real, CSK_Imag
Richard Smithb4e85ed2012-01-06 16:39:00 +0000130 };
131
Richard Smith0a3bdb62011-11-04 02:25:55 +0000132 /// A path from a glvalue to a subobject of that glvalue.
133 struct SubobjectDesignator {
134 /// True if the subobject was named in a manner not supported by C++11. Such
135 /// lvalues can still be folded, but they are not core constant expressions
136 /// and we cannot perform lvalue-to-rvalue conversions on them.
137 bool Invalid : 1;
138
Richard Smithb4e85ed2012-01-06 16:39:00 +0000139 /// Is this a pointer one past the end of an object?
140 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000141
Richard Smithb4e85ed2012-01-06 16:39:00 +0000142 /// The length of the path to the most-derived object of which this is a
143 /// subobject.
144 unsigned MostDerivedPathLength : 30;
145
146 /// The size of the array of which the most-derived object is an element, or
147 /// 0 if the most-derived object is not an array element.
148 uint64_t MostDerivedArraySize;
149
150 /// The type of the most derived object referred to by this address.
151 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000152
Richard Smith9a17a682011-11-07 05:07:52 +0000153 typedef APValue::LValuePathEntry PathEntry;
154
Richard Smith0a3bdb62011-11-04 02:25:55 +0000155 /// The entries on the path from the glvalue to the designated subobject.
156 SmallVector<PathEntry, 8> Entries;
157
Richard Smithb4e85ed2012-01-06 16:39:00 +0000158 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000159
Richard Smithb4e85ed2012-01-06 16:39:00 +0000160 explicit SubobjectDesignator(QualType T)
161 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
162 MostDerivedArraySize(0), MostDerivedType(T) {}
163
164 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
165 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
166 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000167 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000168 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000169 ArrayRef<PathEntry> VEntries = V.getLValuePath();
170 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
171 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000172 MostDerivedPathLength =
173 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174 V.getLValuePath(), MostDerivedArraySize,
175 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000176 }
177 }
178
Richard Smith0a3bdb62011-11-04 02:25:55 +0000179 void setInvalid() {
180 Invalid = true;
181 Entries.clear();
182 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000183
184 /// Determine whether this is a one-past-the-end pointer.
185 bool isOnePastTheEnd() const {
186 if (IsOnePastTheEnd)
187 return true;
188 if (MostDerivedArraySize &&
189 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
190 return true;
191 return false;
192 }
193
194 /// Check that this refers to a valid subobject.
195 bool isValidSubobject() const {
196 if (Invalid)
197 return false;
198 return !isOnePastTheEnd();
199 }
200 /// Check that this refers to a valid subobject, and if not, produce a
201 /// relevant diagnostic and set the designator as invalid.
202 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
203
204 /// Update this designator to refer to the first element within this array.
205 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000206 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000207 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000208 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000209
210 // This is a most-derived object.
211 MostDerivedType = CAT->getElementType();
212 MostDerivedArraySize = CAT->getSize().getZExtValue();
213 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000214 }
215 /// Update this designator to refer to the given base or member of this
216 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000217 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000218 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000219 APValue::BaseOrMemberType Value(D, Virtual);
220 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000221 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000222
223 // If this isn't a base class, it's a new most-derived object.
224 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
225 MostDerivedType = FD->getType();
226 MostDerivedArraySize = 0;
227 MostDerivedPathLength = Entries.size();
228 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000229 }
Richard Smith86024012012-02-18 22:04:06 +0000230 /// Update this designator to refer to the given complex component.
231 void addComplexUnchecked(QualType EltTy, bool Imag) {
232 PathEntry Entry;
233 Entry.ArrayIndex = Imag;
234 Entries.push_back(Entry);
235
236 // This is technically a most-derived object, though in practice this
237 // is unlikely to matter.
238 MostDerivedType = EltTy;
239 MostDerivedArraySize = 2;
240 MostDerivedPathLength = Entries.size();
241 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000242 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000243 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000244 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000245 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000246 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000247 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000248 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
250 setInvalid();
251 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000252 return;
253 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000254 // [expr.add]p4: For the purposes of these operators, a pointer to a
255 // nonarray object behaves the same as a pointer to the first element of
256 // an array of length one with the type of the object as its element type.
257 if (IsOnePastTheEnd && N == (uint64_t)-1)
258 IsOnePastTheEnd = false;
259 else if (!IsOnePastTheEnd && N == 1)
260 IsOnePastTheEnd = true;
261 else if (N != 0) {
262 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000263 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000264 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000265 }
266 };
267
Richard Smithd0dccea2011-10-28 22:34:42 +0000268 /// A stack frame in the constexpr call stack.
269 struct CallStackFrame {
270 EvalInfo &Info;
271
272 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000273 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000274
Richard Smith08d6e032011-12-16 19:06:07 +0000275 /// CallLoc - The location of the call expression for this call.
276 SourceLocation CallLoc;
277
278 /// Callee - The function which was called.
279 const FunctionDecl *Callee;
280
Richard Smith83587db2012-02-15 02:18:13 +0000281 /// Index - The call index of this call.
282 unsigned Index;
283
Richard Smith180f4792011-11-10 06:34:14 +0000284 /// This - The binding for the this pointer in this call, if any.
285 const LValue *This;
286
Richard Smithd0dccea2011-10-28 22:34:42 +0000287 /// ParmBindings - Parameter bindings for this function call, indexed by
288 /// parameters' function scope indices.
Richard Smith1aa0be82012-03-03 22:46:17 +0000289 const APValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000290
Eli Friedmanf6172ae2012-06-25 21:21:08 +0000291 // Note that we intentionally use std::map here so that references to
292 // values are stable.
293 typedef std::map<const Expr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000294 typedef MapTy::const_iterator temp_iterator;
295 /// Temporaries - Temporary lvalues materialized within this stack frame.
296 MapTy Temporaries;
297
Richard Smith08d6e032011-12-16 19:06:07 +0000298 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
299 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000300 const APValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000301 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000302 };
303
Richard Smithdd1f29b2011-12-12 09:28:41 +0000304 /// A partial diagnostic which we might know in advance that we are not going
305 /// to emit.
306 class OptionalDiagnostic {
307 PartialDiagnostic *Diag;
308
309 public:
310 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
311
312 template<typename T>
313 OptionalDiagnostic &operator<<(const T &v) {
314 if (Diag)
315 *Diag << v;
316 return *this;
317 }
Richard Smith789f9b62012-01-31 04:08:20 +0000318
319 OptionalDiagnostic &operator<<(const APSInt &I) {
320 if (Diag) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000321 SmallVector<char, 32> Buffer;
Richard Smith789f9b62012-01-31 04:08:20 +0000322 I.toString(Buffer);
323 *Diag << StringRef(Buffer.data(), Buffer.size());
324 }
325 return *this;
326 }
327
328 OptionalDiagnostic &operator<<(const APFloat &F) {
329 if (Diag) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000330 SmallVector<char, 32> Buffer;
Richard Smith789f9b62012-01-31 04:08:20 +0000331 F.toString(Buffer);
332 *Diag << StringRef(Buffer.data(), Buffer.size());
333 }
334 return *this;
335 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000336 };
337
Richard Smith83587db2012-02-15 02:18:13 +0000338 /// EvalInfo - This is a private struct used by the evaluator to capture
339 /// information about a subexpression as it is folded. It retains information
340 /// about the AST context, but also maintains information about the folded
341 /// expression.
342 ///
343 /// If an expression could be evaluated, it is still possible it is not a C
344 /// "integer constant expression" or constant expression. If not, this struct
345 /// captures information about how and why not.
346 ///
347 /// One bit of information passed *into* the request for constant folding
348 /// indicates whether the subexpression is "evaluated" or not according to C
349 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
350 /// evaluate the expression regardless of what the RHS is, but C only allows
351 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000352 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000353 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000354
Richard Smithbd552ef2011-10-31 05:52:43 +0000355 /// EvalStatus - Contains information about the evaluation.
356 Expr::EvalStatus &EvalStatus;
357
358 /// CurrentCall - The top of the constexpr call stack.
359 CallStackFrame *CurrentCall;
360
Richard Smithbd552ef2011-10-31 05:52:43 +0000361 /// CallStackDepth - The number of calls in the call stack right now.
362 unsigned CallStackDepth;
363
Richard Smith83587db2012-02-15 02:18:13 +0000364 /// NextCallIndex - The next call index to assign.
365 unsigned NextCallIndex;
366
Richard Smithbd552ef2011-10-31 05:52:43 +0000367 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000368 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000369 CallStackFrame BottomFrame;
370
Richard Smith180f4792011-11-10 06:34:14 +0000371 /// EvaluatingDecl - This is the declaration whose initializer is being
372 /// evaluated, if any.
373 const VarDecl *EvaluatingDecl;
374
375 /// EvaluatingDeclValue - This is the value being constructed for the
376 /// declaration whose initializer is being evaluated, if any.
377 APValue *EvaluatingDeclValue;
378
Richard Smithc1c5f272011-12-13 06:39:58 +0000379 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
380 /// notes attached to it will also be stored, otherwise they will not be.
381 bool HasActiveDiagnostic;
382
Richard Smith745f5142012-01-27 01:14:48 +0000383 /// CheckingPotentialConstantExpression - Are we checking whether the
384 /// expression is a potential constant expression? If so, some diagnostics
385 /// are suppressed.
386 bool CheckingPotentialConstantExpression;
387
Richard Smithbd552ef2011-10-31 05:52:43 +0000388 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000389 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000390 CallStackDepth(0), NextCallIndex(1),
391 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000392 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Argyrios Kyrtzidis649dfbc2012-03-15 18:07:13 +0000393 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000394
Richard Smith180f4792011-11-10 06:34:14 +0000395 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
396 EvaluatingDecl = VD;
397 EvaluatingDeclValue = &Value;
398 }
399
David Blaikie4e4d0842012-03-11 07:00:24 +0000400 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000401
Richard Smithc1c5f272011-12-13 06:39:58 +0000402 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000403 // Don't perform any constexpr calls (other than the call we're checking)
404 // when checking a potential constant expression.
405 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
406 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000407 if (NextCallIndex == 0) {
408 // NextCallIndex has wrapped around.
409 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
410 return false;
411 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000412 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
413 return true;
414 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
415 << getLangOpts().ConstexprCallDepth;
416 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000417 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000418
Richard Smith83587db2012-02-15 02:18:13 +0000419 CallStackFrame *getCallFrame(unsigned CallIndex) {
420 assert(CallIndex && "no call index in getCallFrame");
421 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
422 // be null in this loop.
423 CallStackFrame *Frame = CurrentCall;
424 while (Frame->Index > CallIndex)
425 Frame = Frame->Caller;
426 return (Frame->Index == CallIndex) ? Frame : 0;
427 }
428
Richard Smithc1c5f272011-12-13 06:39:58 +0000429 private:
430 /// Add a diagnostic to the diagnostics list.
431 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
432 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
433 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
434 return EvalStatus.Diag->back().second;
435 }
436
Richard Smith08d6e032011-12-16 19:06:07 +0000437 /// Add notes containing a call stack to the current point of evaluation.
438 void addCallStack(unsigned Limit);
439
Richard Smithc1c5f272011-12-13 06:39:58 +0000440 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000441 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000442 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
443 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000444 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000445 // If we have a prior diagnostic, it will be noting that the expression
446 // isn't a constant expression. This diagnostic is more important.
447 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000448 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000449 unsigned CallStackNotes = CallStackDepth - 1;
450 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
451 if (Limit)
452 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000453 if (CheckingPotentialConstantExpression)
454 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000455
Richard Smithc1c5f272011-12-13 06:39:58 +0000456 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000457 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000458 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
459 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000460 if (!CheckingPotentialConstantExpression)
461 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000462 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000463 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000464 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000465 return OptionalDiagnostic();
466 }
467
Richard Smith5cfc7d82012-03-15 04:53:45 +0000468 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
469 = diag::note_invalid_subexpr_in_const_expr,
470 unsigned ExtraNotes = 0) {
471 if (EvalStatus.Diag)
472 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
473 HasActiveDiagnostic = false;
474 return OptionalDiagnostic();
475 }
476
Richard Smithdd1f29b2011-12-12 09:28:41 +0000477 /// Diagnose that the evaluation does not produce a C++11 core constant
478 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000479 template<typename LocArg>
480 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000481 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000482 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000483 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000484 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
485 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000486 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000487 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000488 return Diag(Loc, DiagId, ExtraNotes);
489 }
490
491 /// Add a note to a prior diagnostic.
492 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
493 if (!HasActiveDiagnostic)
494 return OptionalDiagnostic();
495 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000496 }
Richard Smith099e7f62011-12-19 06:19:21 +0000497
498 /// Add a stack of notes to a prior diagnostic.
499 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
500 if (HasActiveDiagnostic) {
501 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
502 Diags.begin(), Diags.end());
503 }
504 }
Richard Smith745f5142012-01-27 01:14:48 +0000505
506 /// Should we continue evaluation as much as possible after encountering a
507 /// construct which can't be folded?
508 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000509 return CheckingPotentialConstantExpression &&
510 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000511 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000512 };
Richard Smithf15fda02012-02-02 01:16:57 +0000513
514 /// Object used to treat all foldable expressions as constant expressions.
515 struct FoldConstant {
516 bool Enabled;
517
518 explicit FoldConstant(EvalInfo &Info)
519 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
520 !Info.EvalStatus.HasSideEffects) {
521 }
522 // Treat the value we've computed since this object was created as constant.
523 void Fold(EvalInfo &Info) {
524 if (Enabled && !Info.EvalStatus.Diag->empty() &&
525 !Info.EvalStatus.HasSideEffects)
526 Info.EvalStatus.Diag->clear();
527 }
528 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000529
530 /// RAII object used to suppress diagnostics and side-effects from a
531 /// speculative evaluation.
532 class SpeculativeEvaluationRAII {
533 EvalInfo &Info;
534 Expr::EvalStatus Old;
535
536 public:
537 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000538 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith74e1ad92012-02-16 02:46:34 +0000539 : 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.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000589static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
Richard Smith08d6e032011-12-16 19:06:07 +0000590 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
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000637 SmallVector<char, 128> Buffer;
Richard Smith08d6e032011-12-16 19:06:07 +0000638 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.
Richard Smith80ad52f2013-01-02 11:42:31 +0000740 if (!Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000741 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000742 return checkNullPointer(Info, E, CSK) &&
743 Designator.checkSubobject(Info, E, CSK);
744 }
745
746 void addDecl(EvalInfo &Info, const Expr *E,
747 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000748 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
749 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000750 }
751 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000752 if (checkSubobject(Info, E, CSK_ArrayToPointer))
753 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000754 }
Richard Smith86024012012-02-18 22:04:06 +0000755 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000756 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
757 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000758 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000759 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000760 if (checkNullPointer(Info, E, CSK_ArrayIndex))
761 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000762 }
John McCallefdb83e2010-05-07 21:00:08 +0000763 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000764
765 struct MemberPtr {
766 MemberPtr() {}
767 explicit MemberPtr(const ValueDecl *Decl) :
768 DeclAndIsDerivedMember(Decl, false), Path() {}
769
770 /// The member or (direct or indirect) field referred to by this member
771 /// pointer, or 0 if this is a null member pointer.
772 const ValueDecl *getDecl() const {
773 return DeclAndIsDerivedMember.getPointer();
774 }
775 /// Is this actually a member of some type derived from the relevant class?
776 bool isDerivedMember() const {
777 return DeclAndIsDerivedMember.getInt();
778 }
779 /// Get the class which the declaration actually lives in.
780 const CXXRecordDecl *getContainingRecord() const {
781 return cast<CXXRecordDecl>(
782 DeclAndIsDerivedMember.getPointer()->getDeclContext());
783 }
784
Richard Smith1aa0be82012-03-03 22:46:17 +0000785 void moveInto(APValue &V) const {
786 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000787 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000788 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000789 assert(V.isMemberPointer());
790 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
791 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
792 Path.clear();
793 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
794 Path.insert(Path.end(), P.begin(), P.end());
795 }
796
797 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
798 /// whether the member is a member of some class derived from the class type
799 /// of the member pointer.
800 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
801 /// Path - The path of base/derived classes from the member declaration's
802 /// class (exclusive) to the class type of the member pointer (inclusive).
803 SmallVector<const CXXRecordDecl*, 4> Path;
804
805 /// Perform a cast towards the class of the Decl (either up or down the
806 /// hierarchy).
807 bool castBack(const CXXRecordDecl *Class) {
808 assert(!Path.empty());
809 const CXXRecordDecl *Expected;
810 if (Path.size() >= 2)
811 Expected = Path[Path.size() - 2];
812 else
813 Expected = getContainingRecord();
814 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
815 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
816 // if B does not contain the original member and is not a base or
817 // derived class of the class containing the original member, the result
818 // of the cast is undefined.
819 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
820 // (D::*). We consider that to be a language defect.
821 return false;
822 }
823 Path.pop_back();
824 return true;
825 }
826 /// Perform a base-to-derived member pointer cast.
827 bool castToDerived(const CXXRecordDecl *Derived) {
828 if (!getDecl())
829 return true;
830 if (!isDerivedMember()) {
831 Path.push_back(Derived);
832 return true;
833 }
834 if (!castBack(Derived))
835 return false;
836 if (Path.empty())
837 DeclAndIsDerivedMember.setInt(false);
838 return true;
839 }
840 /// Perform a derived-to-base member pointer cast.
841 bool castToBase(const CXXRecordDecl *Base) {
842 if (!getDecl())
843 return true;
844 if (Path.empty())
845 DeclAndIsDerivedMember.setInt(true);
846 if (isDerivedMember()) {
847 Path.push_back(Base);
848 return true;
849 }
850 return castBack(Base);
851 }
852 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000853
Richard Smithb02e4622012-02-01 01:42:44 +0000854 /// Compare two member pointers, which are assumed to be of the same type.
855 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
856 if (!LHS.getDecl() || !RHS.getDecl())
857 return !LHS.getDecl() && !RHS.getDecl();
858 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
859 return false;
860 return LHS.Path == RHS.Path;
861 }
862
Richard Smithc1c5f272011-12-13 06:39:58 +0000863 /// Kinds of constant expression checking, for diagnostics.
864 enum CheckConstantExpressionKind {
865 CCEK_Constant, ///< A normal constant.
866 CCEK_ReturnValue, ///< A constexpr function return value.
867 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
868 };
John McCallf4cf1a12010-05-07 17:22:02 +0000869}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000870
Richard Smith1aa0be82012-03-03 22:46:17 +0000871static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000872static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
873 const LValue &This, const Expr *E,
874 CheckConstantExpressionKind CCEK = CCEK_Constant,
875 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000876static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
877static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000878static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
879 EvalInfo &Info);
880static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000881static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000882static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000883 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000884static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000885static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000886
887//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000888// Misc utilities
889//===----------------------------------------------------------------------===//
890
Richard Smith180f4792011-11-10 06:34:14 +0000891/// Should this call expression be treated as a string literal?
892static bool IsStringLiteralCall(const CallExpr *E) {
893 unsigned Builtin = E->isBuiltinCall();
894 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
895 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
896}
897
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000898static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000899 // C++11 [expr.const]p3 An address constant expression is a prvalue core
900 // constant expression of pointer type that evaluates to...
901
902 // ... a null pointer value, or a prvalue core constant expression of type
903 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000904 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000905
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000906 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
907 // ... the address of an object with static storage duration,
908 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
909 return VD->hasGlobalStorage();
910 // ... the address of a function,
911 return isa<FunctionDecl>(D);
912 }
913
914 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000915 switch (E->getStmtClass()) {
916 default:
917 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000918 case Expr::CompoundLiteralExprClass: {
919 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
920 return CLE->isFileScope() && CLE->isLValue();
921 }
Richard Smith180f4792011-11-10 06:34:14 +0000922 // A string literal has static storage duration.
923 case Expr::StringLiteralClass:
924 case Expr::PredefinedExprClass:
925 case Expr::ObjCStringLiteralClass:
926 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000927 case Expr::CXXTypeidExprClass:
Francois Pichete275a182012-04-16 04:08:35 +0000928 case Expr::CXXUuidofExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000929 return true;
930 case Expr::CallExprClass:
931 return IsStringLiteralCall(cast<CallExpr>(E));
932 // For GCC compatibility, &&label has static storage duration.
933 case Expr::AddrLabelExprClass:
934 return true;
935 // A Block literal expression may be used as the initialization value for
936 // Block variables at global or local static scope.
937 case Expr::BlockExprClass:
938 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000939 case Expr::ImplicitValueInitExprClass:
940 // FIXME:
941 // We can never form an lvalue with an implicit value initialization as its
942 // base through expression evaluation, so these only appear in one case: the
943 // implicit variable declaration we invent when checking whether a constexpr
944 // constructor can produce a constant expression. We must assume that such
945 // an expression might be a global lvalue.
946 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000947 }
John McCall42c8f872010-05-10 23:27:23 +0000948}
949
Richard Smith83587db2012-02-15 02:18:13 +0000950static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
951 assert(Base && "no location for a null lvalue");
952 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
953 if (VD)
954 Info.Note(VD->getLocation(), diag::note_declared_at);
955 else
Ted Kremenek890f0f12012-08-23 20:46:57 +0000956 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smith83587db2012-02-15 02:18:13 +0000957 diag::note_constexpr_temporary_here);
958}
959
Richard Smith9a17a682011-11-07 05:07:52 +0000960/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000961/// value for an address or reference constant expression. Return true if we
962/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000963static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
964 QualType Type, const LValue &LVal) {
965 bool IsReferenceType = Type->isReferenceType();
966
Richard Smithc1c5f272011-12-13 06:39:58 +0000967 APValue::LValueBase Base = LVal.getLValueBase();
968 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
969
Richard Smithb78ae972012-02-18 04:58:18 +0000970 // Check that the object is a global. Note that the fake 'this' object we
971 // manufacture when checking potential constant expressions is conservatively
972 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000973 if (!IsGlobalLValue(Base)) {
Richard Smith80ad52f2013-01-02 11:42:31 +0000974 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000975 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000976 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
977 << IsReferenceType << !Designator.Entries.empty()
978 << !!VD << VD;
979 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000980 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000981 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000982 }
Richard Smith61e61622012-01-12 06:08:57 +0000983 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000984 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000985 }
Richard Smith83587db2012-02-15 02:18:13 +0000986 assert((Info.CheckingPotentialConstantExpression ||
987 LVal.getLValueCallIndex() == 0) &&
988 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +0000989
Hans Wennborg48def652012-08-29 18:27:29 +0000990 // Check if this is a thread-local variable.
991 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
992 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
993 if (Var->isThreadSpecified())
994 return false;
995 }
996 }
997
Richard Smithb4e85ed2012-01-06 16:39:00 +0000998 // Allow address constant expressions to be past-the-end pointers. This is
999 // an extension: the standard requires them to point to an object.
1000 if (!IsReferenceType)
1001 return true;
1002
1003 // A reference constant expression must refer to an object.
1004 if (!Base) {
1005 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001006 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001007 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001008 }
1009
Richard Smithc1c5f272011-12-13 06:39:58 +00001010 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001011 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001012 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001013 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001014 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001015 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001016 }
1017
Richard Smith9a17a682011-11-07 05:07:52 +00001018 return true;
1019}
1020
Richard Smith51201882011-12-30 21:15:51 +00001021/// Check that this core constant expression is of literal type, and if not,
1022/// produce an appropriate diagnostic.
1023static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1024 if (!E->isRValue() || E->getType()->isLiteralType())
1025 return true;
1026
1027 // Prvalue constant expressions must be of literal types.
Richard Smith80ad52f2013-01-02 11:42:31 +00001028 if (Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001029 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001030 << E->getType();
1031 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001032 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001033 return false;
1034}
1035
Richard Smith47a1eed2011-10-29 20:57:55 +00001036/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001037/// constant expression. If not, report an appropriate diagnostic. Does not
1038/// check that the expression is of literal type.
1039static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1040 QualType Type, const APValue &Value) {
1041 // Core issue 1454: For a literal constant expression of array or class type,
1042 // each subobject of its value shall have been initialized by a constant
1043 // expression.
1044 if (Value.isArray()) {
1045 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1046 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1047 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1048 Value.getArrayInitializedElt(I)))
1049 return false;
1050 }
1051 if (!Value.hasArrayFiller())
1052 return true;
1053 return CheckConstantExpression(Info, DiagLoc, EltTy,
1054 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001055 }
Richard Smith83587db2012-02-15 02:18:13 +00001056 if (Value.isUnion() && Value.getUnionField()) {
1057 return CheckConstantExpression(Info, DiagLoc,
1058 Value.getUnionField()->getType(),
1059 Value.getUnionValue());
1060 }
1061 if (Value.isStruct()) {
1062 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1063 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1064 unsigned BaseIndex = 0;
1065 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1066 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1067 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1068 Value.getStructBase(BaseIndex)))
1069 return false;
1070 }
1071 }
1072 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1073 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001074 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1075 Value.getStructField(I->getFieldIndex())))
Richard Smith83587db2012-02-15 02:18:13 +00001076 return false;
1077 }
1078 }
1079
1080 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001081 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001082 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001083 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1084 }
1085
1086 // Everything else is fine.
1087 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001088}
1089
Richard Smith9e36b532011-10-31 05:11:32 +00001090const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001091 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001092}
1093
1094static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001095 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001096}
1097
Richard Smith65ac5982011-11-01 21:06:14 +00001098static bool IsWeakLValue(const LValue &Value) {
1099 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001100 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001101}
1102
Richard Smith1aa0be82012-03-03 22:46:17 +00001103static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001104 // A null base expression indicates a null pointer. These are always
1105 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001106 if (!Value.getLValueBase()) {
1107 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001108 return true;
1109 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001110
Richard Smithe24f5fc2011-11-17 22:56:20 +00001111 // We have a non-null base. These are generally known to be true, but if it's
1112 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001113 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001114 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001115 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001116}
1117
Richard Smith1aa0be82012-03-03 22:46:17 +00001118static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001119 switch (Val.getKind()) {
1120 case APValue::Uninitialized:
1121 return false;
1122 case APValue::Int:
1123 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001124 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001125 case APValue::Float:
1126 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001127 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001128 case APValue::ComplexInt:
1129 Result = Val.getComplexIntReal().getBoolValue() ||
1130 Val.getComplexIntImag().getBoolValue();
1131 return true;
1132 case APValue::ComplexFloat:
1133 Result = !Val.getComplexFloatReal().isZero() ||
1134 !Val.getComplexFloatImag().isZero();
1135 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001136 case APValue::LValue:
1137 return EvalPointerValueAsBool(Val, Result);
1138 case APValue::MemberPointer:
1139 Result = Val.getMemberPointerDecl();
1140 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001141 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001142 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001143 case APValue::Struct:
1144 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001145 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001146 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001147 }
1148
Richard Smithc49bd112011-10-28 17:51:58 +00001149 llvm_unreachable("unknown APValue kind");
1150}
1151
1152static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1153 EvalInfo &Info) {
1154 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001155 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001156 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001157 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001158 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001159}
1160
Richard Smithc1c5f272011-12-13 06:39:58 +00001161template<typename T>
Eli Friedman26dc97c2012-07-17 21:03:05 +00001162static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +00001163 const T &SrcValue, QualType DestType) {
Eli Friedman26dc97c2012-07-17 21:03:05 +00001164 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001165 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001166}
1167
1168static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1169 QualType SrcType, const APFloat &Value,
1170 QualType DestType, APSInt &Result) {
1171 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001172 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001173 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Richard Smithc1c5f272011-12-13 06:39:58 +00001175 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001176 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001177 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1178 & APFloat::opInvalidOp)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001179 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001180 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001181}
1182
Richard Smithc1c5f272011-12-13 06:39:58 +00001183static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1184 QualType SrcType, QualType DestType,
1185 APFloat &Result) {
1186 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001187 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001188 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1189 APFloat::rmNearestTiesToEven, &ignored)
1190 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001191 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001192 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001193}
1194
Richard Smithf72fccf2012-01-30 22:27:01 +00001195static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1196 QualType DestType, QualType SrcType,
1197 APSInt &Value) {
1198 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001199 APSInt Result = Value;
1200 // Figure out if this is a truncate, extend or noop cast.
1201 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001202 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001203 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001204 return Result;
1205}
1206
Richard Smithc1c5f272011-12-13 06:39:58 +00001207static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1208 QualType SrcType, const APSInt &Value,
1209 QualType DestType, APFloat &Result) {
1210 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1211 if (Result.convertFromAPInt(Value, Value.isSigned(),
1212 APFloat::rmNearestTiesToEven)
1213 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001214 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001215 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001216}
1217
Eli Friedmane6a24e82011-12-22 03:51:45 +00001218static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1219 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001220 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001221 if (!Evaluate(SVal, Info, E))
1222 return false;
1223 if (SVal.isInt()) {
1224 Res = SVal.getInt();
1225 return true;
1226 }
1227 if (SVal.isFloat()) {
1228 Res = SVal.getFloat().bitcastToAPInt();
1229 return true;
1230 }
1231 if (SVal.isVector()) {
1232 QualType VecTy = E->getType();
1233 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1234 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1235 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1236 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1237 Res = llvm::APInt::getNullValue(VecSize);
1238 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1239 APValue &Elt = SVal.getVectorElt(i);
1240 llvm::APInt EltAsInt;
1241 if (Elt.isInt()) {
1242 EltAsInt = Elt.getInt();
1243 } else if (Elt.isFloat()) {
1244 EltAsInt = Elt.getFloat().bitcastToAPInt();
1245 } else {
1246 // Don't try to handle vectors of anything other than int or float
1247 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001248 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001249 return false;
1250 }
1251 unsigned BaseEltSize = EltAsInt.getBitWidth();
1252 if (BigEndian)
1253 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1254 else
1255 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1256 }
1257 return true;
1258 }
1259 // Give up if the input isn't an int, float, or vector. For example, we
1260 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001261 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001262 return false;
1263}
1264
Richard Smithb4e85ed2012-01-06 16:39:00 +00001265/// Cast an lvalue referring to a base subobject to a derived class, by
1266/// truncating the lvalue's path to the given length.
1267static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1268 const RecordDecl *TruncatedType,
1269 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001270 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001271
1272 // Check we actually point to a derived class object.
1273 if (TruncatedElements == D.Entries.size())
1274 return true;
1275 assert(TruncatedElements >= D.MostDerivedPathLength &&
1276 "not casting to a derived class");
1277 if (!Result.checkSubobject(Info, E, CSK_Derived))
1278 return false;
1279
1280 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001281 const RecordDecl *RD = TruncatedType;
1282 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCall8d59dee2012-05-01 00:38:49 +00001283 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001284 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1285 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001286 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001287 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001288 else
Richard Smith180f4792011-11-10 06:34:14 +00001289 Result.Offset -= Layout.getBaseClassOffset(Base);
1290 RD = Base;
1291 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001292 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001293 return true;
1294}
1295
John McCall8d59dee2012-05-01 00:38:49 +00001296static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001297 const CXXRecordDecl *Derived,
1298 const CXXRecordDecl *Base,
1299 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001300 if (!RL) {
1301 if (Derived->isInvalidDecl()) return false;
1302 RL = &Info.Ctx.getASTRecordLayout(Derived);
1303 }
1304
Richard Smith180f4792011-11-10 06:34:14 +00001305 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001306 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCall8d59dee2012-05-01 00:38:49 +00001307 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001308}
1309
Richard Smithb4e85ed2012-01-06 16:39:00 +00001310static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001311 const CXXRecordDecl *DerivedDecl,
1312 const CXXBaseSpecifier *Base) {
1313 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1314
John McCall8d59dee2012-05-01 00:38:49 +00001315 if (!Base->isVirtual())
1316 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001317
Richard Smithb4e85ed2012-01-06 16:39:00 +00001318 SubobjectDesignator &D = Obj.Designator;
1319 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001320 return false;
1321
Richard Smithb4e85ed2012-01-06 16:39:00 +00001322 // Extract most-derived object and corresponding type.
1323 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1324 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1325 return false;
1326
1327 // Find the virtual base class.
John McCall8d59dee2012-05-01 00:38:49 +00001328 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001329 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1330 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001331 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001332 return true;
1333}
1334
1335/// Update LVal to refer to the given field, which must be a member of the type
1336/// currently described by LVal.
John McCall8d59dee2012-05-01 00:38:49 +00001337static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001338 const FieldDecl *FD,
1339 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001340 if (!RL) {
1341 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001342 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCall8d59dee2012-05-01 00:38:49 +00001343 }
Richard Smith180f4792011-11-10 06:34:14 +00001344
1345 unsigned I = FD->getFieldIndex();
1346 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001347 LVal.addDecl(Info, E, FD);
John McCall8d59dee2012-05-01 00:38:49 +00001348 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001349}
1350
Richard Smithd9b02e72012-01-25 22:15:11 +00001351/// Update LVal to refer to the given indirect field.
John McCall8d59dee2012-05-01 00:38:49 +00001352static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smithd9b02e72012-01-25 22:15:11 +00001353 LValue &LVal,
1354 const IndirectFieldDecl *IFD) {
1355 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1356 CE = IFD->chain_end(); C != CE; ++C)
John McCall8d59dee2012-05-01 00:38:49 +00001357 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1358 return false;
1359 return true;
Richard Smithd9b02e72012-01-25 22:15:11 +00001360}
1361
Richard Smith180f4792011-11-10 06:34:14 +00001362/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001363static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1364 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001365 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1366 // extension.
1367 if (Type->isVoidType() || Type->isFunctionType()) {
1368 Size = CharUnits::One();
1369 return true;
1370 }
1371
1372 if (!Type->isConstantSizeType()) {
1373 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001374 // FIXME: Better diagnostic.
1375 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001376 return false;
1377 }
1378
1379 Size = Info.Ctx.getTypeSizeInChars(Type);
1380 return true;
1381}
1382
1383/// Update a pointer value to model pointer arithmetic.
1384/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001385/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001386/// \param LVal - The pointer value to be updated.
1387/// \param EltTy - The pointee type represented by LVal.
1388/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001389static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1390 LValue &LVal, QualType EltTy,
1391 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001392 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001393 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001394 return false;
1395
1396 // Compute the new offset in the appropriate width.
1397 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001398 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001399 return true;
1400}
1401
Richard Smith86024012012-02-18 22:04:06 +00001402/// Update an lvalue to refer to a component of a complex number.
1403/// \param Info - Information about the ongoing evaluation.
1404/// \param LVal - The lvalue to be updated.
1405/// \param EltTy - The complex number's component type.
1406/// \param Imag - False for the real component, true for the imaginary.
1407static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1408 LValue &LVal, QualType EltTy,
1409 bool Imag) {
1410 if (Imag) {
1411 CharUnits SizeOfComponent;
1412 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1413 return false;
1414 LVal.Offset += SizeOfComponent;
1415 }
1416 LVal.addComplex(Info, E, EltTy, Imag);
1417 return true;
1418}
1419
Richard Smith03f96112011-10-24 17:54:18 +00001420/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001421static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1422 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001423 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001424 // If this is a parameter to an active constexpr function call, perform
1425 // argument substitution.
1426 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001427 // Assume arguments of a potential constant expression are unknown
1428 // constant expressions.
1429 if (Info.CheckingPotentialConstantExpression)
1430 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001431 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001432 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001433 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001434 }
Richard Smith177dce72011-11-01 16:57:24 +00001435 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1436 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001437 }
Richard Smith03f96112011-10-24 17:54:18 +00001438
Richard Smith099e7f62011-12-19 06:19:21 +00001439 // Dig out the initializer, and use the declaration which it's attached to.
1440 const Expr *Init = VD->getAnyInitializer(VD);
1441 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001442 // If we're checking a potential constant expression, the variable could be
1443 // initialized later.
1444 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001445 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001446 return false;
1447 }
1448
Richard Smith180f4792011-11-10 06:34:14 +00001449 // If we're currently evaluating the initializer of this declaration, use that
1450 // in-flight value.
1451 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001452 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001453 return !Result.isUninit();
1454 }
1455
Richard Smith65ac5982011-11-01 21:06:14 +00001456 // Never evaluate the initializer of a weak variable. We can't be sure that
1457 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001458 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001459 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001460 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001461 }
Richard Smith65ac5982011-11-01 21:06:14 +00001462
Richard Smith099e7f62011-12-19 06:19:21 +00001463 // Check that we can fold the initializer. In C++, we will have already done
1464 // this in the cases where it matters for conformance.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001465 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00001466 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001467 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001468 Notes.size() + 1) << VD;
1469 Info.Note(VD->getLocation(), diag::note_declared_at);
1470 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001471 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001472 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001473 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001474 Notes.size() + 1) << VD;
1475 Info.Note(VD->getLocation(), diag::note_declared_at);
1476 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001477 }
Richard Smith03f96112011-10-24 17:54:18 +00001478
Richard Smith1aa0be82012-03-03 22:46:17 +00001479 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001480 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001481}
1482
Richard Smithc49bd112011-10-28 17:51:58 +00001483static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001484 Qualifiers Quals = T.getQualifiers();
1485 return Quals.hasConst() && !Quals.hasVolatile();
1486}
1487
Richard Smith59efe262011-11-11 04:05:33 +00001488/// Get the base index of the given base class within an APValue representing
1489/// the given derived class.
1490static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1491 const CXXRecordDecl *Base) {
1492 Base = Base->getCanonicalDecl();
1493 unsigned Index = 0;
1494 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1495 E = Derived->bases_end(); I != E; ++I, ++Index) {
1496 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1497 return Index;
1498 }
1499
1500 llvm_unreachable("base class missing from derived class's bases list");
1501}
1502
Richard Smithfe587202012-04-15 02:50:59 +00001503/// Extract the value of a character from a string literal. CharType is used to
1504/// determine the expected signedness of the result -- a string literal used to
1505/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1506/// of the wrong signedness.
Richard Smithf3908f22012-02-17 03:35:37 +00001507static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smithfe587202012-04-15 02:50:59 +00001508 uint64_t Index, QualType CharType) {
Richard Smithf3908f22012-02-17 03:35:37 +00001509 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1510 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1511 assert(S && "unexpected string literal expression kind");
Richard Smithfe587202012-04-15 02:50:59 +00001512 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smithf3908f22012-02-17 03:35:37 +00001513
1514 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smithfe587202012-04-15 02:50:59 +00001515 CharType->isUnsignedIntegerType());
Richard Smithf3908f22012-02-17 03:35:37 +00001516 if (Index < S->getLength())
1517 Value = S->getCodeUnit(Index);
1518 return Value;
1519}
1520
Richard Smithcc5d4f62011-11-07 09:22:26 +00001521/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001522static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001523 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001524 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001525 if (Sub.Invalid)
1526 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001527 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001528 if (Sub.isOnePastTheEnd()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001529 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001530 (unsigned)diag::note_constexpr_read_past_end :
1531 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001532 return false;
1533 }
Richard Smithf64699e2011-11-11 08:28:03 +00001534 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001535 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001536 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1537 // This object might be initialized later.
1538 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001539
Richard Smith0069b842012-03-10 00:28:11 +00001540 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001541 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001542 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001543 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001544 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001545 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001546 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001547 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001548 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001549 // Note, it should not be possible to form a pointer with a valid
1550 // designator which points more than one past the end of the array.
Richard Smith80ad52f2013-01-02 11:42:31 +00001551 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001552 (unsigned)diag::note_constexpr_read_past_end :
1553 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001554 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001555 }
Richard Smithf3908f22012-02-17 03:35:37 +00001556 // An array object is represented as either an Array APValue or as an
1557 // LValue which refers to a string literal.
1558 if (O->isLValue()) {
1559 assert(I == N - 1 && "extracting subobject of character?");
1560 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001561 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithfe587202012-04-15 02:50:59 +00001562 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smithf3908f22012-02-17 03:35:37 +00001563 return true;
1564 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001565 O = &O->getArrayInitializedElt(Index);
1566 else
1567 O = &O->getArrayFiller();
1568 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001569 } else if (ObjType->isAnyComplexType()) {
1570 // Next subobject is a complex number.
1571 uint64_t Index = Sub.Entries[I].ArrayIndex;
1572 if (Index > 1) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001573 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Richard Smith86024012012-02-18 22:04:06 +00001574 (unsigned)diag::note_constexpr_read_past_end :
1575 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1576 return false;
1577 }
1578 assert(I == N - 1 && "extracting subobject of scalar?");
1579 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001580 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001581 : O->getComplexIntReal());
1582 } else {
1583 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001584 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001585 : O->getComplexFloatReal());
1586 }
1587 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001588 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001589 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001590 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001591 << Field;
1592 Info.Note(Field->getLocation(), diag::note_declared_at);
1593 return false;
1594 }
1595
Richard Smith180f4792011-11-10 06:34:14 +00001596 // Next subobject is a class, struct or union field.
1597 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1598 if (RD->isUnion()) {
1599 const FieldDecl *UnionField = O->getUnionField();
1600 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001601 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001602 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001603 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001604 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001605 }
Richard Smith180f4792011-11-10 06:34:14 +00001606 O = &O->getUnionValue();
1607 } else
1608 O = &O->getStructField(Field->getFieldIndex());
1609 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001610
1611 if (ObjType.isVolatileQualified()) {
1612 if (Info.getLangOpts().CPlusPlus) {
1613 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001614 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001615 << 2 << Field;
1616 Info.Note(Field->getLocation(), diag::note_declared_at);
1617 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001618 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001619 }
1620 return false;
1621 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001622 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001623 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001624 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1625 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1626 O = &O->getStructBase(getBaseIndex(Derived, Base));
1627 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001628 }
Richard Smith180f4792011-11-10 06:34:14 +00001629
Richard Smithf48fdb02011-12-09 22:58:01 +00001630 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001631 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001632 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001633 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001634 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001635 }
1636
Richard Smith0069b842012-03-10 00:28:11 +00001637 // This may look super-stupid, but it serves an important purpose: if we just
1638 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1639 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1640 // object, which is destroyed by Tmp's destructor.
1641 APValue Tmp;
1642 O->swap(Tmp);
1643 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001644 return true;
1645}
1646
Richard Smithf15fda02012-02-02 01:16:57 +00001647/// Find the position where two subobject designators diverge, or equivalently
1648/// the length of the common initial subsequence.
1649static unsigned FindDesignatorMismatch(QualType ObjType,
1650 const SubobjectDesignator &A,
1651 const SubobjectDesignator &B,
1652 bool &WasArrayIndex) {
1653 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1654 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001655 if (!ObjType.isNull() &&
1656 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001657 // Next subobject is an array element.
1658 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1659 WasArrayIndex = true;
1660 return I;
1661 }
Richard Smith86024012012-02-18 22:04:06 +00001662 if (ObjType->isAnyComplexType())
1663 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1664 else
1665 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001666 } else {
1667 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1668 WasArrayIndex = false;
1669 return I;
1670 }
1671 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1672 // Next subobject is a field.
1673 ObjType = FD->getType();
1674 else
1675 // Next subobject is a base class.
1676 ObjType = QualType();
1677 }
1678 }
1679 WasArrayIndex = false;
1680 return I;
1681}
1682
1683/// Determine whether the given subobject designators refer to elements of the
1684/// same array object.
1685static bool AreElementsOfSameArray(QualType ObjType,
1686 const SubobjectDesignator &A,
1687 const SubobjectDesignator &B) {
1688 if (A.Entries.size() != B.Entries.size())
1689 return false;
1690
1691 bool IsArray = A.MostDerivedArraySize != 0;
1692 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1693 // A is a subobject of the array element.
1694 return false;
1695
1696 // If A (and B) designates an array element, the last entry will be the array
1697 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1698 // of length 1' case, and the entire path must match.
1699 bool WasArrayIndex;
1700 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1701 return CommonLength >= A.Entries.size() - IsArray;
1702}
1703
Richard Smith180f4792011-11-10 06:34:14 +00001704/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1705/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1706/// for looking up the glvalue referred to by an entity of reference type.
1707///
1708/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001709/// \param Conv - The expression for which we are performing the conversion.
1710/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001711/// \param Type - The type we expect this conversion to produce, before
1712/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001713/// \param LVal - The glvalue on which we are attempting to perform this action.
1714/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001715static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1716 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001717 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001718 if (LVal.Designator.Invalid)
1719 // A diagnostic will have already been produced.
1720 return false;
1721
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001722 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001723
Richard Smithf48fdb02011-12-09 22:58:01 +00001724 if (!LVal.Base) {
1725 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001726 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001727 return false;
1728 }
1729
Richard Smith83587db2012-02-15 02:18:13 +00001730 CallStackFrame *Frame = 0;
1731 if (LVal.CallIndex) {
1732 Frame = Info.getCallFrame(LVal.CallIndex);
1733 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001734 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001735 NoteLValueLocation(Info, LVal.Base);
1736 return false;
1737 }
1738 }
1739
Richard Smith7098cbd2011-12-21 05:04:46 +00001740 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1741 // is not a constant expression (even if the object is non-volatile). We also
1742 // apply this rule to C++98, in order to conform to the expected 'volatile'
1743 // semantics.
1744 if (Type.isVolatileQualified()) {
1745 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001746 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001747 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001748 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001749 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001750 }
Richard Smithc49bd112011-10-28 17:51:58 +00001751
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001752 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001753 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1754 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001755 // expressions are constant expressions too. Inside constexpr functions,
1756 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001757 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001758 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregord2008e22012-04-06 22:40:38 +00001759 if (VD) {
1760 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1761 VD = VDef;
1762 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001763 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001764 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001765 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001766 }
1767
Richard Smith7098cbd2011-12-21 05:04:46 +00001768 // DR1313: If the object is volatile-qualified but the glvalue was not,
1769 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001770 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001771 if (VT.isVolatileQualified()) {
1772 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001773 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001774 Info.Note(VD->getLocation(), diag::note_declared_at);
1775 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001776 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001777 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001778 return false;
1779 }
1780
1781 if (!isa<ParmVarDecl>(VD)) {
1782 if (VD->isConstexpr()) {
1783 // OK, we can read this variable.
1784 } else if (VT->isIntegralOrEnumerationType()) {
1785 if (!VT.isConstQualified()) {
1786 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001787 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001788 Info.Note(VD->getLocation(), diag::note_declared_at);
1789 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001790 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001791 }
1792 return false;
1793 }
1794 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1795 // We support folding of const floating-point types, in order to make
1796 // static const data members of such types (supported as an extension)
1797 // more useful.
Richard Smith80ad52f2013-01-02 11:42:31 +00001798 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001799 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001800 Info.Note(VD->getLocation(), diag::note_declared_at);
1801 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001802 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001803 }
1804 } else {
1805 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smith80ad52f2013-01-02 11:42:31 +00001806 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001807 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001808 Info.Note(VD->getLocation(), diag::note_declared_at);
1809 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001810 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001811 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001812 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001813 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001814 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001815
Richard Smithf48fdb02011-12-09 22:58:01 +00001816 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001817 return false;
1818
Richard Smith47a1eed2011-10-29 20:57:55 +00001819 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001820 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001821
1822 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1823 // conversion. This happens when the declaration and the lvalue should be
1824 // considered synonymous, for instance when initializing an array of char
1825 // from a string literal. Continue as if the initializer lvalue was the
1826 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001827 assert(RVal.getLValueOffset().isZero() &&
1828 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001829 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001830
1831 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1832 Frame = Info.getCallFrame(CallIndex);
1833 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001834 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001835 NoteLValueLocation(Info, RVal.getLValueBase());
1836 return false;
1837 }
1838 } else {
1839 Frame = 0;
1840 }
Richard Smithc49bd112011-10-28 17:51:58 +00001841 }
1842
Richard Smith7098cbd2011-12-21 05:04:46 +00001843 // Volatile temporary objects cannot be read in constant expressions.
1844 if (Base->getType().isVolatileQualified()) {
1845 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001846 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001847 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1848 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001849 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001850 }
1851 return false;
1852 }
1853
Richard Smithcc5d4f62011-11-07 09:22:26 +00001854 if (Frame) {
1855 // If this is a temporary expression with a nontrivial initializer, grab the
1856 // value from the relevant stack frame.
1857 RVal = Frame->Temporaries[Base];
1858 } else if (const CompoundLiteralExpr *CLE
1859 = dyn_cast<CompoundLiteralExpr>(Base)) {
1860 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1861 // initializer until now for such expressions. Such an expression can't be
1862 // an ICE in C, so this only matters for fold.
1863 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1864 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1865 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001866 } else if (isa<StringLiteral>(Base)) {
1867 // We represent a string literal array as an lvalue pointing at the
1868 // corresponding expression, rather than building an array of chars.
1869 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001870 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001871 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001872 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001873 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001874 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001875
Richard Smithf48fdb02011-12-09 22:58:01 +00001876 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1877 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001878}
1879
Richard Smith59efe262011-11-11 04:05:33 +00001880/// Build an lvalue for the object argument of a member function call.
1881static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1882 LValue &This) {
1883 if (Object->getType()->isPointerType())
1884 return EvaluatePointer(Object, This, Info);
1885
1886 if (Object->isGLValue())
1887 return EvaluateLValue(Object, This, Info);
1888
Richard Smithe24f5fc2011-11-17 22:56:20 +00001889 if (Object->getType()->isLiteralType())
1890 return EvaluateTemporary(Object, This, Info);
1891
1892 return false;
1893}
1894
1895/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1896/// lvalue referring to the result.
1897///
1898/// \param Info - Information about the ongoing evaluation.
1899/// \param BO - The member pointer access operation.
1900/// \param LV - Filled in with a reference to the resulting object.
1901/// \param IncludeMember - Specifies whether the member itself is included in
1902/// the resulting LValue subobject designator. This is not possible when
1903/// creating a bound member function.
1904/// \return The field or method declaration to which the member pointer refers,
1905/// or 0 if evaluation fails.
1906static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1907 const BinaryOperator *BO,
1908 LValue &LV,
1909 bool IncludeMember = true) {
1910 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1911
Richard Smith745f5142012-01-27 01:14:48 +00001912 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1913 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001914 return 0;
1915
1916 MemberPtr MemPtr;
1917 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1918 return 0;
1919
1920 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1921 // member value, the behavior is undefined.
1922 if (!MemPtr.getDecl())
1923 return 0;
1924
Richard Smith745f5142012-01-27 01:14:48 +00001925 if (!EvalObjOK)
1926 return 0;
1927
Richard Smithe24f5fc2011-11-17 22:56:20 +00001928 if (MemPtr.isDerivedMember()) {
1929 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001930 // The end of the derived-to-base path for the base object must match the
1931 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001932 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001933 LV.Designator.Entries.size())
1934 return 0;
1935 unsigned PathLengthToMember =
1936 LV.Designator.Entries.size() - MemPtr.Path.size();
1937 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1938 const CXXRecordDecl *LVDecl = getAsBaseClass(
1939 LV.Designator.Entries[PathLengthToMember + I]);
1940 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1941 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1942 return 0;
1943 }
1944
1945 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001946 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1947 PathLengthToMember))
1948 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001949 } else if (!MemPtr.Path.empty()) {
1950 // Extend the LValue path with the member pointer's path.
1951 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1952 MemPtr.Path.size() + IncludeMember);
1953
1954 // Walk down to the appropriate base class.
1955 QualType LVType = BO->getLHS()->getType();
1956 if (const PointerType *PT = LVType->getAs<PointerType>())
1957 LVType = PT->getPointeeType();
1958 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1959 assert(RD && "member pointer access on non-class-type expression");
1960 // The first class in the path is that of the lvalue.
1961 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1962 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCall8d59dee2012-05-01 00:38:49 +00001963 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1964 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001965 RD = Base;
1966 }
1967 // Finally cast to the class containing the member.
John McCall8d59dee2012-05-01 00:38:49 +00001968 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1969 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001970 }
1971
1972 // Add the member. Note that we cannot build bound member functions here.
1973 if (IncludeMember) {
John McCall8d59dee2012-05-01 00:38:49 +00001974 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
1975 if (!HandleLValueMember(Info, BO, LV, FD))
1976 return 0;
1977 } else if (const IndirectFieldDecl *IFD =
1978 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
1979 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
1980 return 0;
1981 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00001982 llvm_unreachable("can't construct reference to bound member function");
John McCall8d59dee2012-05-01 00:38:49 +00001983 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001984 }
1985
1986 return MemPtr.getDecl();
1987}
1988
1989/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1990/// the provided lvalue, which currently refers to the base object.
1991static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1992 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001993 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001994 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001995 return false;
1996
Richard Smithb4e85ed2012-01-06 16:39:00 +00001997 QualType TargetQT = E->getType();
1998 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1999 TargetQT = PT->getPointeeType();
2000
2001 // Check this cast lands within the final derived-to-base subobject path.
2002 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002003 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002004 << D.MostDerivedType << TargetQT;
2005 return false;
2006 }
2007
Richard Smithe24f5fc2011-11-17 22:56:20 +00002008 // Check the type of the final cast. We don't need to check the path,
2009 // since a cast can only be formed if the path is unique.
2010 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002011 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2012 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002013 if (NewEntriesSize == D.MostDerivedPathLength)
2014 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2015 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002016 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002017 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002018 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002019 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002020 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002021 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002022
2023 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002024 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002025}
2026
Mike Stumpc4c90452009-10-27 22:09:17 +00002027namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002028enum EvalStmtResult {
2029 /// Evaluation failed.
2030 ESR_Failed,
2031 /// Hit a 'return' statement.
2032 ESR_Returned,
2033 /// Evaluation succeeded.
2034 ESR_Succeeded
2035};
2036}
2037
2038// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002039static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002040 const Stmt *S) {
2041 switch (S->getStmtClass()) {
2042 default:
2043 return ESR_Failed;
2044
2045 case Stmt::NullStmtClass:
2046 case Stmt::DeclStmtClass:
2047 return ESR_Succeeded;
2048
Richard Smithc1c5f272011-12-13 06:39:58 +00002049 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002050 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002051 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002052 return ESR_Failed;
2053 return ESR_Returned;
2054 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002055
2056 case Stmt::CompoundStmtClass: {
2057 const CompoundStmt *CS = cast<CompoundStmt>(S);
2058 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2059 BE = CS->body_end(); BI != BE; ++BI) {
2060 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2061 if (ESR != ESR_Succeeded)
2062 return ESR;
2063 }
2064 return ESR_Succeeded;
2065 }
2066 }
2067}
2068
Richard Smith61802452011-12-22 02:22:31 +00002069/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2070/// default constructor. If so, we'll fold it whether or not it's marked as
2071/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2072/// so we need special handling.
2073static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002074 const CXXConstructorDecl *CD,
2075 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002076 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2077 return false;
2078
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002079 // Value-initialization does not call a trivial default constructor, so such a
2080 // call is a core constant expression whether or not the constructor is
2081 // constexpr.
2082 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith80ad52f2013-01-02 11:42:31 +00002083 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002084 // FIXME: If DiagDecl is an implicitly-declared special member function,
2085 // we should be much more explicit about why it's not constexpr.
2086 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2087 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2088 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002089 } else {
2090 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2091 }
2092 }
2093 return true;
2094}
2095
Richard Smithc1c5f272011-12-13 06:39:58 +00002096/// CheckConstexprFunction - Check that a function can be called in a constant
2097/// expression.
2098static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2099 const FunctionDecl *Declaration,
2100 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002101 // Potential constant expressions can contain calls to declared, but not yet
2102 // defined, constexpr functions.
2103 if (Info.CheckingPotentialConstantExpression && !Definition &&
2104 Declaration->isConstexpr())
2105 return false;
2106
Richard Smithc1c5f272011-12-13 06:39:58 +00002107 // Can we evaluate this function call?
2108 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2109 return true;
2110
Richard Smith80ad52f2013-01-02 11:42:31 +00002111 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithc1c5f272011-12-13 06:39:58 +00002112 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002113 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2114 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002115 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2116 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2117 << DiagDecl;
2118 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2119 } else {
2120 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2121 }
2122 return false;
2123}
2124
Richard Smith180f4792011-11-10 06:34:14 +00002125namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002126typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002127}
2128
2129/// EvaluateArgs - Evaluate the arguments to a function call.
2130static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2131 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002132 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002133 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002134 I != E; ++I) {
2135 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2136 // If we're checking for a potential constant expression, evaluate all
2137 // initializers even if some of them fail.
2138 if (!Info.keepEvaluatingAfterFailure())
2139 return false;
2140 Success = false;
2141 }
2142 }
2143 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002144}
2145
Richard Smithd0dccea2011-10-28 22:34:42 +00002146/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002147static bool HandleFunctionCall(SourceLocation CallLoc,
2148 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002149 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002150 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002151 ArgVector ArgValues(Args.size());
2152 if (!EvaluateArgs(Args, ArgValues, Info))
2153 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002154
Richard Smith745f5142012-01-27 01:14:48 +00002155 if (!Info.CheckCallLimit(CallLoc))
2156 return false;
2157
2158 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002159 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2160}
2161
Richard Smith180f4792011-11-10 06:34:14 +00002162/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002163static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002164 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002165 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002166 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002167 ArgVector ArgValues(Args.size());
2168 if (!EvaluateArgs(Args, ArgValues, Info))
2169 return false;
2170
Richard Smith745f5142012-01-27 01:14:48 +00002171 if (!Info.CheckCallLimit(CallLoc))
2172 return false;
2173
Richard Smith86c3ae42012-02-13 03:54:03 +00002174 const CXXRecordDecl *RD = Definition->getParent();
2175 if (RD->getNumVBases()) {
2176 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2177 return false;
2178 }
2179
Richard Smith745f5142012-01-27 01:14:48 +00002180 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002181
2182 // If it's a delegating constructor, just delegate.
2183 if (Definition->isDelegatingConstructor()) {
2184 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002185 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002186 }
2187
Richard Smith610a60c2012-01-10 04:32:03 +00002188 // For a trivial copy or move constructor, perform an APValue copy. This is
2189 // essential for unions, where the operations performed by the constructor
2190 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002191 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002192 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2193 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002194 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002195 RHS.setFrom(Info.Ctx, ArgValues[0]);
2196 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2197 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002198 }
2199
2200 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002201 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002202 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2203 std::distance(RD->field_begin(), RD->field_end()));
2204
John McCall8d59dee2012-05-01 00:38:49 +00002205 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00002206 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2207
Richard Smith745f5142012-01-27 01:14:48 +00002208 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002209 unsigned BasesSeen = 0;
2210#ifndef NDEBUG
2211 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2212#endif
2213 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2214 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002215 LValue Subobject = This;
2216 APValue *Value = &Result;
2217
2218 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002219 if ((*I)->isBaseInitializer()) {
2220 QualType BaseType((*I)->getBaseClass(), 0);
2221#ifndef NDEBUG
2222 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002223 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002224 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2225 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2226 "base class initializers not in expected order");
2227 ++BaseIt;
2228#endif
John McCall8d59dee2012-05-01 00:38:49 +00002229 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2230 BaseType->getAsCXXRecordDecl(), &Layout))
2231 return false;
Richard Smith745f5142012-01-27 01:14:48 +00002232 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002233 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCall8d59dee2012-05-01 00:38:49 +00002234 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2235 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002236 if (RD->isUnion()) {
2237 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002238 Value = &Result.getUnionValue();
2239 } else {
2240 Value = &Result.getStructField(FD->getFieldIndex());
2241 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002242 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002243 // Walk the indirect field decl's chain to find the object to initialize,
2244 // and make sure we've initialized every step along it.
2245 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2246 CE = IFD->chain_end();
2247 C != CE; ++C) {
2248 FieldDecl *FD = cast<FieldDecl>(*C);
2249 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2250 // Switch the union field if it differs. This happens if we had
2251 // preceding zero-initialization, and we're now initializing a union
2252 // subobject other than the first.
2253 // FIXME: In this case, the values of the other subobjects are
2254 // specified, since zero-initialization sets all padding bits to zero.
2255 if (Value->isUninit() ||
2256 (Value->isUnion() && Value->getUnionField() != FD)) {
2257 if (CD->isUnion())
2258 *Value = APValue(FD);
2259 else
2260 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2261 std::distance(CD->field_begin(), CD->field_end()));
2262 }
John McCall8d59dee2012-05-01 00:38:49 +00002263 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2264 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002265 if (CD->isUnion())
2266 Value = &Value->getUnionValue();
2267 else
2268 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002269 }
Richard Smith180f4792011-11-10 06:34:14 +00002270 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002271 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002272 }
Richard Smith745f5142012-01-27 01:14:48 +00002273
Richard Smith83587db2012-02-15 02:18:13 +00002274 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2275 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002276 ? CCEK_Constant : CCEK_MemberInit)) {
2277 // If we're checking for a potential constant expression, evaluate all
2278 // initializers even if some of them fail.
2279 if (!Info.keepEvaluatingAfterFailure())
2280 return false;
2281 Success = false;
2282 }
Richard Smith180f4792011-11-10 06:34:14 +00002283 }
2284
Richard Smith745f5142012-01-27 01:14:48 +00002285 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002286}
2287
Eli Friedman4efaa272008-11-12 09:44:48 +00002288//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002289// Generic Evaluation
2290//===----------------------------------------------------------------------===//
2291namespace {
2292
Richard Smithf48fdb02011-12-09 22:58:01 +00002293// FIXME: RetTy is always bool. Remove it.
2294template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002295class ExprEvaluatorBase
2296 : public ConstStmtVisitor<Derived, RetTy> {
2297private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002298 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002299 return static_cast<Derived*>(this)->Success(V, E);
2300 }
Richard Smith51201882011-12-30 21:15:51 +00002301 RetTy DerivedZeroInitialization(const Expr *E) {
2302 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002303 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002304
Richard Smith74e1ad92012-02-16 02:46:34 +00002305 // Check whether a conditional operator with a non-constant condition is a
2306 // potential constant expression. If neither arm is a potential constant
2307 // expression, then the conditional operator is not either.
2308 template<typename ConditionalOperator>
2309 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2310 assert(Info.CheckingPotentialConstantExpression);
2311
2312 // Speculatively evaluate both arms.
2313 {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002314 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith74e1ad92012-02-16 02:46:34 +00002315 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2316
2317 StmtVisitorTy::Visit(E->getFalseExpr());
2318 if (Diag.empty())
2319 return;
2320
2321 Diag.clear();
2322 StmtVisitorTy::Visit(E->getTrueExpr());
2323 if (Diag.empty())
2324 return;
2325 }
2326
2327 Error(E, diag::note_constexpr_conditional_never_const);
2328 }
2329
2330
2331 template<typename ConditionalOperator>
2332 bool HandleConditionalOperator(const ConditionalOperator *E) {
2333 bool BoolResult;
2334 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2335 if (Info.CheckingPotentialConstantExpression)
2336 CheckPotentialConstantConditional(E);
2337 return false;
2338 }
2339
2340 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2341 return StmtVisitorTy::Visit(EvalExpr);
2342 }
2343
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002344protected:
2345 EvalInfo &Info;
2346 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2347 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2348
Richard Smithdd1f29b2011-12-12 09:28:41 +00002349 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002350 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002351 }
2352
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002353 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2354
2355public:
2356 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2357
2358 EvalInfo &getEvalInfo() { return Info; }
2359
Richard Smithf48fdb02011-12-09 22:58:01 +00002360 /// Report an evaluation error. This should only be called when an error is
2361 /// first discovered. When propagating an error, just return false.
2362 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002363 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002364 return false;
2365 }
2366 bool Error(const Expr *E) {
2367 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2368 }
2369
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002370 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002371 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002372 }
2373 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002374 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002375 }
2376
2377 RetTy VisitParenExpr(const ParenExpr *E)
2378 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2379 RetTy VisitUnaryExtension(const UnaryOperator *E)
2380 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2381 RetTy VisitUnaryPlus(const UnaryOperator *E)
2382 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2383 RetTy VisitChooseExpr(const ChooseExpr *E)
2384 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2385 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2386 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002387 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2388 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002389 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2390 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002391 // We cannot create any objects for which cleanups are required, so there is
2392 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2393 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2394 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002395
Richard Smithc216a012011-12-12 12:46:16 +00002396 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2397 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2398 return static_cast<Derived*>(this)->VisitCastExpr(E);
2399 }
2400 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2401 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2402 return static_cast<Derived*>(this)->VisitCastExpr(E);
2403 }
2404
Richard Smithe24f5fc2011-11-17 22:56:20 +00002405 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2406 switch (E->getOpcode()) {
2407 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002408 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002409
2410 case BO_Comma:
2411 VisitIgnoredValue(E->getLHS());
2412 return StmtVisitorTy::Visit(E->getRHS());
2413
2414 case BO_PtrMemD:
2415 case BO_PtrMemI: {
2416 LValue Obj;
2417 if (!HandleMemberPointerAccess(Info, E, Obj))
2418 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002419 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002420 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002421 return false;
2422 return DerivedSuccess(Result, E);
2423 }
2424 }
2425 }
2426
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002427 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002428 // Evaluate and cache the common expression. We treat it as a temporary,
2429 // even though it's not quite the same thing.
2430 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2431 Info, E->getCommon()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002432 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002433
Richard Smith74e1ad92012-02-16 02:46:34 +00002434 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002435 }
2436
2437 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002438 bool IsBcpCall = false;
2439 // If the condition (ignoring parens) is a __builtin_constant_p call,
2440 // the result is a constant expression if it can be folded without
2441 // side-effects. This is an important GNU extension. See GCC PR38377
2442 // for discussion.
2443 if (const CallExpr *CallCE =
2444 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2445 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2446 IsBcpCall = true;
2447
2448 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2449 // constant expression; we can't check whether it's potentially foldable.
2450 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2451 return false;
2452
2453 FoldConstant Fold(Info);
2454
Richard Smith74e1ad92012-02-16 02:46:34 +00002455 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002456 return false;
2457
2458 if (IsBcpCall)
2459 Fold.Fold(Info);
2460
2461 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002462 }
2463
2464 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002465 APValue &Value = Info.CurrentCall->Temporaries[E];
2466 if (Value.isUninit()) {
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002467 const Expr *Source = E->getSourceExpr();
2468 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002469 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002470 if (Source == E) { // sanity checking.
2471 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002472 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002473 }
2474 return StmtVisitorTy::Visit(Source);
2475 }
Richard Smithe92b1f42012-06-26 08:12:11 +00002476 return DerivedSuccess(Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002477 }
Richard Smithf10d9172011-10-11 21:43:33 +00002478
Richard Smithd0dccea2011-10-28 22:34:42 +00002479 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002480 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002481 QualType CalleeType = Callee->getType();
2482
Richard Smithd0dccea2011-10-28 22:34:42 +00002483 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002484 LValue *This = 0, ThisVal;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002485 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002486 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002487
Richard Smith59efe262011-11-11 04:05:33 +00002488 // Extract function decl and 'this' pointer from the callee.
2489 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002490 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002491 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2492 // Explicit bound member calls, such as x.f() or p->g();
2493 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002494 return false;
2495 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002496 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002497 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002498 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2499 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002500 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2501 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002502 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002503 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002504 return Error(Callee);
2505
2506 FD = dyn_cast<FunctionDecl>(Member);
2507 if (!FD)
2508 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002509 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002510 LValue Call;
2511 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002512 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002513
Richard Smithb4e85ed2012-01-06 16:39:00 +00002514 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002515 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002516 FD = dyn_cast_or_null<FunctionDecl>(
2517 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002518 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002519 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002520
2521 // Overloaded operator calls to member functions are represented as normal
2522 // calls with '*this' as the first argument.
2523 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2524 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002525 // FIXME: When selecting an implicit conversion for an overloaded
2526 // operator delete, we sometimes try to evaluate calls to conversion
2527 // operators without a 'this' parameter!
2528 if (Args.empty())
2529 return Error(E);
2530
Richard Smith59efe262011-11-11 04:05:33 +00002531 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2532 return false;
2533 This = &ThisVal;
2534 Args = Args.slice(1);
2535 }
2536
2537 // Don't call function pointers which have been cast to some other type.
2538 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002539 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002540 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002541 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002542
Richard Smithb04035a2012-02-01 02:39:43 +00002543 if (This && !This->checkSubobject(Info, E, CSK_This))
2544 return false;
2545
Richard Smith86c3ae42012-02-13 03:54:03 +00002546 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2547 // calls to such functions in constant expressions.
2548 if (This && !HasQualifier &&
2549 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2550 return Error(E, diag::note_constexpr_virtual_call);
2551
Richard Smithc1c5f272011-12-13 06:39:58 +00002552 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002553 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002554 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002555
Richard Smithc1c5f272011-12-13 06:39:58 +00002556 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002557 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2558 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002559 return false;
2560
Richard Smith83587db2012-02-15 02:18:13 +00002561 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002562 }
2563
Richard Smithc49bd112011-10-28 17:51:58 +00002564 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2565 return StmtVisitorTy::Visit(E->getInitializer());
2566 }
Richard Smithf10d9172011-10-11 21:43:33 +00002567 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002568 if (E->getNumInits() == 0)
2569 return DerivedZeroInitialization(E);
2570 if (E->getNumInits() == 1)
2571 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002572 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002573 }
2574 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002575 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002576 }
2577 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002578 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002579 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002580 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002581 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002582 }
Richard Smithf10d9172011-10-11 21:43:33 +00002583
Richard Smith180f4792011-11-10 06:34:14 +00002584 /// A member expression where the object is a prvalue is itself a prvalue.
2585 RetTy VisitMemberExpr(const MemberExpr *E) {
2586 assert(!E->isArrow() && "missing call to bound member function?");
2587
Richard Smith1aa0be82012-03-03 22:46:17 +00002588 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002589 if (!Evaluate(Val, Info, E->getBase()))
2590 return false;
2591
2592 QualType BaseTy = E->getBase()->getType();
2593
2594 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002595 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002596 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek890f0f12012-08-23 20:46:57 +00002597 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smith180f4792011-11-10 06:34:14 +00002598 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2599
Richard Smithb4e85ed2012-01-06 16:39:00 +00002600 SubobjectDesignator Designator(BaseTy);
2601 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002602
Richard Smithf48fdb02011-12-09 22:58:01 +00002603 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002604 DerivedSuccess(Val, E);
2605 }
2606
Richard Smithc49bd112011-10-28 17:51:58 +00002607 RetTy VisitCastExpr(const CastExpr *E) {
2608 switch (E->getCastKind()) {
2609 default:
2610 break;
2611
David Chisnall7a7ee302012-01-16 17:27:18 +00002612 case CK_AtomicToNonAtomic:
2613 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002614 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002615 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002616 return StmtVisitorTy::Visit(E->getSubExpr());
2617
2618 case CK_LValueToRValue: {
2619 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002620 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2621 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002622 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002623 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2624 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2625 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002626 return false;
2627 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002628 }
2629 }
2630
Richard Smithf48fdb02011-12-09 22:58:01 +00002631 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002632 }
2633
Richard Smith8327fad2011-10-24 18:44:57 +00002634 /// Visit a value which is evaluated, but whose value is ignored.
2635 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002636 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002637 if (!Evaluate(Scratch, Info, E))
2638 Info.EvalStatus.HasSideEffects = true;
2639 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002640};
2641
2642}
2643
2644//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002645// Common base class for lvalue and temporary evaluation.
2646//===----------------------------------------------------------------------===//
2647namespace {
2648template<class Derived>
2649class LValueExprEvaluatorBase
2650 : public ExprEvaluatorBase<Derived, bool> {
2651protected:
2652 LValue &Result;
2653 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2654 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2655
2656 bool Success(APValue::LValueBase B) {
2657 Result.set(B);
2658 return true;
2659 }
2660
2661public:
2662 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2663 ExprEvaluatorBaseTy(Info), Result(Result) {}
2664
Richard Smith1aa0be82012-03-03 22:46:17 +00002665 bool Success(const APValue &V, const Expr *E) {
2666 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002667 return true;
2668 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002669
Richard Smithe24f5fc2011-11-17 22:56:20 +00002670 bool VisitMemberExpr(const MemberExpr *E) {
2671 // Handle non-static data members.
2672 QualType BaseTy;
2673 if (E->isArrow()) {
2674 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2675 return false;
Ted Kremenek890f0f12012-08-23 20:46:57 +00002676 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002677 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002678 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002679 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2680 return false;
2681 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002682 } else {
2683 if (!this->Visit(E->getBase()))
2684 return false;
2685 BaseTy = E->getBase()->getType();
2686 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002687
Richard Smithd9b02e72012-01-25 22:15:11 +00002688 const ValueDecl *MD = E->getMemberDecl();
2689 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2690 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2691 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2692 (void)BaseTy;
John McCall8d59dee2012-05-01 00:38:49 +00002693 if (!HandleLValueMember(this->Info, E, Result, FD))
2694 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002695 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCall8d59dee2012-05-01 00:38:49 +00002696 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2697 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002698 } else
2699 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002700
Richard Smithd9b02e72012-01-25 22:15:11 +00002701 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002702 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002703 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002704 RefValue))
2705 return false;
2706 return Success(RefValue, E);
2707 }
2708 return true;
2709 }
2710
2711 bool VisitBinaryOperator(const BinaryOperator *E) {
2712 switch (E->getOpcode()) {
2713 default:
2714 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2715
2716 case BO_PtrMemD:
2717 case BO_PtrMemI:
2718 return HandleMemberPointerAccess(this->Info, E, Result);
2719 }
2720 }
2721
2722 bool VisitCastExpr(const CastExpr *E) {
2723 switch (E->getCastKind()) {
2724 default:
2725 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2726
2727 case CK_DerivedToBase:
2728 case CK_UncheckedDerivedToBase: {
2729 if (!this->Visit(E->getSubExpr()))
2730 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002731
2732 // Now figure out the necessary offset to add to the base LV to get from
2733 // the derived class to the base class.
2734 QualType Type = E->getSubExpr()->getType();
2735
2736 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2737 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002738 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002739 *PathI))
2740 return false;
2741 Type = (*PathI)->getType();
2742 }
2743
2744 return true;
2745 }
2746 }
2747 }
2748};
2749}
2750
2751//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002752// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002753//
2754// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2755// function designators (in C), decl references to void objects (in C), and
2756// temporaries (if building with -Wno-address-of-temporary).
2757//
2758// LValue evaluation produces values comprising a base expression of one of the
2759// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002760// - Declarations
2761// * VarDecl
2762// * FunctionDecl
2763// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002764// * CompoundLiteralExpr in C
2765// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002766// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002767// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002768// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002769// * ObjCEncodeExpr
2770// * AddrLabelExpr
2771// * BlockExpr
2772// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002773// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002774// * Any Expr, with a CallIndex indicating the function in which the temporary
2775// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002776// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002777//===----------------------------------------------------------------------===//
2778namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002779class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002780 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002781public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002782 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2783 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002784
Richard Smithc49bd112011-10-28 17:51:58 +00002785 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2786
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002787 bool VisitDeclRefExpr(const DeclRefExpr *E);
2788 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002789 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002790 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2791 bool VisitMemberExpr(const MemberExpr *E);
2792 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2793 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002794 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichete275a182012-04-16 04:08:35 +00002795 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002796 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2797 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002798 bool VisitUnaryReal(const UnaryOperator *E);
2799 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002800
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002801 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002802 switch (E->getCastKind()) {
2803 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002804 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002805
Eli Friedmandb924222011-10-11 00:13:24 +00002806 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002807 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002808 if (!Visit(E->getSubExpr()))
2809 return false;
2810 Result.Designator.setInvalid();
2811 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002812
Richard Smithe24f5fc2011-11-17 22:56:20 +00002813 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002814 if (!Visit(E->getSubExpr()))
2815 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002816 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002817 }
2818 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002819};
2820} // end anonymous namespace
2821
Richard Smithc49bd112011-10-28 17:51:58 +00002822/// Evaluate an expression as an lvalue. This can be legitimately called on
2823/// expressions which are not glvalues, in a few cases:
2824/// * function designators in C,
2825/// * "extern void" objects,
2826/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002827static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002828 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2829 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2830 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002831 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002832}
2833
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002834bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002835 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2836 return Success(FD);
2837 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002838 return VisitVarDecl(E, VD);
2839 return Error(E);
2840}
Richard Smith436c8892011-10-24 23:14:33 +00002841
Richard Smithc49bd112011-10-28 17:51:58 +00002842bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002843 if (!VD->getType()->isReferenceType()) {
2844 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002845 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002846 return true;
2847 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002848 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002849 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002850
Richard Smith1aa0be82012-03-03 22:46:17 +00002851 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002852 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2853 return false;
2854 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002855}
2856
Richard Smithbd552ef2011-10-31 05:52:43 +00002857bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2858 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002859 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002860 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002861 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2862
Richard Smith83587db2012-02-15 02:18:13 +00002863 Result.set(E, Info.CurrentCall->Index);
2864 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2865 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002866 }
2867
2868 // Materialization of an lvalue temporary occurs when we need to force a copy
2869 // (for instance, if it's a bitfield).
2870 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2871 if (!Visit(E->GetTemporaryExpr()))
2872 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002873 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002874 Info.CurrentCall->Temporaries[E]))
2875 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002876 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002877 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002878}
2879
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002880bool
2881LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002882 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2883 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2884 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002885 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002886}
2887
Richard Smith47d21452011-12-27 12:18:28 +00002888bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith9be36ab2012-10-17 23:52:07 +00002889 if (!E->isPotentiallyEvaluated())
Richard Smith47d21452011-12-27 12:18:28 +00002890 return Success(E);
Richard Smith9be36ab2012-10-17 23:52:07 +00002891
2892 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
2893 << E->getExprOperand()->getType()
2894 << E->getExprOperand()->getSourceRange();
2895 return false;
Richard Smith47d21452011-12-27 12:18:28 +00002896}
2897
Francois Pichete275a182012-04-16 04:08:35 +00002898bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2899 return Success(E);
2900}
2901
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002902bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002903 // Handle static data members.
2904 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2905 VisitIgnoredValue(E->getBase());
2906 return VisitVarDecl(E, VD);
2907 }
2908
Richard Smithd0dccea2011-10-28 22:34:42 +00002909 // Handle static member functions.
2910 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2911 if (MD->isStatic()) {
2912 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002913 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002914 }
2915 }
2916
Richard Smith180f4792011-11-10 06:34:14 +00002917 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002918 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002919}
2920
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002921bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002922 // FIXME: Deal with vectors as array subscript bases.
2923 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002924 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002925
Anders Carlsson3068d112008-11-16 19:01:22 +00002926 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002927 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002928
Anders Carlsson3068d112008-11-16 19:01:22 +00002929 APSInt Index;
2930 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002931 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002932 int64_t IndexValue
2933 = Index.isSigned() ? Index.getSExtValue()
2934 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002935
Richard Smithb4e85ed2012-01-06 16:39:00 +00002936 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002937}
Eli Friedman4efaa272008-11-12 09:44:48 +00002938
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002939bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002940 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002941}
2942
Richard Smith86024012012-02-18 22:04:06 +00002943bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2944 if (!Visit(E->getSubExpr()))
2945 return false;
2946 // __real is a no-op on scalar lvalues.
2947 if (E->getSubExpr()->getType()->isAnyComplexType())
2948 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
2949 return true;
2950}
2951
2952bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
2953 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
2954 "lvalue __imag__ on scalar?");
2955 if (!Visit(E->getSubExpr()))
2956 return false;
2957 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
2958 return true;
2959}
2960
Eli Friedman4efaa272008-11-12 09:44:48 +00002961//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002962// Pointer Evaluation
2963//===----------------------------------------------------------------------===//
2964
Anders Carlssonc754aa62008-07-08 05:13:58 +00002965namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002966class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002967 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002968 LValue &Result;
2969
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002970 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002971 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002972 return true;
2973 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002974public:
Mike Stump1eb44332009-09-09 15:08:12 +00002975
John McCallefdb83e2010-05-07 21:00:08 +00002976 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002977 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002978
Richard Smith1aa0be82012-03-03 22:46:17 +00002979 bool Success(const APValue &V, const Expr *E) {
2980 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002981 return true;
2982 }
Richard Smith51201882011-12-30 21:15:51 +00002983 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002984 return Success((Expr*)0);
2985 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002986
John McCallefdb83e2010-05-07 21:00:08 +00002987 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002988 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002989 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002990 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002991 { return Success(E); }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002992 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002993 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002994 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002995 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002996 bool VisitCallExpr(const CallExpr *E);
2997 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002998 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002999 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003000 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003001 }
Richard Smith180f4792011-11-10 06:34:14 +00003002 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3003 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003004 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003005 Result = *Info.CurrentCall->This;
3006 return true;
3007 }
John McCall56ca35d2011-02-17 10:25:35 +00003008
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003009 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003010};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003011} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003012
John McCallefdb83e2010-05-07 21:00:08 +00003013static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003014 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003015 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003016}
3017
John McCallefdb83e2010-05-07 21:00:08 +00003018bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003019 if (E->getOpcode() != BO_Add &&
3020 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003021 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003022
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003023 const Expr *PExp = E->getLHS();
3024 const Expr *IExp = E->getRHS();
3025 if (IExp->getType()->isPointerType())
3026 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003027
Richard Smith745f5142012-01-27 01:14:48 +00003028 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3029 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003030 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003031
John McCallefdb83e2010-05-07 21:00:08 +00003032 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003033 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003034 return false;
3035 int64_t AdditionalOffset
3036 = Offset.isSigned() ? Offset.getSExtValue()
3037 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003038 if (E->getOpcode() == BO_Sub)
3039 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003040
Ted Kremenek890f0f12012-08-23 20:46:57 +00003041 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003042 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3043 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003044}
Eli Friedman4efaa272008-11-12 09:44:48 +00003045
John McCallefdb83e2010-05-07 21:00:08 +00003046bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3047 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003048}
Mike Stump1eb44332009-09-09 15:08:12 +00003049
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003050bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3051 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003052
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003053 switch (E->getCastKind()) {
3054 default:
3055 break;
3056
John McCall2de56d12010-08-25 11:45:40 +00003057 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003058 case CK_CPointerToObjCPointerCast:
3059 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003060 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003061 if (!Visit(SubExpr))
3062 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003063 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3064 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3065 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003066 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003067 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003068 if (SubExpr->getType()->isVoidPointerType())
3069 CCEDiag(E, diag::note_constexpr_invalid_cast)
3070 << 3 << SubExpr->getType();
3071 else
3072 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3073 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003074 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003075
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003076 case CK_DerivedToBase:
3077 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003078 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003079 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003080 if (!Result.Base && Result.Offset.isZero())
3081 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003082
Richard Smith180f4792011-11-10 06:34:14 +00003083 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003084 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003085 QualType Type =
3086 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003087
Richard Smith180f4792011-11-10 06:34:14 +00003088 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003089 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003090 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3091 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003092 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003093 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003094 }
3095
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003096 return true;
3097 }
3098
Richard Smithe24f5fc2011-11-17 22:56:20 +00003099 case CK_BaseToDerived:
3100 if (!Visit(E->getSubExpr()))
3101 return false;
3102 if (!Result.Base && Result.Offset.isZero())
3103 return true;
3104 return HandleBaseToDerivedCast(Info, E, Result);
3105
Richard Smith47a1eed2011-10-29 20:57:55 +00003106 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003107 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003108 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003109
John McCall2de56d12010-08-25 11:45:40 +00003110 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003111 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3112
Richard Smith1aa0be82012-03-03 22:46:17 +00003113 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003114 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003115 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003116
John McCallefdb83e2010-05-07 21:00:08 +00003117 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003118 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3119 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003120 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003121 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003122 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003123 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003124 return true;
3125 } else {
3126 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003127 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003128 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003129 }
3130 }
John McCall2de56d12010-08-25 11:45:40 +00003131 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003132 if (SubExpr->isGLValue()) {
3133 if (!EvaluateLValue(SubExpr, Result, Info))
3134 return false;
3135 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003136 Result.set(SubExpr, Info.CurrentCall->Index);
3137 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3138 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003139 return false;
3140 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003141 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003142 if (const ConstantArrayType *CAT
3143 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3144 Result.addArray(Info, E, CAT);
3145 else
3146 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003147 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003148
John McCall2de56d12010-08-25 11:45:40 +00003149 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003150 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003151 }
3152
Richard Smithc49bd112011-10-28 17:51:58 +00003153 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003154}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003155
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003156bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003157 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003158 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003159
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003160 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003161}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003162
3163//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003164// Member Pointer Evaluation
3165//===----------------------------------------------------------------------===//
3166
3167namespace {
3168class MemberPointerExprEvaluator
3169 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3170 MemberPtr &Result;
3171
3172 bool Success(const ValueDecl *D) {
3173 Result = MemberPtr(D);
3174 return true;
3175 }
3176public:
3177
3178 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3179 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3180
Richard Smith1aa0be82012-03-03 22:46:17 +00003181 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003182 Result.setFrom(V);
3183 return true;
3184 }
Richard Smith51201882011-12-30 21:15:51 +00003185 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003186 return Success((const ValueDecl*)0);
3187 }
3188
3189 bool VisitCastExpr(const CastExpr *E);
3190 bool VisitUnaryAddrOf(const UnaryOperator *E);
3191};
3192} // end anonymous namespace
3193
3194static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3195 EvalInfo &Info) {
3196 assert(E->isRValue() && E->getType()->isMemberPointerType());
3197 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3198}
3199
3200bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3201 switch (E->getCastKind()) {
3202 default:
3203 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3204
3205 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003206 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003207 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003208
3209 case CK_BaseToDerivedMemberPointer: {
3210 if (!Visit(E->getSubExpr()))
3211 return false;
3212 if (E->path_empty())
3213 return true;
3214 // Base-to-derived member pointer casts store the path in derived-to-base
3215 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3216 // the wrong end of the derived->base arc, so stagger the path by one class.
3217 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3218 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3219 PathI != PathE; ++PathI) {
3220 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3221 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3222 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003223 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003224 }
3225 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3226 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003227 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003228 return true;
3229 }
3230
3231 case CK_DerivedToBaseMemberPointer:
3232 if (!Visit(E->getSubExpr()))
3233 return false;
3234 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3235 PathE = E->path_end(); PathI != PathE; ++PathI) {
3236 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3237 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3238 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003239 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003240 }
3241 return true;
3242 }
3243}
3244
3245bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3246 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3247 // member can be formed.
3248 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3249}
3250
3251//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003252// Record Evaluation
3253//===----------------------------------------------------------------------===//
3254
3255namespace {
3256 class RecordExprEvaluator
3257 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3258 const LValue &This;
3259 APValue &Result;
3260 public:
3261
3262 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3263 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3264
Richard Smith1aa0be82012-03-03 22:46:17 +00003265 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003266 Result = V;
3267 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003268 }
Richard Smith51201882011-12-30 21:15:51 +00003269 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003270
Richard Smith59efe262011-11-11 04:05:33 +00003271 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003272 bool VisitInitListExpr(const InitListExpr *E);
3273 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3274 };
3275}
3276
Richard Smith51201882011-12-30 21:15:51 +00003277/// Perform zero-initialization on an object of non-union class type.
3278/// C++11 [dcl.init]p5:
3279/// To zero-initialize an object or reference of type T means:
3280/// [...]
3281/// -- if T is a (possibly cv-qualified) non-union class type,
3282/// each non-static data member and each base-class subobject is
3283/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003284static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3285 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003286 const LValue &This, APValue &Result) {
3287 assert(!RD->isUnion() && "Expected non-union class type");
3288 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3289 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3290 std::distance(RD->field_begin(), RD->field_end()));
3291
John McCall8d59dee2012-05-01 00:38:49 +00003292 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003293 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3294
3295 if (CD) {
3296 unsigned Index = 0;
3297 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003298 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003299 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3300 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003301 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3302 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003303 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003304 Result.getStructBase(Index)))
3305 return false;
3306 }
3307 }
3308
Richard Smithb4e85ed2012-01-06 16:39:00 +00003309 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3310 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003311 // -- if T is a reference type, no initialization is performed.
David Blaikie262bc182012-04-30 02:36:29 +00003312 if (I->getType()->isReferenceType())
Richard Smith51201882011-12-30 21:15:51 +00003313 continue;
3314
3315 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003316 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003317 return false;
Richard Smith51201882011-12-30 21:15:51 +00003318
David Blaikie262bc182012-04-30 02:36:29 +00003319 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003320 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003321 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003322 return false;
3323 }
3324
3325 return true;
3326}
3327
3328bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3329 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003330 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003331 if (RD->isUnion()) {
3332 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3333 // object's first non-static named data member is zero-initialized
3334 RecordDecl::field_iterator I = RD->field_begin();
3335 if (I == RD->field_end()) {
3336 Result = APValue((const FieldDecl*)0);
3337 return true;
3338 }
3339
3340 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003341 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCall8d59dee2012-05-01 00:38:49 +00003342 return false;
David Blaikie581deb32012-06-06 20:45:41 +00003343 Result = APValue(*I);
David Blaikie262bc182012-04-30 02:36:29 +00003344 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003345 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003346 }
3347
Richard Smithce582fe2012-02-17 00:44:16 +00003348 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003349 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003350 return false;
3351 }
3352
Richard Smithb4e85ed2012-01-06 16:39:00 +00003353 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003354}
3355
Richard Smith59efe262011-11-11 04:05:33 +00003356bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3357 switch (E->getCastKind()) {
3358 default:
3359 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3360
3361 case CK_ConstructorConversion:
3362 return Visit(E->getSubExpr());
3363
3364 case CK_DerivedToBase:
3365 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003366 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003367 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003368 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003369 if (!DerivedObject.isStruct())
3370 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003371
3372 // Derived-to-base rvalue conversion: just slice off the derived part.
3373 APValue *Value = &DerivedObject;
3374 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3375 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3376 PathE = E->path_end(); PathI != PathE; ++PathI) {
3377 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3378 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3379 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3380 RD = Base;
3381 }
3382 Result = *Value;
3383 return true;
3384 }
3385 }
3386}
3387
Richard Smith180f4792011-11-10 06:34:14 +00003388bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003389 // Cannot constant-evaluate std::initializer_list inits.
3390 if (E->initializesStdInitializerList())
3391 return false;
3392
Richard Smith180f4792011-11-10 06:34:14 +00003393 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003394 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00003395 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3396
3397 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003398 const FieldDecl *Field = E->getInitializedFieldInUnion();
3399 Result = APValue(Field);
3400 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003401 return true;
Richard Smithec789162012-01-12 18:54:33 +00003402
3403 // If the initializer list for a union does not contain any elements, the
3404 // first element of the union is value-initialized.
3405 ImplicitValueInitExpr VIE(Field->getType());
3406 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3407
Richard Smith180f4792011-11-10 06:34:14 +00003408 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003409 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3410 return false;
Richard Smith83587db2012-02-15 02:18:13 +00003411 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003412 }
3413
3414 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3415 "initializer list for class with base classes");
3416 Result = APValue(APValue::UninitStruct(), 0,
3417 std::distance(RD->field_begin(), RD->field_end()));
3418 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003419 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003420 for (RecordDecl::field_iterator Field = RD->field_begin(),
3421 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3422 // Anonymous bit-fields are not considered members of the class for
3423 // purposes of aggregate initialization.
3424 if (Field->isUnnamedBitfield())
3425 continue;
3426
3427 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003428
Richard Smith745f5142012-01-27 01:14:48 +00003429 bool HaveInit = ElementNo < E->getNumInits();
3430
3431 // FIXME: Diagnostics here should point to the end of the initializer
3432 // list, not the start.
John McCall8d59dee2012-05-01 00:38:49 +00003433 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie581deb32012-06-06 20:45:41 +00003434 Subobject, *Field, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003435 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003436
3437 // Perform an implicit value-initialization for members beyond the end of
3438 // the initializer list.
3439 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3440
Richard Smith83587db2012-02-15 02:18:13 +00003441 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003442 Result.getStructField(Field->getFieldIndex()),
Richard Smith745f5142012-01-27 01:14:48 +00003443 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3444 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003445 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003446 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003447 }
3448 }
3449
Richard Smith745f5142012-01-27 01:14:48 +00003450 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003451}
3452
3453bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3454 const CXXConstructorDecl *FD = E->getConstructor();
John McCall1de9d7d2012-04-26 18:10:01 +00003455 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3456
Richard Smith51201882011-12-30 21:15:51 +00003457 bool ZeroInit = E->requiresZeroInitialization();
3458 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003459 // If we've already performed zero-initialization, we're already done.
3460 if (!Result.isUninit())
3461 return true;
3462
Richard Smith51201882011-12-30 21:15:51 +00003463 if (ZeroInit)
3464 return ZeroInitialization(E);
3465
Richard Smith61802452011-12-22 02:22:31 +00003466 const CXXRecordDecl *RD = FD->getParent();
3467 if (RD->isUnion())
3468 Result = APValue((FieldDecl*)0);
3469 else
3470 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3471 std::distance(RD->field_begin(), RD->field_end()));
3472 return true;
3473 }
3474
Richard Smith180f4792011-11-10 06:34:14 +00003475 const FunctionDecl *Definition = 0;
3476 FD->getBody(Definition);
3477
Richard Smithc1c5f272011-12-13 06:39:58 +00003478 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3479 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003480
Richard Smith610a60c2012-01-10 04:32:03 +00003481 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003482 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003483 if (const MaterializeTemporaryExpr *ME
3484 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3485 return Visit(ME->GetTemporaryExpr());
3486
Richard Smith51201882011-12-30 21:15:51 +00003487 if (ZeroInit && !ZeroInitialization(E))
3488 return false;
3489
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003490 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003491 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003492 cast<CXXConstructorDecl>(Definition), Info,
3493 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003494}
3495
3496static bool EvaluateRecord(const Expr *E, const LValue &This,
3497 APValue &Result, EvalInfo &Info) {
3498 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003499 "can't evaluate expression as a record rvalue");
3500 return RecordExprEvaluator(Info, This, Result).Visit(E);
3501}
3502
3503//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003504// Temporary Evaluation
3505//
3506// Temporaries are represented in the AST as rvalues, but generally behave like
3507// lvalues. The full-object of which the temporary is a subobject is implicitly
3508// materialized so that a reference can bind to it.
3509//===----------------------------------------------------------------------===//
3510namespace {
3511class TemporaryExprEvaluator
3512 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3513public:
3514 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3515 LValueExprEvaluatorBaseTy(Info, Result) {}
3516
3517 /// Visit an expression which constructs the value of this temporary.
3518 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003519 Result.set(E, Info.CurrentCall->Index);
3520 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003521 }
3522
3523 bool VisitCastExpr(const CastExpr *E) {
3524 switch (E->getCastKind()) {
3525 default:
3526 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3527
3528 case CK_ConstructorConversion:
3529 return VisitConstructExpr(E->getSubExpr());
3530 }
3531 }
3532 bool VisitInitListExpr(const InitListExpr *E) {
3533 return VisitConstructExpr(E);
3534 }
3535 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3536 return VisitConstructExpr(E);
3537 }
3538 bool VisitCallExpr(const CallExpr *E) {
3539 return VisitConstructExpr(E);
3540 }
3541};
3542} // end anonymous namespace
3543
3544/// Evaluate an expression of record type as a temporary.
3545static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003546 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003547 return TemporaryExprEvaluator(Info, Result).Visit(E);
3548}
3549
3550//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003551// Vector Evaluation
3552//===----------------------------------------------------------------------===//
3553
3554namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003555 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003556 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3557 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003558 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003559
Richard Smith07fc6572011-10-22 21:10:00 +00003560 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3561 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003562
Richard Smith07fc6572011-10-22 21:10:00 +00003563 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3564 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3565 // FIXME: remove this APValue copy.
3566 Result = APValue(V.data(), V.size());
3567 return true;
3568 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003569 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003570 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003571 Result = V;
3572 return true;
3573 }
Richard Smith51201882011-12-30 21:15:51 +00003574 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003575
Richard Smith07fc6572011-10-22 21:10:00 +00003576 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003577 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003578 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003579 bool VisitInitListExpr(const InitListExpr *E);
3580 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003581 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003582 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003583 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003584 };
3585} // end anonymous namespace
3586
3587static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003588 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003589 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003590}
3591
Richard Smith07fc6572011-10-22 21:10:00 +00003592bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3593 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003594 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003595
Richard Smithd62ca372011-12-06 22:44:34 +00003596 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003597 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003598
Eli Friedman46a52322011-03-25 00:43:55 +00003599 switch (E->getCastKind()) {
3600 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003601 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003602 if (SETy->isIntegerType()) {
3603 APSInt IntResult;
3604 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003605 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003606 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003607 } else if (SETy->isRealFloatingType()) {
3608 APFloat F(0.0);
3609 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003610 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003611 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003612 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003613 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003614 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003615
3616 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003617 SmallVector<APValue, 4> Elts(NElts, Val);
3618 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003619 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003620 case CK_BitCast: {
3621 // Evaluate the operand into an APInt we can extract from.
3622 llvm::APInt SValInt;
3623 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3624 return false;
3625 // Extract the elements
3626 QualType EltTy = VTy->getElementType();
3627 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3628 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3629 SmallVector<APValue, 4> Elts;
3630 if (EltTy->isRealFloatingType()) {
3631 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3632 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3633 unsigned FloatEltSize = EltSize;
3634 if (&Sem == &APFloat::x87DoubleExtended)
3635 FloatEltSize = 80;
3636 for (unsigned i = 0; i < NElts; i++) {
3637 llvm::APInt Elt;
3638 if (BigEndian)
3639 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3640 else
3641 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3642 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3643 }
3644 } else if (EltTy->isIntegerType()) {
3645 for (unsigned i = 0; i < NElts; i++) {
3646 llvm::APInt Elt;
3647 if (BigEndian)
3648 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3649 else
3650 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3651 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3652 }
3653 } else {
3654 return Error(E);
3655 }
3656 return Success(Elts, E);
3657 }
Eli Friedman46a52322011-03-25 00:43:55 +00003658 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003659 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003660 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003661}
3662
Richard Smith07fc6572011-10-22 21:10:00 +00003663bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003664VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003665 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003666 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003667 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003668
Nate Begeman59b5da62009-01-18 03:20:47 +00003669 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003670 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003671
Eli Friedman3edd5a92012-01-03 23:24:20 +00003672 // The number of initializers can be less than the number of
3673 // vector elements. For OpenCL, this can be due to nested vector
3674 // initialization. For GCC compatibility, missing trailing elements
3675 // should be initialized with zeroes.
3676 unsigned CountInits = 0, CountElts = 0;
3677 while (CountElts < NumElements) {
3678 // Handle nested vector initialization.
3679 if (CountInits < NumInits
3680 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3681 APValue v;
3682 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3683 return Error(E);
3684 unsigned vlen = v.getVectorLength();
3685 for (unsigned j = 0; j < vlen; j++)
3686 Elements.push_back(v.getVectorElt(j));
3687 CountElts += vlen;
3688 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003689 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003690 if (CountInits < NumInits) {
3691 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003692 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003693 } else // trailing integer zero.
3694 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3695 Elements.push_back(APValue(sInt));
3696 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003697 } else {
3698 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003699 if (CountInits < NumInits) {
3700 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003701 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003702 } else // trailing float zero.
3703 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3704 Elements.push_back(APValue(f));
3705 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003706 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003707 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003708 }
Richard Smith07fc6572011-10-22 21:10:00 +00003709 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003710}
3711
Richard Smith07fc6572011-10-22 21:10:00 +00003712bool
Richard Smith51201882011-12-30 21:15:51 +00003713VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003714 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003715 QualType EltTy = VT->getElementType();
3716 APValue ZeroElement;
3717 if (EltTy->isIntegerType())
3718 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3719 else
3720 ZeroElement =
3721 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3722
Chris Lattner5f9e2722011-07-23 10:55:15 +00003723 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003724 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003725}
3726
Richard Smith07fc6572011-10-22 21:10:00 +00003727bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003728 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003729 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003730}
3731
Nate Begeman59b5da62009-01-18 03:20:47 +00003732//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003733// Array Evaluation
3734//===----------------------------------------------------------------------===//
3735
3736namespace {
3737 class ArrayExprEvaluator
3738 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003739 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003740 APValue &Result;
3741 public:
3742
Richard Smith180f4792011-11-10 06:34:14 +00003743 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3744 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003745
3746 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003747 assert((V.isArray() || V.isLValue()) &&
3748 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003749 Result = V;
3750 return true;
3751 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003752
Richard Smith51201882011-12-30 21:15:51 +00003753 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003754 const ConstantArrayType *CAT =
3755 Info.Ctx.getAsConstantArrayType(E->getType());
3756 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003757 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003758
3759 Result = APValue(APValue::UninitArray(), 0,
3760 CAT->getSize().getZExtValue());
3761 if (!Result.hasArrayFiller()) return true;
3762
Richard Smith51201882011-12-30 21:15:51 +00003763 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003764 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003765 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003766 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003767 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003768 }
3769
Richard Smithcc5d4f62011-11-07 09:22:26 +00003770 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003771 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003772 };
3773} // end anonymous namespace
3774
Richard Smith180f4792011-11-10 06:34:14 +00003775static bool EvaluateArray(const Expr *E, const LValue &This,
3776 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003777 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003778 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003779}
3780
3781bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3782 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3783 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003784 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003785
Richard Smith974c5f92011-12-22 01:07:19 +00003786 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3787 // an appropriately-typed string literal enclosed in braces.
Richard Smithfe587202012-04-15 02:50:59 +00003788 if (E->isStringLiteralInit()) {
Richard Smith974c5f92011-12-22 01:07:19 +00003789 LValue LV;
3790 if (!EvaluateLValue(E->getInit(0), LV, Info))
3791 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003792 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003793 LV.moveInto(Val);
3794 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003795 }
3796
Richard Smith745f5142012-01-27 01:14:48 +00003797 bool Success = true;
3798
Richard Smithde31aa72012-07-07 22:48:24 +00003799 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
3800 "zero-initialized array shouldn't have any initialized elts");
3801 APValue Filler;
3802 if (Result.isArray() && Result.hasArrayFiller())
3803 Filler = Result.getArrayFiller();
3804
Richard Smithcc5d4f62011-11-07 09:22:26 +00003805 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3806 CAT->getSize().getZExtValue());
Richard Smithde31aa72012-07-07 22:48:24 +00003807
3808 // If the array was previously zero-initialized, preserve the
3809 // zero-initialized values.
3810 if (!Filler.isUninit()) {
3811 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
3812 Result.getArrayInitializedElt(I) = Filler;
3813 if (Result.hasArrayFiller())
3814 Result.getArrayFiller() = Filler;
3815 }
3816
Richard Smith180f4792011-11-10 06:34:14 +00003817 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003818 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003819 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003820 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003821 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003822 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3823 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003824 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3825 CAT->getElementType(), 1)) {
3826 if (!Info.keepEvaluatingAfterFailure())
3827 return false;
3828 Success = false;
3829 }
Richard Smith180f4792011-11-10 06:34:14 +00003830 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003831
Richard Smith745f5142012-01-27 01:14:48 +00003832 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003833 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003834 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3835 // but sometimes does:
3836 // struct S { constexpr S() : p(&p) {} void *p; };
3837 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003838 return EvaluateInPlace(Result.getArrayFiller(), Info,
3839 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003840}
3841
Richard Smithe24f5fc2011-11-17 22:56:20 +00003842bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smithde31aa72012-07-07 22:48:24 +00003843 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3844 // but sometimes does:
3845 // struct S { constexpr S() : p(&p) {} void *p; };
3846 // S s[10];
3847 LValue Subobject = This;
3848
3849 APValue *Value = &Result;
3850 bool HadZeroInit = true;
Richard Smitha4334df2012-07-10 22:12:55 +00003851 QualType ElemTy = E->getType();
3852 while (const ConstantArrayType *CAT =
3853 Info.Ctx.getAsConstantArrayType(ElemTy)) {
Richard Smithde31aa72012-07-07 22:48:24 +00003854 Subobject.addArray(Info, E, CAT);
3855 HadZeroInit &= !Value->isUninit();
3856 if (!HadZeroInit)
3857 *Value = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3858 if (!Value->hasArrayFiller())
3859 return true;
Richard Smithde31aa72012-07-07 22:48:24 +00003860 Value = &Value->getArrayFiller();
Richard Smitha4334df2012-07-10 22:12:55 +00003861 ElemTy = CAT->getElementType();
Richard Smithde31aa72012-07-07 22:48:24 +00003862 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00003863
Richard Smitha4334df2012-07-10 22:12:55 +00003864 if (!ElemTy->isRecordType())
3865 return Error(E);
3866
Richard Smithe24f5fc2011-11-17 22:56:20 +00003867 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003868
Richard Smith51201882011-12-30 21:15:51 +00003869 bool ZeroInit = E->requiresZeroInitialization();
3870 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003871 if (HadZeroInit)
3872 return true;
3873
Richard Smith51201882011-12-30 21:15:51 +00003874 if (ZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003875 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003876 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003877 }
3878
Richard Smith61802452011-12-22 02:22:31 +00003879 const CXXRecordDecl *RD = FD->getParent();
3880 if (RD->isUnion())
Richard Smithde31aa72012-07-07 22:48:24 +00003881 *Value = APValue((FieldDecl*)0);
Richard Smith61802452011-12-22 02:22:31 +00003882 else
Richard Smithde31aa72012-07-07 22:48:24 +00003883 *Value =
Richard Smith61802452011-12-22 02:22:31 +00003884 APValue(APValue::UninitStruct(), RD->getNumBases(),
3885 std::distance(RD->field_begin(), RD->field_end()));
3886 return true;
3887 }
3888
Richard Smithe24f5fc2011-11-17 22:56:20 +00003889 const FunctionDecl *Definition = 0;
3890 FD->getBody(Definition);
3891
Richard Smithc1c5f272011-12-13 06:39:58 +00003892 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3893 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003894
Richard Smithec789162012-01-12 18:54:33 +00003895 if (ZeroInit && !HadZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003896 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003897 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003898 return false;
3899 }
3900
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003901 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003902 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003903 cast<CXXConstructorDecl>(Definition),
Richard Smithde31aa72012-07-07 22:48:24 +00003904 Info, *Value);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003905}
3906
Richard Smithcc5d4f62011-11-07 09:22:26 +00003907//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003908// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003909//
3910// As a GNU extension, we support casting pointers to sufficiently-wide integer
3911// types and back in constant folding. Integer values are thus represented
3912// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003913//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003914
3915namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003916class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003917 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003918 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003919public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003920 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003921 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003922
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003923 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003924 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003925 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003926 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003927 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003928 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003929 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003930 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003931 return true;
3932 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003933 bool Success(const llvm::APSInt &SI, const Expr *E) {
3934 return Success(SI, E, Result);
3935 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003936
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003937 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003938 assert(E->getType()->isIntegralOrEnumerationType() &&
3939 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003940 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003941 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003942 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003943 Result.getInt().setIsUnsigned(
3944 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003945 return true;
3946 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003947 bool Success(const llvm::APInt &I, const Expr *E) {
3948 return Success(I, E, Result);
3949 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003950
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003951 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003952 assert(E->getType()->isIntegralOrEnumerationType() &&
3953 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003954 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003955 return true;
3956 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003957 bool Success(uint64_t Value, const Expr *E) {
3958 return Success(Value, E, Result);
3959 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003960
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003961 bool Success(CharUnits Size, const Expr *E) {
3962 return Success(Size.getQuantity(), E);
3963 }
3964
Richard Smith1aa0be82012-03-03 22:46:17 +00003965 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003966 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003967 Result = V;
3968 return true;
3969 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003970 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003971 }
Mike Stump1eb44332009-09-09 15:08:12 +00003972
Richard Smith51201882011-12-30 21:15:51 +00003973 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003974
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003975 //===--------------------------------------------------------------------===//
3976 // Visitor Methods
3977 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003978
Chris Lattner4c4867e2008-07-12 00:38:25 +00003979 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003980 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003981 }
3982 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003983 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003984 }
Eli Friedman04309752009-11-24 05:28:59 +00003985
3986 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3987 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003988 if (CheckReferencedDecl(E, E->getDecl()))
3989 return true;
3990
3991 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003992 }
3993 bool VisitMemberExpr(const MemberExpr *E) {
3994 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003995 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003996 return true;
3997 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003998
3999 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004000 }
4001
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004002 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004003 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004004 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004005 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004006
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004007 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004008 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004009
Anders Carlsson3068d112008-11-16 19:01:22 +00004010 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004011 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004012 }
Mike Stump1eb44332009-09-09 15:08:12 +00004013
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004014 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4015 return Success(E->getValue(), E);
4016 }
4017
Richard Smithf10d9172011-10-11 21:43:33 +00004018 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004019 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004020 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004021 }
4022
Sebastian Redl64b45f72009-01-05 20:52:13 +00004023 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004024 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004025 }
4026
Francois Pichet6ad6f282010-12-07 00:08:36 +00004027 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4028 return Success(E->getValue(), E);
4029 }
4030
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004031 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4032 return Success(E->getValue(), E);
4033 }
4034
John Wiegley21ff2e52011-04-28 00:16:57 +00004035 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4036 return Success(E->getValue(), E);
4037 }
4038
John Wiegley55262202011-04-25 06:54:41 +00004039 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4040 return Success(E->getValue(), E);
4041 }
4042
Eli Friedman722c7172009-02-28 03:59:05 +00004043 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004044 bool VisitUnaryImag(const UnaryOperator *E);
4045
Sebastian Redl295995c2010-09-10 20:55:47 +00004046 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004047 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004048
Chris Lattnerfcee0012008-07-11 21:24:13 +00004049private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004050 CharUnits GetAlignOfExpr(const Expr *E);
4051 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004052 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004053 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004054 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004055};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004056} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004057
Richard Smithc49bd112011-10-28 17:51:58 +00004058/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4059/// produce either the integer value or a pointer.
4060///
4061/// GCC has a heinous extension which folds casts between pointer types and
4062/// pointer-sized integral types. We support this by allowing the evaluation of
4063/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4064/// Some simple arithmetic on such values is supported (they are treated much
4065/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004066static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004067 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004068 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004069 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004070}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004071
Richard Smithf48fdb02011-12-09 22:58:01 +00004072static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004073 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004074 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004075 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004076 if (!Val.isInt()) {
4077 // FIXME: It would be better to produce the diagnostic for casting
4078 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004079 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004080 return false;
4081 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004082 Result = Val.getInt();
4083 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004084}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004085
Richard Smithf48fdb02011-12-09 22:58:01 +00004086/// Check whether the given declaration can be directly converted to an integral
4087/// rvalue. If not, no diagnostic is produced; there are other things we can
4088/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004089bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004090 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004091 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004092 // Check for signedness/width mismatches between E type and ECD value.
4093 bool SameSign = (ECD->getInitVal().isSigned()
4094 == E->getType()->isSignedIntegerOrEnumerationType());
4095 bool SameWidth = (ECD->getInitVal().getBitWidth()
4096 == Info.Ctx.getIntWidth(E->getType()));
4097 if (SameSign && SameWidth)
4098 return Success(ECD->getInitVal(), E);
4099 else {
4100 // Get rid of mismatch (otherwise Success assertions will fail)
4101 // by computing a new value matching the type of E.
4102 llvm::APSInt Val = ECD->getInitVal();
4103 if (!SameSign)
4104 Val.setIsSigned(!ECD->getInitVal().isSigned());
4105 if (!SameWidth)
4106 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4107 return Success(Val, E);
4108 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004109 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004110 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004111}
4112
Chris Lattnera4d55d82008-10-06 06:40:35 +00004113/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4114/// as GCC.
4115static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4116 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004117 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004118 enum gcc_type_class {
4119 no_type_class = -1,
4120 void_type_class, integer_type_class, char_type_class,
4121 enumeral_type_class, boolean_type_class,
4122 pointer_type_class, reference_type_class, offset_type_class,
4123 real_type_class, complex_type_class,
4124 function_type_class, method_type_class,
4125 record_type_class, union_type_class,
4126 array_type_class, string_type_class,
4127 lang_type_class
4128 };
Mike Stump1eb44332009-09-09 15:08:12 +00004129
4130 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004131 // ideal, however it is what gcc does.
4132 if (E->getNumArgs() == 0)
4133 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004134
Chris Lattnera4d55d82008-10-06 06:40:35 +00004135 QualType ArgTy = E->getArg(0)->getType();
4136 if (ArgTy->isVoidType())
4137 return void_type_class;
4138 else if (ArgTy->isEnumeralType())
4139 return enumeral_type_class;
4140 else if (ArgTy->isBooleanType())
4141 return boolean_type_class;
4142 else if (ArgTy->isCharType())
4143 return string_type_class; // gcc doesn't appear to use char_type_class
4144 else if (ArgTy->isIntegerType())
4145 return integer_type_class;
4146 else if (ArgTy->isPointerType())
4147 return pointer_type_class;
4148 else if (ArgTy->isReferenceType())
4149 return reference_type_class;
4150 else if (ArgTy->isRealType())
4151 return real_type_class;
4152 else if (ArgTy->isComplexType())
4153 return complex_type_class;
4154 else if (ArgTy->isFunctionType())
4155 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004156 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004157 return record_type_class;
4158 else if (ArgTy->isUnionType())
4159 return union_type_class;
4160 else if (ArgTy->isArrayType())
4161 return array_type_class;
4162 else if (ArgTy->isUnionType())
4163 return union_type_class;
4164 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004165 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004166}
4167
Richard Smith80d4b552011-12-28 19:48:30 +00004168/// EvaluateBuiltinConstantPForLValue - Determine the result of
4169/// __builtin_constant_p when applied to the given lvalue.
4170///
4171/// An lvalue is only "constant" if it is a pointer or reference to the first
4172/// character of a string literal.
4173template<typename LValue>
4174static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004175 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004176 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4177}
4178
4179/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4180/// GCC as we can manage.
4181static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4182 QualType ArgType = Arg->getType();
4183
4184 // __builtin_constant_p always has one operand. The rules which gcc follows
4185 // are not precisely documented, but are as follows:
4186 //
4187 // - If the operand is of integral, floating, complex or enumeration type,
4188 // and can be folded to a known value of that type, it returns 1.
4189 // - If the operand and can be folded to a pointer to the first character
4190 // of a string literal (or such a pointer cast to an integral type), it
4191 // returns 1.
4192 //
4193 // Otherwise, it returns 0.
4194 //
4195 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4196 // its support for this does not currently work.
4197 if (ArgType->isIntegralOrEnumerationType()) {
4198 Expr::EvalResult Result;
4199 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4200 return false;
4201
4202 APValue &V = Result.Val;
4203 if (V.getKind() == APValue::Int)
4204 return true;
4205
4206 return EvaluateBuiltinConstantPForLValue(V);
4207 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4208 return Arg->isEvaluatable(Ctx);
4209 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4210 LValue LV;
4211 Expr::EvalStatus Status;
4212 EvalInfo Info(Ctx, Status);
4213 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4214 : EvaluatePointer(Arg, LV, Info)) &&
4215 !Status.HasSideEffects)
4216 return EvaluateBuiltinConstantPForLValue(LV);
4217 }
4218
4219 // Anything else isn't considered to be sufficiently constant.
4220 return false;
4221}
4222
John McCall42c8f872010-05-10 23:27:23 +00004223/// Retrieves the "underlying object type" of the given expression,
4224/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004225QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4226 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4227 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004228 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004229 } else if (const Expr *E = B.get<const Expr*>()) {
4230 if (isa<CompoundLiteralExpr>(E))
4231 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004232 }
4233
4234 return QualType();
4235}
4236
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004237bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004238 LValue Base;
Richard Smithc6794852012-05-23 04:13:20 +00004239
4240 {
4241 // The operand of __builtin_object_size is never evaluated for side-effects.
4242 // If there are any, but we can determine the pointed-to object anyway, then
4243 // ignore the side-effects.
4244 SpeculativeEvaluationRAII SpeculativeEval(Info);
4245 if (!EvaluatePointer(E->getArg(0), Base, Info))
4246 return false;
4247 }
John McCall42c8f872010-05-10 23:27:23 +00004248
4249 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004250 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004251
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004252 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004253 if (T.isNull() ||
4254 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004255 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004256 T->isVariablyModifiedType() ||
4257 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004258 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004259
4260 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4261 CharUnits Offset = Base.getLValueOffset();
4262
4263 if (!Offset.isNegative() && Offset <= Size)
4264 Size -= Offset;
4265 else
4266 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004267 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004268}
4269
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004270bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00004271 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004272 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004273 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004274
4275 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004276 if (TryEvaluateBuiltinObjectSize(E))
4277 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004278
Richard Smith8ae4ec22012-08-07 04:16:51 +00004279 // If evaluating the argument has side-effects, we can't determine the size
4280 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4281 // handle all cases where the expression has side-effects.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004282 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004283 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004284 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004285 return Success(0, E);
4286 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004287
Richard Smithc6794852012-05-23 04:13:20 +00004288 // Expression had no side effects, but we couldn't statically determine the
4289 // size of the referenced object.
Richard Smithf48fdb02011-12-09 22:58:01 +00004290 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004291 }
4292
Benjamin Kramerd1900572012-10-06 14:42:22 +00004293 case Builtin::BI__builtin_bswap16:
Richard Smith70d38f32012-09-28 20:20:52 +00004294 case Builtin::BI__builtin_bswap32:
4295 case Builtin::BI__builtin_bswap64: {
4296 APSInt Val;
4297 if (!EvaluateInteger(E->getArg(0), Val, Info))
4298 return false;
4299
4300 return Success(Val.byteSwap(), E);
4301 }
4302
Chris Lattner019f4e82008-10-06 05:28:25 +00004303 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004304 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004305
Richard Smith80d4b552011-12-28 19:48:30 +00004306 case Builtin::BI__builtin_constant_p:
4307 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004308
Chris Lattner21fb98e2009-09-23 06:06:36 +00004309 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004310 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004311 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004312 return Success(Operand, E);
4313 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004314
4315 case Builtin::BI__builtin_expect:
4316 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004317
Douglas Gregor5726d402010-09-10 06:27:15 +00004318 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004319 // A call to strlen is not a constant expression.
Richard Smith80ad52f2013-01-02 11:42:31 +00004320 if (Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004321 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004322 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4323 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004324 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004325 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004326 case Builtin::BI__builtin_strlen:
4327 // As an extension, we support strlen() and __builtin_strlen() as constant
4328 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004329 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004330 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4331 // The string literal may have embedded null characters. Find the first
4332 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004333 StringRef Str = S->getString();
4334 StringRef::size_type Pos = Str.find(0);
4335 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004336 Str = Str.substr(0, Pos);
4337
4338 return Success(Str.size(), E);
4339 }
4340
Richard Smithf48fdb02011-12-09 22:58:01 +00004341 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004342
Richard Smith2c39d712012-04-13 00:45:38 +00004343 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00004344 case Builtin::BI__atomic_is_lock_free:
4345 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00004346 APSInt SizeVal;
4347 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4348 return false;
4349
4350 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4351 // of two less than the maximum inline atomic width, we know it is
4352 // lock-free. If the size isn't a power of two, or greater than the
4353 // maximum alignment where we promote atomics, we know it is not lock-free
4354 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4355 // the answer can only be determined at runtime; for example, 16-byte
4356 // atomics have lock-free implementations on some, but not all,
4357 // x86-64 processors.
4358
4359 // Check power-of-two.
4360 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00004361 if (Size.isPowerOfTwo()) {
4362 // Check against inlining width.
4363 unsigned InlineWidthBits =
4364 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4365 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4366 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4367 Size == CharUnits::One() ||
4368 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4369 Expr::NPC_NeverValueDependent))
4370 // OK, we will inline appropriately-aligned operations of this size,
4371 // and _Atomic(T) is appropriately-aligned.
4372 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004373
Richard Smith2c39d712012-04-13 00:45:38 +00004374 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4375 castAs<PointerType>()->getPointeeType();
4376 if (!PointeeType->isIncompleteType() &&
4377 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4378 // OK, we will inline operations on this object.
4379 return Success(1, E);
4380 }
4381 }
4382 }
Eli Friedman454b57a2011-10-17 21:44:23 +00004383
Richard Smith2c39d712012-04-13 00:45:38 +00004384 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4385 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004386 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004387 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004388}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004389
Richard Smith625b8072011-10-31 01:37:14 +00004390static bool HasSameBase(const LValue &A, const LValue &B) {
4391 if (!A.getLValueBase())
4392 return !B.getLValueBase();
4393 if (!B.getLValueBase())
4394 return false;
4395
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004396 if (A.getLValueBase().getOpaqueValue() !=
4397 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004398 const Decl *ADecl = GetLValueBaseDecl(A);
4399 if (!ADecl)
4400 return false;
4401 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004402 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004403 return false;
4404 }
4405
4406 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004407 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004408}
4409
Richard Smith7b48a292012-02-01 05:53:12 +00004410/// Perform the given integer operation, which is known to need at most BitWidth
4411/// bits, and check for overflow in the original type (if that type was not an
4412/// unsigned type).
4413template<typename Operation>
4414static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4415 const APSInt &LHS, const APSInt &RHS,
4416 unsigned BitWidth, Operation Op) {
4417 if (LHS.isUnsigned())
4418 return Op(LHS, RHS);
4419
4420 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4421 APSInt Result = Value.trunc(LHS.getBitWidth());
4422 if (Result.extend(BitWidth) != Value)
4423 HandleOverflow(Info, E, Value, E->getType());
4424 return Result;
4425}
4426
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004427namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004428
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004429/// \brief Data recursive integer evaluator of certain binary operators.
4430///
4431/// We use a data recursive algorithm for binary operators so that we are able
4432/// to handle extreme cases of chained binary operators without causing stack
4433/// overflow.
4434class DataRecursiveIntBinOpEvaluator {
4435 struct EvalResult {
4436 APValue Val;
4437 bool Failed;
4438
4439 EvalResult() : Failed(false) { }
4440
4441 void swap(EvalResult &RHS) {
4442 Val.swap(RHS.Val);
4443 Failed = RHS.Failed;
4444 RHS.Failed = false;
4445 }
4446 };
4447
4448 struct Job {
4449 const Expr *E;
4450 EvalResult LHSResult; // meaningful only for binary operator expression.
4451 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4452
4453 Job() : StoredInfo(0) { }
4454 void startSpeculativeEval(EvalInfo &Info) {
4455 OldEvalStatus = Info.EvalStatus;
4456 Info.EvalStatus.Diag = 0;
4457 StoredInfo = &Info;
4458 }
4459 ~Job() {
4460 if (StoredInfo) {
4461 StoredInfo->EvalStatus = OldEvalStatus;
4462 }
4463 }
4464 private:
4465 EvalInfo *StoredInfo; // non-null if status changed.
4466 Expr::EvalStatus OldEvalStatus;
4467 };
4468
4469 SmallVector<Job, 16> Queue;
4470
4471 IntExprEvaluator &IntEval;
4472 EvalInfo &Info;
4473 APValue &FinalResult;
4474
4475public:
4476 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4477 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4478
4479 /// \brief True if \param E is a binary operator that we are going to handle
4480 /// data recursively.
4481 /// We handle binary operators that are comma, logical, or that have operands
4482 /// with integral or enumeration type.
4483 static bool shouldEnqueue(const BinaryOperator *E) {
4484 return E->getOpcode() == BO_Comma ||
4485 E->isLogicalOp() ||
4486 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4487 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004488 }
4489
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004490 bool Traverse(const BinaryOperator *E) {
4491 enqueue(E);
4492 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004493 while (!Queue.empty())
4494 process(PrevResult);
4495
4496 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004497
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004498 FinalResult.swap(PrevResult.Val);
4499 return true;
4500 }
4501
4502private:
4503 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4504 return IntEval.Success(Value, E, Result);
4505 }
4506 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4507 return IntEval.Success(Value, E, Result);
4508 }
4509 bool Error(const Expr *E) {
4510 return IntEval.Error(E);
4511 }
4512 bool Error(const Expr *E, diag::kind D) {
4513 return IntEval.Error(E, D);
4514 }
4515
4516 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4517 return Info.CCEDiag(E, D);
4518 }
4519
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004520 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4521 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004522 bool &SuppressRHSDiags);
4523
4524 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4525 const BinaryOperator *E, APValue &Result);
4526
4527 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4528 Result.Failed = !Evaluate(Result.Val, Info, E);
4529 if (Result.Failed)
4530 Result.Val = APValue();
4531 }
4532
Richard Trieub7783052012-03-21 23:30:30 +00004533 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004534
4535 void enqueue(const Expr *E) {
4536 E = E->IgnoreParens();
4537 Queue.resize(Queue.size()+1);
4538 Queue.back().E = E;
4539 Queue.back().Kind = Job::AnyExprKind;
4540 }
4541};
4542
4543}
4544
4545bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004546 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004547 bool &SuppressRHSDiags) {
4548 if (E->getOpcode() == BO_Comma) {
4549 // Ignore LHS but note if we could not evaluate it.
4550 if (LHSResult.Failed)
4551 Info.EvalStatus.HasSideEffects = true;
4552 return true;
4553 }
4554
4555 if (E->isLogicalOp()) {
4556 bool lhsResult;
4557 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004558 // We were able to evaluate the LHS, see if we can get away with not
4559 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004560 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004561 Success(lhsResult, E, LHSResult.Val);
4562 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004563 }
4564 } else {
4565 // Since we weren't able to evaluate the left hand side, it
4566 // must have had side effects.
4567 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004568
4569 // We can't evaluate the LHS; however, sometimes the result
4570 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4571 // Don't ignore RHS and suppress diagnostics from this arm.
4572 SuppressRHSDiags = true;
4573 }
4574
4575 return true;
4576 }
4577
4578 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4579 E->getRHS()->getType()->isIntegralOrEnumerationType());
4580
4581 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004582 return false; // Ignore RHS;
4583
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004584 return true;
4585}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004586
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004587bool DataRecursiveIntBinOpEvaluator::
4588 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4589 const BinaryOperator *E, APValue &Result) {
4590 if (E->getOpcode() == BO_Comma) {
4591 if (RHSResult.Failed)
4592 return false;
4593 Result = RHSResult.Val;
4594 return true;
4595 }
4596
4597 if (E->isLogicalOp()) {
4598 bool lhsResult, rhsResult;
4599 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4600 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4601
4602 if (LHSIsOK) {
4603 if (RHSIsOK) {
4604 if (E->getOpcode() == BO_LOr)
4605 return Success(lhsResult || rhsResult, E, Result);
4606 else
4607 return Success(lhsResult && rhsResult, E, Result);
4608 }
4609 } else {
4610 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004611 // We can't evaluate the LHS; however, sometimes the result
4612 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4613 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004614 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004615 }
4616 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004617
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004618 return false;
4619 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004620
4621 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4622 E->getRHS()->getType()->isIntegralOrEnumerationType());
4623
4624 if (LHSResult.Failed || RHSResult.Failed)
4625 return false;
4626
4627 const APValue &LHSVal = LHSResult.Val;
4628 const APValue &RHSVal = RHSResult.Val;
4629
4630 // Handle cases like (unsigned long)&a + 4.
4631 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4632 Result = LHSVal;
4633 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4634 RHSVal.getInt().getZExtValue());
4635 if (E->getOpcode() == BO_Add)
4636 Result.getLValueOffset() += AdditionalOffset;
4637 else
4638 Result.getLValueOffset() -= AdditionalOffset;
4639 return true;
4640 }
4641
4642 // Handle cases like 4 + (unsigned long)&a
4643 if (E->getOpcode() == BO_Add &&
4644 RHSVal.isLValue() && LHSVal.isInt()) {
4645 Result = RHSVal;
4646 Result.getLValueOffset() += CharUnits::fromQuantity(
4647 LHSVal.getInt().getZExtValue());
4648 return true;
4649 }
4650
4651 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4652 // Handle (intptr_t)&&A - (intptr_t)&&B.
4653 if (!LHSVal.getLValueOffset().isZero() ||
4654 !RHSVal.getLValueOffset().isZero())
4655 return false;
4656 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4657 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4658 if (!LHSExpr || !RHSExpr)
4659 return false;
4660 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4661 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4662 if (!LHSAddrExpr || !RHSAddrExpr)
4663 return false;
4664 // Make sure both labels come from the same function.
4665 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4666 RHSAddrExpr->getLabel()->getDeclContext())
4667 return false;
4668 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4669 return true;
4670 }
4671
4672 // All the following cases expect both operands to be an integer
4673 if (!LHSVal.isInt() || !RHSVal.isInt())
4674 return Error(E);
4675
4676 const APSInt &LHS = LHSVal.getInt();
4677 APSInt RHS = RHSVal.getInt();
4678
4679 switch (E->getOpcode()) {
4680 default:
4681 return Error(E);
4682 case BO_Mul:
4683 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4684 LHS.getBitWidth() * 2,
4685 std::multiplies<APSInt>()), E,
4686 Result);
4687 case BO_Add:
4688 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4689 LHS.getBitWidth() + 1,
4690 std::plus<APSInt>()), E, Result);
4691 case BO_Sub:
4692 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4693 LHS.getBitWidth() + 1,
4694 std::minus<APSInt>()), E, Result);
4695 case BO_And: return Success(LHS & RHS, E, Result);
4696 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4697 case BO_Or: return Success(LHS | RHS, E, Result);
4698 case BO_Div:
4699 case BO_Rem:
4700 if (RHS == 0)
4701 return Error(E, diag::note_expr_divide_by_zero);
4702 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4703 // not actually undefined behavior in C++11 due to a language defect.
4704 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4705 LHS.isSigned() && LHS.isMinSignedValue())
4706 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4707 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4708 Result);
4709 case BO_Shl: {
David Tweed7a834212013-01-07 16:43:27 +00004710 if (Info.getLangOpts().OpenCL)
4711 // OpenCL 6.3j: shift values are effectively % word size of LHS.
4712 RHS &= APSInt(llvm::APInt(LHS.getBitWidth(),
4713 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
4714 RHS.isUnsigned());
4715 else if (RHS.isSigned() && RHS.isNegative()) {
4716 // During constant-folding, a negative shift is an opposite shift. Such
4717 // a shift is not a constant expression.
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004718 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4719 RHS = -RHS;
4720 goto shift_right;
4721 }
4722
4723 shift_left:
4724 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4725 // the shifted type.
4726 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4727 if (SA != RHS) {
4728 CCEDiag(E, diag::note_constexpr_large_shift)
4729 << RHS << E->getType() << LHS.getBitWidth();
4730 } else if (LHS.isSigned()) {
4731 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4732 // operand, and must not overflow the corresponding unsigned type.
4733 if (LHS.isNegative())
4734 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4735 else if (LHS.countLeadingZeros() < SA)
4736 CCEDiag(E, diag::note_constexpr_lshift_discards);
4737 }
4738
4739 return Success(LHS << SA, E, Result);
4740 }
4741 case BO_Shr: {
David Tweed7a834212013-01-07 16:43:27 +00004742 if (Info.getLangOpts().OpenCL)
4743 // OpenCL 6.3j: shift values are effectively % word size of LHS.
4744 RHS &= APSInt(llvm::APInt(LHS.getBitWidth(),
4745 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
4746 RHS.isUnsigned());
4747 else if (RHS.isSigned() && RHS.isNegative()) {
4748 // During constant-folding, a negative shift is an opposite shift. Such a
4749 // shift is not a constant expression.
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004750 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4751 RHS = -RHS;
4752 goto shift_left;
4753 }
4754
4755 shift_right:
4756 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4757 // shifted type.
4758 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4759 if (SA != RHS)
4760 CCEDiag(E, diag::note_constexpr_large_shift)
4761 << RHS << E->getType() << LHS.getBitWidth();
4762
4763 return Success(LHS >> SA, E, Result);
4764 }
4765
4766 case BO_LT: return Success(LHS < RHS, E, Result);
4767 case BO_GT: return Success(LHS > RHS, E, Result);
4768 case BO_LE: return Success(LHS <= RHS, E, Result);
4769 case BO_GE: return Success(LHS >= RHS, E, Result);
4770 case BO_EQ: return Success(LHS == RHS, E, Result);
4771 case BO_NE: return Success(LHS != RHS, E, Result);
4772 }
4773}
4774
Richard Trieub7783052012-03-21 23:30:30 +00004775void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004776 Job &job = Queue.back();
4777
4778 switch (job.Kind) {
4779 case Job::AnyExprKind: {
4780 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4781 if (shouldEnqueue(Bop)) {
4782 job.Kind = Job::BinOpKind;
4783 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004784 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004785 }
4786 }
4787
4788 EvaluateExpr(job.E, Result);
4789 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004790 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004791 }
4792
4793 case Job::BinOpKind: {
4794 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004795 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004796 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004797 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004798 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004799 }
4800 if (SuppressRHSDiags)
4801 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004802 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004803 job.Kind = Job::BinOpVisitedLHSKind;
4804 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004805 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004806 }
4807
4808 case Job::BinOpVisitedLHSKind: {
4809 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4810 EvalResult RHS;
4811 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004812 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004813 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004814 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004815 }
4816 }
4817
4818 llvm_unreachable("Invalid Job::Kind!");
4819}
4820
4821bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4822 if (E->isAssignmentOp())
4823 return Error(E);
4824
4825 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4826 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004827
Anders Carlsson286f85e2008-11-16 07:17:21 +00004828 QualType LHSTy = E->getLHS()->getType();
4829 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004830
4831 if (LHSTy->isAnyComplexType()) {
4832 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004833 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004834
Richard Smith745f5142012-01-27 01:14:48 +00004835 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4836 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004837 return false;
4838
Richard Smith745f5142012-01-27 01:14:48 +00004839 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004840 return false;
4841
4842 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004843 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004844 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004845 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004846 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4847
John McCall2de56d12010-08-25 11:45:40 +00004848 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004849 return Success((CR_r == APFloat::cmpEqual &&
4850 CR_i == APFloat::cmpEqual), E);
4851 else {
John McCall2de56d12010-08-25 11:45:40 +00004852 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004853 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004854 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004855 CR_r == APFloat::cmpLessThan ||
4856 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004857 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004858 CR_i == APFloat::cmpLessThan ||
4859 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004860 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004861 } else {
John McCall2de56d12010-08-25 11:45:40 +00004862 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004863 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4864 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4865 else {
John McCall2de56d12010-08-25 11:45:40 +00004866 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004867 "Invalid compex comparison.");
4868 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4869 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4870 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004871 }
4872 }
Mike Stump1eb44332009-09-09 15:08:12 +00004873
Anders Carlsson286f85e2008-11-16 07:17:21 +00004874 if (LHSTy->isRealFloatingType() &&
4875 RHSTy->isRealFloatingType()) {
4876 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004877
Richard Smith745f5142012-01-27 01:14:48 +00004878 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4879 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004880 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004881
Richard Smith745f5142012-01-27 01:14:48 +00004882 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004883 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004884
Anders Carlsson286f85e2008-11-16 07:17:21 +00004885 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004886
Anders Carlsson286f85e2008-11-16 07:17:21 +00004887 switch (E->getOpcode()) {
4888 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004889 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004890 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004891 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004892 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004893 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004894 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004895 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004896 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004897 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004898 E);
John McCall2de56d12010-08-25 11:45:40 +00004899 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004900 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004901 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004902 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004903 || CR == APFloat::cmpLessThan
4904 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004905 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004906 }
Mike Stump1eb44332009-09-09 15:08:12 +00004907
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004908 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004909 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004910 LValue LHSValue, RHSValue;
4911
4912 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4913 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004914 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004915
Richard Smith745f5142012-01-27 01:14:48 +00004916 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004917 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004918
Richard Smith625b8072011-10-31 01:37:14 +00004919 // Reject differing bases from the normal codepath; we special-case
4920 // comparisons to null.
4921 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004922 if (E->getOpcode() == BO_Sub) {
4923 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004924 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4925 return false;
4926 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramer7b2f93c2012-10-03 14:15:39 +00004927 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedman65639282012-01-04 23:13:47 +00004928 if (!LHSExpr || !RHSExpr)
4929 return false;
4930 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4931 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4932 if (!LHSAddrExpr || !RHSAddrExpr)
4933 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004934 // Make sure both labels come from the same function.
4935 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4936 RHSAddrExpr->getLabel()->getDeclContext())
4937 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004938 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004939 return true;
4940 }
Richard Smith9e36b532011-10-31 05:11:32 +00004941 // Inequalities and subtractions between unrelated pointers have
4942 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004943 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004944 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004945 // A constant address may compare equal to the address of a symbol.
4946 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004947 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004948 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4949 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004950 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004951 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004952 // distinct addresses. In clang, the result of such a comparison is
4953 // unspecified, so it is not a constant expression. However, we do know
4954 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004955 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4956 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004957 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004958 // We can't tell whether weak symbols will end up pointing to the same
4959 // object.
4960 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004961 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004962 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004963 // (Note that clang defaults to -fmerge-all-constants, which can
4964 // lead to inconsistent results for comparisons involving the address
4965 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004966 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004967 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004968
Richard Smith15efc4d2012-02-01 08:10:20 +00004969 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4970 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4971
Richard Smithf15fda02012-02-02 01:16:57 +00004972 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4973 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4974
John McCall2de56d12010-08-25 11:45:40 +00004975 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004976 // C++11 [expr.add]p6:
4977 // Unless both pointers point to elements of the same array object, or
4978 // one past the last element of the array object, the behavior is
4979 // undefined.
4980 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4981 !AreElementsOfSameArray(getType(LHSValue.Base),
4982 LHSDesignator, RHSDesignator))
4983 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4984
Chris Lattner4992bdd2010-04-20 17:13:14 +00004985 QualType Type = E->getLHS()->getType();
4986 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004987
Richard Smith180f4792011-11-10 06:34:14 +00004988 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004989 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004990 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004991
Richard Smith15efc4d2012-02-01 08:10:20 +00004992 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4993 // and produce incorrect results when it overflows. Such behavior
4994 // appears to be non-conforming, but is common, so perhaps we should
4995 // assume the standard intended for such cases to be undefined behavior
4996 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004997
Richard Smith15efc4d2012-02-01 08:10:20 +00004998 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4999 // overflow in the final conversion to ptrdiff_t.
5000 APSInt LHS(
5001 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5002 APSInt RHS(
5003 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5004 APSInt ElemSize(
5005 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5006 APSInt TrueResult = (LHS - RHS) / ElemSize;
5007 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5008
5009 if (Result.extend(65) != TrueResult)
5010 HandleOverflow(Info, E, TrueResult, E->getType());
5011 return Success(Result, E);
5012 }
Richard Smith82f28582012-01-31 06:41:30 +00005013
5014 // C++11 [expr.rel]p3:
5015 // Pointers to void (after pointer conversions) can be compared, with a
5016 // result defined as follows: If both pointers represent the same
5017 // address or are both the null pointer value, the result is true if the
5018 // operator is <= or >= and false otherwise; otherwise the result is
5019 // unspecified.
5020 // We interpret this as applying to pointers to *cv* void.
5021 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005022 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005023 CCEDiag(E, diag::note_constexpr_void_comparison);
5024
Richard Smithf15fda02012-02-02 01:16:57 +00005025 // C++11 [expr.rel]p2:
5026 // - If two pointers point to non-static data members of the same object,
5027 // or to subobjects or array elements fo such members, recursively, the
5028 // pointer to the later declared member compares greater provided the
5029 // two members have the same access control and provided their class is
5030 // not a union.
5031 // [...]
5032 // - Otherwise pointer comparisons are unspecified.
5033 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5034 E->isRelationalOp()) {
5035 bool WasArrayIndex;
5036 unsigned Mismatch =
5037 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5038 RHSDesignator, WasArrayIndex);
5039 // At the point where the designators diverge, the comparison has a
5040 // specified value if:
5041 // - we are comparing array indices
5042 // - we are comparing fields of a union, or fields with the same access
5043 // Otherwise, the result is unspecified and thus the comparison is not a
5044 // constant expression.
5045 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5046 Mismatch < RHSDesignator.Entries.size()) {
5047 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5048 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5049 if (!LF && !RF)
5050 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5051 else if (!LF)
5052 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5053 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5054 << RF->getParent() << RF;
5055 else if (!RF)
5056 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5057 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5058 << LF->getParent() << LF;
5059 else if (!LF->getParent()->isUnion() &&
5060 LF->getAccess() != RF->getAccess())
5061 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5062 << LF << LF->getAccess() << RF << RF->getAccess()
5063 << LF->getParent();
5064 }
5065 }
5066
Eli Friedmana3169882012-04-16 04:30:08 +00005067 // The comparison here must be unsigned, and performed with the same
5068 // width as the pointer.
Eli Friedmana3169882012-04-16 04:30:08 +00005069 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5070 uint64_t CompareLHS = LHSOffset.getQuantity();
5071 uint64_t CompareRHS = RHSOffset.getQuantity();
5072 assert(PtrSize <= 64 && "Unexpected pointer width");
5073 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5074 CompareLHS &= Mask;
5075 CompareRHS &= Mask;
5076
Eli Friedman28503762012-04-16 19:23:57 +00005077 // If there is a base and this is a relational operator, we can only
5078 // compare pointers within the object in question; otherwise, the result
5079 // depends on where the object is located in memory.
5080 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5081 QualType BaseTy = getType(LHSValue.Base);
5082 if (BaseTy->isIncompleteType())
5083 return Error(E);
5084 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5085 uint64_t OffsetLimit = Size.getQuantity();
5086 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5087 return Error(E);
5088 }
5089
Richard Smith625b8072011-10-31 01:37:14 +00005090 switch (E->getOpcode()) {
5091 default: llvm_unreachable("missing comparison operator");
Eli Friedmana3169882012-04-16 04:30:08 +00005092 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5093 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5094 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5095 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5096 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5097 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005098 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005099 }
5100 }
Richard Smithb02e4622012-02-01 01:42:44 +00005101
5102 if (LHSTy->isMemberPointerType()) {
5103 assert(E->isEqualityOp() && "unexpected member pointer operation");
5104 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5105
5106 MemberPtr LHSValue, RHSValue;
5107
5108 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5109 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5110 return false;
5111
5112 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5113 return false;
5114
5115 // C++11 [expr.eq]p2:
5116 // If both operands are null, they compare equal. Otherwise if only one is
5117 // null, they compare unequal.
5118 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5119 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5120 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5121 }
5122
5123 // Otherwise if either is a pointer to a virtual member function, the
5124 // result is unspecified.
5125 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5126 if (MD->isVirtual())
5127 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5128 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5129 if (MD->isVirtual())
5130 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5131
5132 // Otherwise they compare equal if and only if they would refer to the
5133 // same member of the same most derived object or the same subobject if
5134 // they were dereferenced with a hypothetical object of the associated
5135 // class type.
5136 bool Equal = LHSValue == RHSValue;
5137 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5138 }
5139
Richard Smith26f2cac2012-02-14 22:35:28 +00005140 if (LHSTy->isNullPtrType()) {
5141 assert(E->isComparisonOp() && "unexpected nullptr operation");
5142 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5143 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5144 // are compared, the result is true of the operator is <=, >= or ==, and
5145 // false otherwise.
5146 BinaryOperator::Opcode Opcode = E->getOpcode();
5147 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5148 }
5149
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005150 assert((!LHSTy->isIntegralOrEnumerationType() ||
5151 !RHSTy->isIntegralOrEnumerationType()) &&
5152 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5153 // We can't continue from here for non-integral types.
5154 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005155}
5156
Ken Dyck8b752f12010-01-27 17:10:57 +00005157CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005158 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5159 // result shall be the alignment of the referenced type."
5160 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5161 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005162
5163 // __alignof is defined to return the preferred alignment.
5164 return Info.Ctx.toCharUnitsFromBits(
5165 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005166}
5167
Ken Dyck8b752f12010-01-27 17:10:57 +00005168CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005169 E = E->IgnoreParens();
5170
5171 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005172 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005173 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005174 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5175 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005176
Chris Lattneraf707ab2009-01-24 21:53:27 +00005177 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005178 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5179 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005180
Chris Lattnere9feb472009-01-24 21:09:06 +00005181 return GetAlignOfType(E->getType());
5182}
5183
5184
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005185/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5186/// a result as the expression's type.
5187bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5188 const UnaryExprOrTypeTraitExpr *E) {
5189 switch(E->getKind()) {
5190 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005191 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005192 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005193 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005194 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005195 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005196
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005197 case UETT_VecStep: {
5198 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005199
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005200 if (Ty->isVectorType()) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00005201 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005202
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005203 // The vec_step built-in functions that take a 3-component
5204 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5205 if (n == 3)
5206 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005207
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005208 return Success(n, E);
5209 } else
5210 return Success(1, E);
5211 }
5212
5213 case UETT_SizeOf: {
5214 QualType SrcTy = E->getTypeOfArgument();
5215 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5216 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005217 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5218 SrcTy = Ref->getPointeeType();
5219
Richard Smith180f4792011-11-10 06:34:14 +00005220 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005221 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005222 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005223 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005224 }
5225 }
5226
5227 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005228}
5229
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005230bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005231 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005232 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005233 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005234 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005235 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005236 for (unsigned i = 0; i != n; ++i) {
5237 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5238 switch (ON.getKind()) {
5239 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005240 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005241 APSInt IdxResult;
5242 if (!EvaluateInteger(Idx, IdxResult, Info))
5243 return false;
5244 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5245 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005246 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005247 CurrentType = AT->getElementType();
5248 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5249 Result += IdxResult.getSExtValue() * ElementSize;
5250 break;
5251 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005252
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005253 case OffsetOfExpr::OffsetOfNode::Field: {
5254 FieldDecl *MemberDecl = ON.getField();
5255 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005256 if (!RT)
5257 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005258 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005259 if (RD->isInvalidDecl()) return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005260 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005261 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005262 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005263 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005264 CurrentType = MemberDecl->getType().getNonReferenceType();
5265 break;
5266 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005267
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005268 case OffsetOfExpr::OffsetOfNode::Identifier:
5269 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005270
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005271 case OffsetOfExpr::OffsetOfNode::Base: {
5272 CXXBaseSpecifier *BaseSpec = ON.getBase();
5273 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005274 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005275
5276 // Find the layout of the class whose base we are looking into.
5277 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005278 if (!RT)
5279 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005280 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005281 if (RD->isInvalidDecl()) return false;
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005282 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5283
5284 // Find the base class itself.
5285 CurrentType = BaseSpec->getType();
5286 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5287 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005288 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005289
5290 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005291 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005292 break;
5293 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005294 }
5295 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005296 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005297}
5298
Chris Lattnerb542afe2008-07-11 19:10:17 +00005299bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005300 switch (E->getOpcode()) {
5301 default:
5302 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5303 // See C99 6.6p3.
5304 return Error(E);
5305 case UO_Extension:
5306 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5307 // If so, we could clear the diagnostic ID.
5308 return Visit(E->getSubExpr());
5309 case UO_Plus:
5310 // The result is just the value.
5311 return Visit(E->getSubExpr());
5312 case UO_Minus: {
5313 if (!Visit(E->getSubExpr()))
5314 return false;
5315 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005316 const APSInt &Value = Result.getInt();
5317 if (Value.isSigned() && Value.isMinSignedValue())
5318 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5319 E->getType());
5320 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005321 }
5322 case UO_Not: {
5323 if (!Visit(E->getSubExpr()))
5324 return false;
5325 if (!Result.isInt()) return Error(E);
5326 return Success(~Result.getInt(), E);
5327 }
5328 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005329 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005330 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005331 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005332 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005333 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005334 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005335}
Mike Stump1eb44332009-09-09 15:08:12 +00005336
Chris Lattner732b2232008-07-12 01:15:53 +00005337/// HandleCast - This is used to evaluate implicit or explicit casts where the
5338/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005339bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5340 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005341 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005342 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005343
Eli Friedman46a52322011-03-25 00:43:55 +00005344 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005345 case CK_BaseToDerived:
5346 case CK_DerivedToBase:
5347 case CK_UncheckedDerivedToBase:
5348 case CK_Dynamic:
5349 case CK_ToUnion:
5350 case CK_ArrayToPointerDecay:
5351 case CK_FunctionToPointerDecay:
5352 case CK_NullToPointer:
5353 case CK_NullToMemberPointer:
5354 case CK_BaseToDerivedMemberPointer:
5355 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005356 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005357 case CK_ConstructorConversion:
5358 case CK_IntegralToPointer:
5359 case CK_ToVoid:
5360 case CK_VectorSplat:
5361 case CK_IntegralToFloating:
5362 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005363 case CK_CPointerToObjCPointerCast:
5364 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005365 case CK_AnyPointerToBlockPointerCast:
5366 case CK_ObjCObjectLValueCast:
5367 case CK_FloatingRealToComplex:
5368 case CK_FloatingComplexToReal:
5369 case CK_FloatingComplexCast:
5370 case CK_FloatingComplexToIntegralComplex:
5371 case CK_IntegralRealToComplex:
5372 case CK_IntegralComplexCast:
5373 case CK_IntegralComplexToFloatingComplex:
Eli Friedmana6c66ce2012-08-31 00:14:07 +00005374 case CK_BuiltinFnToFnPtr:
Eli Friedman46a52322011-03-25 00:43:55 +00005375 llvm_unreachable("invalid cast kind for integral value");
5376
Eli Friedmane50c2972011-03-25 19:07:11 +00005377 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005378 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005379 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005380 case CK_ARCProduceObject:
5381 case CK_ARCConsumeObject:
5382 case CK_ARCReclaimReturnedObject:
5383 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005384 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005385 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005386
Richard Smith7d580a42012-01-17 21:17:26 +00005387 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005388 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005389 case CK_AtomicToNonAtomic:
5390 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005391 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005392 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005393
5394 case CK_MemberPointerToBoolean:
5395 case CK_PointerToBoolean:
5396 case CK_IntegralToBoolean:
5397 case CK_FloatingToBoolean:
5398 case CK_FloatingComplexToBoolean:
5399 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005400 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005401 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005402 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005403 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005404 }
5405
Eli Friedman46a52322011-03-25 00:43:55 +00005406 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005407 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005408 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005409
Eli Friedmanbe265702009-02-20 01:15:07 +00005410 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005411 // Allow casts of address-of-label differences if they are no-ops
5412 // or narrowing. (The narrowing case isn't actually guaranteed to
5413 // be constant-evaluatable except in some narrow cases which are hard
5414 // to detect here. We let it through on the assumption the user knows
5415 // what they are doing.)
5416 if (Result.isAddrLabelDiff())
5417 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005418 // Only allow casts of lvalues if they are lossless.
5419 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5420 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005421
Richard Smithf72fccf2012-01-30 22:27:01 +00005422 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5423 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005424 }
Mike Stump1eb44332009-09-09 15:08:12 +00005425
Eli Friedman46a52322011-03-25 00:43:55 +00005426 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005427 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5428
John McCallefdb83e2010-05-07 21:00:08 +00005429 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005430 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005431 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005432
Daniel Dunbardd211642009-02-19 22:24:01 +00005433 if (LV.getLValueBase()) {
5434 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005435 // FIXME: Allow a larger integer size than the pointer size, and allow
5436 // narrowing back down to pointer width in subsequent integral casts.
5437 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005438 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005439 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005440
Richard Smithb755a9d2011-11-16 07:18:12 +00005441 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005442 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005443 return true;
5444 }
5445
Ken Dycka7305832010-01-15 12:37:54 +00005446 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5447 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005448 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005449 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005450
Eli Friedman46a52322011-03-25 00:43:55 +00005451 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005452 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005453 if (!EvaluateComplex(SubExpr, C, Info))
5454 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005455 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005456 }
Eli Friedman2217c872009-02-22 11:46:18 +00005457
Eli Friedman46a52322011-03-25 00:43:55 +00005458 case CK_FloatingToIntegral: {
5459 APFloat F(0.0);
5460 if (!EvaluateFloat(SubExpr, F, Info))
5461 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005462
Richard Smithc1c5f272011-12-13 06:39:58 +00005463 APSInt Value;
5464 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5465 return false;
5466 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005467 }
5468 }
Mike Stump1eb44332009-09-09 15:08:12 +00005469
Eli Friedman46a52322011-03-25 00:43:55 +00005470 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005471}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005472
Eli Friedman722c7172009-02-28 03:59:05 +00005473bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5474 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005475 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005476 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5477 return false;
5478 if (!LV.isComplexInt())
5479 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005480 return Success(LV.getComplexIntReal(), E);
5481 }
5482
5483 return Visit(E->getSubExpr());
5484}
5485
Eli Friedman664a1042009-02-27 04:45:43 +00005486bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005487 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005488 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005489 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5490 return false;
5491 if (!LV.isComplexInt())
5492 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005493 return Success(LV.getComplexIntImag(), E);
5494 }
5495
Richard Smith8327fad2011-10-24 18:44:57 +00005496 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005497 return Success(0, E);
5498}
5499
Douglas Gregoree8aff02011-01-04 17:33:58 +00005500bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5501 return Success(E->getPackLength(), E);
5502}
5503
Sebastian Redl295995c2010-09-10 20:55:47 +00005504bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5505 return Success(E->getValue(), E);
5506}
5507
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005508//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005509// Float Evaluation
5510//===----------------------------------------------------------------------===//
5511
5512namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005513class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005514 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005515 APFloat &Result;
5516public:
5517 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005518 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005519
Richard Smith1aa0be82012-03-03 22:46:17 +00005520 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005521 Result = V.getFloat();
5522 return true;
5523 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005524
Richard Smith51201882011-12-30 21:15:51 +00005525 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005526 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5527 return true;
5528 }
5529
Chris Lattner019f4e82008-10-06 05:28:25 +00005530 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005531
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005532 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005533 bool VisitBinaryOperator(const BinaryOperator *E);
5534 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005535 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005536
John McCallabd3a852010-05-07 22:08:54 +00005537 bool VisitUnaryReal(const UnaryOperator *E);
5538 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005539
Richard Smith51201882011-12-30 21:15:51 +00005540 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005541};
5542} // end anonymous namespace
5543
5544static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005545 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005546 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005547}
5548
Jay Foad4ba2a172011-01-12 09:06:06 +00005549static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005550 QualType ResultTy,
5551 const Expr *Arg,
5552 bool SNaN,
5553 llvm::APFloat &Result) {
5554 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5555 if (!S) return false;
5556
5557 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5558
5559 llvm::APInt fill;
5560
5561 // Treat empty strings as if they were zero.
5562 if (S->getString().empty())
5563 fill = llvm::APInt(32, 0);
5564 else if (S->getString().getAsInteger(0, fill))
5565 return false;
5566
5567 if (SNaN)
5568 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5569 else
5570 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5571 return true;
5572}
5573
Chris Lattner019f4e82008-10-06 05:28:25 +00005574bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005575 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005576 default:
5577 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5578
Chris Lattner019f4e82008-10-06 05:28:25 +00005579 case Builtin::BI__builtin_huge_val:
5580 case Builtin::BI__builtin_huge_valf:
5581 case Builtin::BI__builtin_huge_vall:
5582 case Builtin::BI__builtin_inf:
5583 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005584 case Builtin::BI__builtin_infl: {
5585 const llvm::fltSemantics &Sem =
5586 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005587 Result = llvm::APFloat::getInf(Sem);
5588 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005589 }
Mike Stump1eb44332009-09-09 15:08:12 +00005590
John McCalldb7b72a2010-02-28 13:00:19 +00005591 case Builtin::BI__builtin_nans:
5592 case Builtin::BI__builtin_nansf:
5593 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005594 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5595 true, Result))
5596 return Error(E);
5597 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005598
Chris Lattner9e621712008-10-06 06:31:58 +00005599 case Builtin::BI__builtin_nan:
5600 case Builtin::BI__builtin_nanf:
5601 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005602 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005603 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005604 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5605 false, Result))
5606 return Error(E);
5607 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005608
5609 case Builtin::BI__builtin_fabs:
5610 case Builtin::BI__builtin_fabsf:
5611 case Builtin::BI__builtin_fabsl:
5612 if (!EvaluateFloat(E->getArg(0), Result, Info))
5613 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005614
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005615 if (Result.isNegative())
5616 Result.changeSign();
5617 return true;
5618
Mike Stump1eb44332009-09-09 15:08:12 +00005619 case Builtin::BI__builtin_copysign:
5620 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005621 case Builtin::BI__builtin_copysignl: {
5622 APFloat RHS(0.);
5623 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5624 !EvaluateFloat(E->getArg(1), RHS, Info))
5625 return false;
5626 Result.copySign(RHS);
5627 return true;
5628 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005629 }
5630}
5631
John McCallabd3a852010-05-07 22:08:54 +00005632bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005633 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5634 ComplexValue CV;
5635 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5636 return false;
5637 Result = CV.FloatReal;
5638 return true;
5639 }
5640
5641 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005642}
5643
5644bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005645 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5646 ComplexValue CV;
5647 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5648 return false;
5649 Result = CV.FloatImag;
5650 return true;
5651 }
5652
Richard Smith8327fad2011-10-24 18:44:57 +00005653 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005654 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5655 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005656 return true;
5657}
5658
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005659bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005660 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005661 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005662 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005663 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005664 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005665 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5666 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005667 Result.changeSign();
5668 return true;
5669 }
5670}
Chris Lattner019f4e82008-10-06 05:28:25 +00005671
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005672bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005673 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5674 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005675
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005676 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005677 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5678 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005679 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005680 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005681 return false;
5682
5683 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005684 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005685 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005686 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005687 break;
John McCall2de56d12010-08-25 11:45:40 +00005688 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005689 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005690 break;
John McCall2de56d12010-08-25 11:45:40 +00005691 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005692 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005693 break;
John McCall2de56d12010-08-25 11:45:40 +00005694 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005695 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005696 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005697 }
Richard Smith7b48a292012-02-01 05:53:12 +00005698
5699 if (Result.isInfinity() || Result.isNaN())
5700 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5701 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005702}
5703
5704bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5705 Result = E->getValue();
5706 return true;
5707}
5708
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005709bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5710 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005711
Eli Friedman2a523ee2011-03-25 00:54:52 +00005712 switch (E->getCastKind()) {
5713 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005714 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005715
5716 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005717 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005718 return EvaluateInteger(SubExpr, IntResult, Info) &&
5719 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5720 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005721 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005722
5723 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005724 if (!Visit(SubExpr))
5725 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005726 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5727 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005728 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005729
Eli Friedman2a523ee2011-03-25 00:54:52 +00005730 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005731 ComplexValue V;
5732 if (!EvaluateComplex(SubExpr, V, Info))
5733 return false;
5734 Result = V.getComplexFloatReal();
5735 return true;
5736 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005737 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005738}
5739
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005740//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005741// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005742//===----------------------------------------------------------------------===//
5743
5744namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005745class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005746 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005747 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005748
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005749public:
John McCallf4cf1a12010-05-07 17:22:02 +00005750 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005751 : ExprEvaluatorBaseTy(info), Result(Result) {}
5752
Richard Smith1aa0be82012-03-03 22:46:17 +00005753 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005754 Result.setFrom(V);
5755 return true;
5756 }
Mike Stump1eb44332009-09-09 15:08:12 +00005757
Eli Friedman7ead5c72012-01-10 04:58:17 +00005758 bool ZeroInitialization(const Expr *E);
5759
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005760 //===--------------------------------------------------------------------===//
5761 // Visitor Methods
5762 //===--------------------------------------------------------------------===//
5763
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005764 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005765 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005766 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005767 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005768 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005769};
5770} // end anonymous namespace
5771
John McCallf4cf1a12010-05-07 17:22:02 +00005772static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5773 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005774 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005775 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005776}
5777
Eli Friedman7ead5c72012-01-10 04:58:17 +00005778bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00005779 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005780 if (ElemTy->isRealFloatingType()) {
5781 Result.makeComplexFloat();
5782 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5783 Result.FloatReal = Zero;
5784 Result.FloatImag = Zero;
5785 } else {
5786 Result.makeComplexInt();
5787 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5788 Result.IntReal = Zero;
5789 Result.IntImag = Zero;
5790 }
5791 return true;
5792}
5793
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005794bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5795 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005796
5797 if (SubExpr->getType()->isRealFloatingType()) {
5798 Result.makeComplexFloat();
5799 APFloat &Imag = Result.FloatImag;
5800 if (!EvaluateFloat(SubExpr, Imag, Info))
5801 return false;
5802
5803 Result.FloatReal = APFloat(Imag.getSemantics());
5804 return true;
5805 } else {
5806 assert(SubExpr->getType()->isIntegerType() &&
5807 "Unexpected imaginary literal.");
5808
5809 Result.makeComplexInt();
5810 APSInt &Imag = Result.IntImag;
5811 if (!EvaluateInteger(SubExpr, Imag, Info))
5812 return false;
5813
5814 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5815 return true;
5816 }
5817}
5818
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005819bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005820
John McCall8786da72010-12-14 17:51:41 +00005821 switch (E->getCastKind()) {
5822 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005823 case CK_BaseToDerived:
5824 case CK_DerivedToBase:
5825 case CK_UncheckedDerivedToBase:
5826 case CK_Dynamic:
5827 case CK_ToUnion:
5828 case CK_ArrayToPointerDecay:
5829 case CK_FunctionToPointerDecay:
5830 case CK_NullToPointer:
5831 case CK_NullToMemberPointer:
5832 case CK_BaseToDerivedMemberPointer:
5833 case CK_DerivedToBaseMemberPointer:
5834 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005835 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005836 case CK_ConstructorConversion:
5837 case CK_IntegralToPointer:
5838 case CK_PointerToIntegral:
5839 case CK_PointerToBoolean:
5840 case CK_ToVoid:
5841 case CK_VectorSplat:
5842 case CK_IntegralCast:
5843 case CK_IntegralToBoolean:
5844 case CK_IntegralToFloating:
5845 case CK_FloatingToIntegral:
5846 case CK_FloatingToBoolean:
5847 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005848 case CK_CPointerToObjCPointerCast:
5849 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005850 case CK_AnyPointerToBlockPointerCast:
5851 case CK_ObjCObjectLValueCast:
5852 case CK_FloatingComplexToReal:
5853 case CK_FloatingComplexToBoolean:
5854 case CK_IntegralComplexToReal:
5855 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005856 case CK_ARCProduceObject:
5857 case CK_ARCConsumeObject:
5858 case CK_ARCReclaimReturnedObject:
5859 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005860 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmana6c66ce2012-08-31 00:14:07 +00005861 case CK_BuiltinFnToFnPtr:
John McCall8786da72010-12-14 17:51:41 +00005862 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005863
John McCall8786da72010-12-14 17:51:41 +00005864 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005865 case CK_AtomicToNonAtomic:
5866 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005867 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005868 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005869
5870 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005871 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005872 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005873 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005874
5875 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005876 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005877 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005878 return false;
5879
John McCall8786da72010-12-14 17:51:41 +00005880 Result.makeComplexFloat();
5881 Result.FloatImag = APFloat(Real.getSemantics());
5882 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005883 }
5884
John McCall8786da72010-12-14 17:51:41 +00005885 case CK_FloatingComplexCast: {
5886 if (!Visit(E->getSubExpr()))
5887 return false;
5888
5889 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5890 QualType From
5891 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5892
Richard Smithc1c5f272011-12-13 06:39:58 +00005893 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5894 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005895 }
5896
5897 case CK_FloatingComplexToIntegralComplex: {
5898 if (!Visit(E->getSubExpr()))
5899 return false;
5900
5901 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5902 QualType From
5903 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5904 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005905 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5906 To, Result.IntReal) &&
5907 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5908 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005909 }
5910
5911 case CK_IntegralRealToComplex: {
5912 APSInt &Real = Result.IntReal;
5913 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5914 return false;
5915
5916 Result.makeComplexInt();
5917 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5918 return true;
5919 }
5920
5921 case CK_IntegralComplexCast: {
5922 if (!Visit(E->getSubExpr()))
5923 return false;
5924
5925 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5926 QualType From
5927 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5928
Richard Smithf72fccf2012-01-30 22:27:01 +00005929 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5930 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005931 return true;
5932 }
5933
5934 case CK_IntegralComplexToFloatingComplex: {
5935 if (!Visit(E->getSubExpr()))
5936 return false;
5937
Ted Kremenek890f0f12012-08-23 20:46:57 +00005938 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005939 QualType From
Ted Kremenek890f0f12012-08-23 20:46:57 +00005940 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005941 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005942 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5943 To, Result.FloatReal) &&
5944 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5945 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005946 }
5947 }
5948
5949 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005950}
5951
John McCallf4cf1a12010-05-07 17:22:02 +00005952bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005953 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005954 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5955
Richard Smith745f5142012-01-27 01:14:48 +00005956 bool LHSOK = Visit(E->getLHS());
5957 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005958 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005959
John McCallf4cf1a12010-05-07 17:22:02 +00005960 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005961 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005962 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005963
Daniel Dunbar3f279872009-01-29 01:32:56 +00005964 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5965 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005966 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005967 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005968 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005969 if (Result.isComplexFloat()) {
5970 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5971 APFloat::rmNearestTiesToEven);
5972 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5973 APFloat::rmNearestTiesToEven);
5974 } else {
5975 Result.getComplexIntReal() += RHS.getComplexIntReal();
5976 Result.getComplexIntImag() += RHS.getComplexIntImag();
5977 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005978 break;
John McCall2de56d12010-08-25 11:45:40 +00005979 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005980 if (Result.isComplexFloat()) {
5981 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5982 APFloat::rmNearestTiesToEven);
5983 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5984 APFloat::rmNearestTiesToEven);
5985 } else {
5986 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5987 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5988 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005989 break;
John McCall2de56d12010-08-25 11:45:40 +00005990 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005991 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005992 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005993 APFloat &LHS_r = LHS.getComplexFloatReal();
5994 APFloat &LHS_i = LHS.getComplexFloatImag();
5995 APFloat &RHS_r = RHS.getComplexFloatReal();
5996 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005997
Daniel Dunbar3f279872009-01-29 01:32:56 +00005998 APFloat Tmp = LHS_r;
5999 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6000 Result.getComplexFloatReal() = Tmp;
6001 Tmp = LHS_i;
6002 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6003 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6004
6005 Tmp = LHS_r;
6006 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6007 Result.getComplexFloatImag() = Tmp;
6008 Tmp = LHS_i;
6009 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6010 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6011 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00006012 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00006013 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006014 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6015 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00006016 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006017 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6018 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6019 }
6020 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006021 case BO_Div:
6022 if (Result.isComplexFloat()) {
6023 ComplexValue LHS = Result;
6024 APFloat &LHS_r = LHS.getComplexFloatReal();
6025 APFloat &LHS_i = LHS.getComplexFloatImag();
6026 APFloat &RHS_r = RHS.getComplexFloatReal();
6027 APFloat &RHS_i = RHS.getComplexFloatImag();
6028 APFloat &Res_r = Result.getComplexFloatReal();
6029 APFloat &Res_i = Result.getComplexFloatImag();
6030
6031 APFloat Den = RHS_r;
6032 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6033 APFloat Tmp = RHS_i;
6034 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6035 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6036
6037 Res_r = LHS_r;
6038 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6039 Tmp = LHS_i;
6040 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6041 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6042 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6043
6044 Res_i = LHS_i;
6045 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6046 Tmp = LHS_r;
6047 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6048 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6049 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6050 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006051 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6052 return Error(E, diag::note_expr_divide_by_zero);
6053
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006054 ComplexValue LHS = Result;
6055 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6056 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6057 Result.getComplexIntReal() =
6058 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6059 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6060 Result.getComplexIntImag() =
6061 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6062 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6063 }
6064 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006065 }
6066
John McCallf4cf1a12010-05-07 17:22:02 +00006067 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006068}
6069
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006070bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6071 // Get the operand value into 'Result'.
6072 if (!Visit(E->getSubExpr()))
6073 return false;
6074
6075 switch (E->getOpcode()) {
6076 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006077 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006078 case UO_Extension:
6079 return true;
6080 case UO_Plus:
6081 // The result is always just the subexpr.
6082 return true;
6083 case UO_Minus:
6084 if (Result.isComplexFloat()) {
6085 Result.getComplexFloatReal().changeSign();
6086 Result.getComplexFloatImag().changeSign();
6087 }
6088 else {
6089 Result.getComplexIntReal() = -Result.getComplexIntReal();
6090 Result.getComplexIntImag() = -Result.getComplexIntImag();
6091 }
6092 return true;
6093 case UO_Not:
6094 if (Result.isComplexFloat())
6095 Result.getComplexFloatImag().changeSign();
6096 else
6097 Result.getComplexIntImag() = -Result.getComplexIntImag();
6098 return true;
6099 }
6100}
6101
Eli Friedman7ead5c72012-01-10 04:58:17 +00006102bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6103 if (E->getNumInits() == 2) {
6104 if (E->getType()->isComplexType()) {
6105 Result.makeComplexFloat();
6106 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6107 return false;
6108 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6109 return false;
6110 } else {
6111 Result.makeComplexInt();
6112 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6113 return false;
6114 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6115 return false;
6116 }
6117 return true;
6118 }
6119 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6120}
6121
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006122//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006123// Void expression evaluation, primarily for a cast to void on the LHS of a
6124// comma operator
6125//===----------------------------------------------------------------------===//
6126
6127namespace {
6128class VoidExprEvaluator
6129 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6130public:
6131 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6132
Richard Smith1aa0be82012-03-03 22:46:17 +00006133 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006134
6135 bool VisitCastExpr(const CastExpr *E) {
6136 switch (E->getCastKind()) {
6137 default:
6138 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6139 case CK_ToVoid:
6140 VisitIgnoredValue(E->getSubExpr());
6141 return true;
6142 }
6143 }
6144};
6145} // end anonymous namespace
6146
6147static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6148 assert(E->isRValue() && E->getType()->isVoidType());
6149 return VoidExprEvaluator(Info).Visit(E);
6150}
6151
6152//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006153// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006154//===----------------------------------------------------------------------===//
6155
Richard Smith1aa0be82012-03-03 22:46:17 +00006156static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006157 // In C, function designators are not lvalues, but we evaluate them as if they
6158 // are.
6159 if (E->isGLValue() || E->getType()->isFunctionType()) {
6160 LValue LV;
6161 if (!EvaluateLValue(E, LV, Info))
6162 return false;
6163 LV.moveInto(Result);
6164 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006165 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006166 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006167 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006168 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006169 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006170 } else if (E->getType()->hasPointerRepresentation()) {
6171 LValue LV;
6172 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006173 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006174 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006175 } else if (E->getType()->isRealFloatingType()) {
6176 llvm::APFloat F(0.0);
6177 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006178 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006179 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006180 } else if (E->getType()->isAnyComplexType()) {
6181 ComplexValue C;
6182 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006183 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006184 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006185 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006186 MemberPtr P;
6187 if (!EvaluateMemberPointer(E, P, Info))
6188 return false;
6189 P.moveInto(Result);
6190 return true;
Richard Smith51201882011-12-30 21:15:51 +00006191 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006192 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006193 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006194 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006195 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006196 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006197 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006198 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006199 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006200 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6201 return false;
6202 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006203 } else if (E->getType()->isVoidType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00006204 if (!Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006205 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006206 << E->getType();
Richard Smithaa9c3502011-12-07 00:43:50 +00006207 if (!EvaluateVoid(E, Info))
6208 return false;
Richard Smith80ad52f2013-01-02 11:42:31 +00006209 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006210 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006211 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006212 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006213 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006214 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006215 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006216
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006217 return true;
6218}
6219
Richard Smith83587db2012-02-15 02:18:13 +00006220/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6221/// cases, the in-place evaluation is essential, since later initializers for
6222/// an object can indirectly refer to subobjects which were initialized earlier.
6223static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6224 const Expr *E, CheckConstantExpressionKind CCEK,
6225 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006226 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006227 return false;
6228
6229 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006230 // Evaluate arrays and record types in-place, so that later initializers can
6231 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006232 if (E->getType()->isArrayType())
6233 return EvaluateArray(E, This, Result, Info);
6234 else if (E->getType()->isRecordType())
6235 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006236 }
6237
6238 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006239 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006240}
6241
Richard Smithf48fdb02011-12-09 22:58:01 +00006242/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6243/// lvalue-to-rvalue cast if it is an lvalue.
6244static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006245 if (!CheckLiteralType(Info, E))
6246 return false;
6247
Richard Smith1aa0be82012-03-03 22:46:17 +00006248 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006249 return false;
6250
6251 if (E->isGLValue()) {
6252 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006253 LV.setFrom(Info.Ctx, Result);
6254 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006255 return false;
6256 }
6257
Richard Smith1aa0be82012-03-03 22:46:17 +00006258 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006259 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006260}
Richard Smithc49bd112011-10-28 17:51:58 +00006261
Richard Smith51f47082011-10-29 00:50:52 +00006262/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006263/// any crazy technique (that has nothing to do with language standards) that
6264/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006265/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6266/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006267bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006268 // Fast-path evaluations of integer literals, since we sometimes see files
6269 // containing vast quantities of these.
6270 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6271 Result.Val = APValue(APSInt(L->getValue(),
6272 L->getType()->isUnsignedIntegerType()));
6273 return true;
6274 }
6275
Richard Smith2d6a5672012-01-14 04:30:29 +00006276 // FIXME: Evaluating values of large array and record types can cause
6277 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006278 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00006279 !Ctx.getLangOpts().CPlusPlus11)
Richard Smith1445bba2011-11-10 03:30:42 +00006280 return false;
6281
Richard Smithf48fdb02011-12-09 22:58:01 +00006282 EvalInfo Info(Ctx, Result);
6283 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006284}
6285
Jay Foad4ba2a172011-01-12 09:06:06 +00006286bool Expr::EvaluateAsBooleanCondition(bool &Result,
6287 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006288 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006289 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006290 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006291}
6292
Richard Smith80d4b552011-12-28 19:48:30 +00006293bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6294 SideEffectsKind AllowSideEffects) const {
6295 if (!getType()->isIntegralOrEnumerationType())
6296 return false;
6297
Richard Smithc49bd112011-10-28 17:51:58 +00006298 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006299 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6300 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006301 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006302
Richard Smithc49bd112011-10-28 17:51:58 +00006303 Result = ExprResult.Val.getInt();
6304 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006305}
6306
Jay Foad4ba2a172011-01-12 09:06:06 +00006307bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006308 EvalInfo Info(Ctx, Result);
6309
John McCallefdb83e2010-05-07 21:00:08 +00006310 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006311 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6312 !CheckLValueConstantExpression(Info, getExprLoc(),
6313 Ctx.getLValueReferenceType(getType()), LV))
6314 return false;
6315
Richard Smith1aa0be82012-03-03 22:46:17 +00006316 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006317 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006318}
6319
Richard Smith099e7f62011-12-19 06:19:21 +00006320bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6321 const VarDecl *VD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006322 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006323 // FIXME: Evaluating initializers for large array and record types can cause
6324 // performance problems. Only do so in C++11 for now.
6325 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00006326 !Ctx.getLangOpts().CPlusPlus11)
Richard Smith2d6a5672012-01-14 04:30:29 +00006327 return false;
6328
Richard Smith099e7f62011-12-19 06:19:21 +00006329 Expr::EvalStatus EStatus;
6330 EStatus.Diag = &Notes;
6331
6332 EvalInfo InitInfo(Ctx, EStatus);
6333 InitInfo.setEvaluatingDecl(VD, Value);
6334
6335 LValue LVal;
6336 LVal.set(VD);
6337
Richard Smith51201882011-12-30 21:15:51 +00006338 // C++11 [basic.start.init]p2:
6339 // Variables with static storage duration or thread storage duration shall be
6340 // zero-initialized before any other initialization takes place.
6341 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006342 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006343 !VD->getType()->isReferenceType()) {
6344 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006345 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6346 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006347 return false;
6348 }
6349
Richard Smith83587db2012-02-15 02:18:13 +00006350 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6351 /*AllowNonLiteralTypes=*/true) ||
6352 EStatus.HasSideEffects)
6353 return false;
6354
6355 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6356 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006357}
6358
Richard Smith51f47082011-10-29 00:50:52 +00006359/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6360/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006361bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006362 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006363 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006364}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006365
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +00006366APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006367 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006368 EvalResult EvalResult;
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +00006369 EvalResult.Diag = Diag;
Richard Smith51f47082011-10-29 00:50:52 +00006370 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006371 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006372 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006373 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006374
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006375 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006376}
John McCalld905f5a2010-05-07 05:32:02 +00006377
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006378 bool Expr::EvalResult::isGlobalLValue() const {
6379 assert(Val.isLValue());
6380 return IsGlobalLValue(Val.getLValueBase());
6381 }
6382
6383
John McCalld905f5a2010-05-07 05:32:02 +00006384/// isIntegerConstantExpr - this recursive routine will test if an expression is
6385/// an integer constant expression.
6386
6387/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6388/// comma, etc
John McCalld905f5a2010-05-07 05:32:02 +00006389
6390// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smithceb59d92012-12-28 13:25:52 +00006391// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
6392// and a (possibly null) SourceLocation indicating the location of the problem.
6393//
John McCalld905f5a2010-05-07 05:32:02 +00006394// Note that to reduce code duplication, this helper does no evaluation
6395// itself; the caller checks whether the expression is evaluatable, and
6396// in the rare cases where CheckICE actually cares about the evaluated
6397// value, it calls into Evalute.
John McCalld905f5a2010-05-07 05:32:02 +00006398
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006399namespace {
6400
Richard Smithceb59d92012-12-28 13:25:52 +00006401enum ICEKind {
6402 /// This expression is an ICE.
6403 IK_ICE,
6404 /// This expression is not an ICE, but if it isn't evaluated, it's
6405 /// a legal subexpression for an ICE. This return value is used to handle
6406 /// the comma operator in C99 mode, and non-constant subexpressions.
6407 IK_ICEIfUnevaluated,
6408 /// This expression is not an ICE, and is not a legal subexpression for one.
6409 IK_NotICE
6410};
6411
John McCalld905f5a2010-05-07 05:32:02 +00006412struct ICEDiag {
Richard Smithceb59d92012-12-28 13:25:52 +00006413 ICEKind Kind;
John McCalld905f5a2010-05-07 05:32:02 +00006414 SourceLocation Loc;
6415
Richard Smithceb59d92012-12-28 13:25:52 +00006416 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCalld905f5a2010-05-07 05:32:02 +00006417};
6418
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006419}
6420
Richard Smithceb59d92012-12-28 13:25:52 +00006421static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
6422
6423static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCalld905f5a2010-05-07 05:32:02 +00006424
6425static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6426 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006427 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smithceb59d92012-12-28 13:25:52 +00006428 !EVResult.Val.isInt())
6429 return ICEDiag(IK_NotICE, E->getLocStart());
6430
John McCalld905f5a2010-05-07 05:32:02 +00006431 return NoDiag();
6432}
6433
6434static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6435 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smithceb59d92012-12-28 13:25:52 +00006436 if (!E->getType()->isIntegralOrEnumerationType())
6437 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006438
6439 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006440#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006441#define STMT(Node, Base) case Expr::Node##Class:
6442#define EXPR(Node, Base)
6443#include "clang/AST/StmtNodes.inc"
6444 case Expr::PredefinedExprClass:
6445 case Expr::FloatingLiteralClass:
6446 case Expr::ImaginaryLiteralClass:
6447 case Expr::StringLiteralClass:
6448 case Expr::ArraySubscriptExprClass:
6449 case Expr::MemberExprClass:
6450 case Expr::CompoundAssignOperatorClass:
6451 case Expr::CompoundLiteralExprClass:
6452 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006453 case Expr::DesignatedInitExprClass:
6454 case Expr::ImplicitValueInitExprClass:
6455 case Expr::ParenListExprClass:
6456 case Expr::VAArgExprClass:
6457 case Expr::AddrLabelExprClass:
6458 case Expr::StmtExprClass:
6459 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006460 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006461 case Expr::CXXDynamicCastExprClass:
6462 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006463 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006464 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006465 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006466 case Expr::CXXThisExprClass:
6467 case Expr::CXXThrowExprClass:
6468 case Expr::CXXNewExprClass:
6469 case Expr::CXXDeleteExprClass:
6470 case Expr::CXXPseudoDestructorExprClass:
6471 case Expr::UnresolvedLookupExprClass:
6472 case Expr::DependentScopeDeclRefExprClass:
6473 case Expr::CXXConstructExprClass:
6474 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006475 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006476 case Expr::CXXTemporaryObjectExprClass:
6477 case Expr::CXXUnresolvedConstructExprClass:
6478 case Expr::CXXDependentScopeMemberExprClass:
6479 case Expr::UnresolvedMemberExprClass:
6480 case Expr::ObjCStringLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00006481 case Expr::ObjCBoxedExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006482 case Expr::ObjCArrayLiteralClass:
6483 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006484 case Expr::ObjCEncodeExprClass:
6485 case Expr::ObjCMessageExprClass:
6486 case Expr::ObjCSelectorExprClass:
6487 case Expr::ObjCProtocolExprClass:
6488 case Expr::ObjCIvarRefExprClass:
6489 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006490 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006491 case Expr::ObjCIsaExprClass:
6492 case Expr::ShuffleVectorExprClass:
6493 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006494 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006495 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006496 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006497 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smith9a4db032012-09-12 00:56:43 +00006498 case Expr::FunctionParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006499 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006500 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006501 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006502 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006503 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006504 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006505 case Expr::LambdaExprClass:
Richard Smithceb59d92012-12-28 13:25:52 +00006506 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redlcea8d962011-09-24 17:48:14 +00006507
Douglas Gregoree8aff02011-01-04 17:33:58 +00006508 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006509 case Expr::GNUNullExprClass:
6510 // GCC considers the GNU __null value to be an integral constant expression.
6511 return NoDiag();
6512
John McCall91a57552011-07-15 05:09:51 +00006513 case Expr::SubstNonTypeTemplateParmExprClass:
6514 return
6515 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6516
John McCalld905f5a2010-05-07 05:32:02 +00006517 case Expr::ParenExprClass:
6518 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006519 case Expr::GenericSelectionExprClass:
6520 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006521 case Expr::IntegerLiteralClass:
6522 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006523 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006524 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006525 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006526 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006527 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006528 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006529 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006530 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006531 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006532 return NoDiag();
6533 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006534 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006535 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6536 // constant expressions, but they can never be ICEs because an ICE cannot
6537 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006538 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006539 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006540 return CheckEvalInICE(E, Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006541 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006542 }
Richard Smith359c89d2012-02-24 22:12:32 +00006543 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006544 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6545 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006546 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006547 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006548 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006549 // Parameter variables are never constants. Without this check,
6550 // getAnyInitializer() can find a default argument, which leads
6551 // to chaos.
6552 if (isa<ParmVarDecl>(D))
Richard Smithceb59d92012-12-28 13:25:52 +00006553 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006554
6555 // C++ 7.1.5.1p2
6556 // A variable of non-volatile const-qualified integral or enumeration
6557 // type initialized by an ICE can be used in ICEs.
6558 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006559 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smithceb59d92012-12-28 13:25:52 +00006560 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithdb1822c2011-11-08 01:31:09 +00006561
Richard Smith099e7f62011-12-19 06:19:21 +00006562 const VarDecl *VD;
6563 // Look for a declaration of this variable that has an initializer, and
6564 // check whether it is an ICE.
6565 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6566 return NoDiag();
6567 else
Richard Smithceb59d92012-12-28 13:25:52 +00006568 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006569 }
6570 }
Richard Smithceb59d92012-12-28 13:25:52 +00006571 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006572 }
John McCalld905f5a2010-05-07 05:32:02 +00006573 case Expr::UnaryOperatorClass: {
6574 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6575 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006576 case UO_PostInc:
6577 case UO_PostDec:
6578 case UO_PreInc:
6579 case UO_PreDec:
6580 case UO_AddrOf:
6581 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006582 // C99 6.6/3 allows increment and decrement within unevaluated
6583 // subexpressions of constant expressions, but they can never be ICEs
6584 // because an ICE cannot contain an lvalue operand.
Richard Smithceb59d92012-12-28 13:25:52 +00006585 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006586 case UO_Extension:
6587 case UO_LNot:
6588 case UO_Plus:
6589 case UO_Minus:
6590 case UO_Not:
6591 case UO_Real:
6592 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006593 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006594 }
Richard Smithceb59d92012-12-28 13:25:52 +00006595
John McCalld905f5a2010-05-07 05:32:02 +00006596 // OffsetOf falls through here.
6597 }
6598 case Expr::OffsetOfExprClass: {
Richard Smithceb59d92012-12-28 13:25:52 +00006599 // Note that per C99, offsetof must be an ICE. And AFAIK, using
6600 // EvaluateAsRValue matches the proposed gcc behavior for cases like
6601 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
6602 // compliance: we should warn earlier for offsetof expressions with
6603 // array subscripts that aren't ICEs, and if the array subscripts
6604 // are ICEs, the value of the offsetof must be an integer constant.
6605 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006606 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006607 case Expr::UnaryExprOrTypeTraitExprClass: {
6608 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6609 if ((Exp->getKind() == UETT_SizeOf) &&
6610 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smithceb59d92012-12-28 13:25:52 +00006611 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006612 return NoDiag();
6613 }
6614 case Expr::BinaryOperatorClass: {
6615 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6616 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006617 case BO_PtrMemD:
6618 case BO_PtrMemI:
6619 case BO_Assign:
6620 case BO_MulAssign:
6621 case BO_DivAssign:
6622 case BO_RemAssign:
6623 case BO_AddAssign:
6624 case BO_SubAssign:
6625 case BO_ShlAssign:
6626 case BO_ShrAssign:
6627 case BO_AndAssign:
6628 case BO_XorAssign:
6629 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006630 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6631 // constant expressions, but they can never be ICEs because an ICE cannot
6632 // contain an lvalue operand.
Richard Smithceb59d92012-12-28 13:25:52 +00006633 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006634
John McCall2de56d12010-08-25 11:45:40 +00006635 case BO_Mul:
6636 case BO_Div:
6637 case BO_Rem:
6638 case BO_Add:
6639 case BO_Sub:
6640 case BO_Shl:
6641 case BO_Shr:
6642 case BO_LT:
6643 case BO_GT:
6644 case BO_LE:
6645 case BO_GE:
6646 case BO_EQ:
6647 case BO_NE:
6648 case BO_And:
6649 case BO_Xor:
6650 case BO_Or:
6651 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006652 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6653 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006654 if (Exp->getOpcode() == BO_Div ||
6655 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006656 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006657 // we don't evaluate one.
Richard Smithceb59d92012-12-28 13:25:52 +00006658 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006659 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006660 if (REval == 0)
Richard Smithceb59d92012-12-28 13:25:52 +00006661 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006662 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006663 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006664 if (LEval.isMinSignedValue())
Richard Smithceb59d92012-12-28 13:25:52 +00006665 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006666 }
6667 }
6668 }
John McCall2de56d12010-08-25 11:45:40 +00006669 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006670 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006671 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6672 // if it isn't evaluated.
Richard Smithceb59d92012-12-28 13:25:52 +00006673 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
6674 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006675 } else {
6676 // In both C89 and C++, commas in ICEs are illegal.
Richard Smithceb59d92012-12-28 13:25:52 +00006677 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006678 }
6679 }
Richard Smithceb59d92012-12-28 13:25:52 +00006680 return Worst(LHSResult, RHSResult);
John McCalld905f5a2010-05-07 05:32:02 +00006681 }
John McCall2de56d12010-08-25 11:45:40 +00006682 case BO_LAnd:
6683 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006684 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6685 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006686 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCalld905f5a2010-05-07 05:32:02 +00006687 // Rare case where the RHS has a comma "side-effect"; we need
6688 // to actually check the condition to see whether the side
6689 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006690 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006691 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006692 return RHSResult;
6693 return NoDiag();
6694 }
6695
Richard Smithceb59d92012-12-28 13:25:52 +00006696 return Worst(LHSResult, RHSResult);
John McCalld905f5a2010-05-07 05:32:02 +00006697 }
6698 }
6699 }
6700 case Expr::ImplicitCastExprClass:
6701 case Expr::CStyleCastExprClass:
6702 case Expr::CXXFunctionalCastExprClass:
6703 case Expr::CXXStaticCastExprClass:
6704 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006705 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006706 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006707 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006708 if (isa<ExplicitCastExpr>(E)) {
6709 if (const FloatingLiteral *FL
6710 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6711 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6712 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6713 APSInt IgnoredVal(DestWidth, !DestSigned);
6714 bool Ignored;
6715 // If the value does not fit in the destination type, the behavior is
6716 // undefined, so we are not required to treat it as a constant
6717 // expression.
6718 if (FL->getValue().convertToInteger(IgnoredVal,
6719 llvm::APFloat::rmTowardZero,
6720 &Ignored) & APFloat::opInvalidOp)
Richard Smithceb59d92012-12-28 13:25:52 +00006721 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith2116b142011-12-18 02:33:09 +00006722 return NoDiag();
6723 }
6724 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006725 switch (cast<CastExpr>(E)->getCastKind()) {
6726 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006727 case CK_AtomicToNonAtomic:
6728 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006729 case CK_NoOp:
6730 case CK_IntegralToBoolean:
6731 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006732 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006733 default:
Richard Smithceb59d92012-12-28 13:25:52 +00006734 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedmaneea0e812011-09-29 21:49:34 +00006735 }
John McCalld905f5a2010-05-07 05:32:02 +00006736 }
John McCall56ca35d2011-02-17 10:25:35 +00006737 case Expr::BinaryConditionalOperatorClass: {
6738 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6739 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006740 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCall56ca35d2011-02-17 10:25:35 +00006741 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006742 if (FalseResult.Kind == IK_NotICE) return FalseResult;
6743 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
6744 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith9b403c52012-12-28 12:53:55 +00006745 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006746 return FalseResult;
6747 }
John McCalld905f5a2010-05-07 05:32:02 +00006748 case Expr::ConditionalOperatorClass: {
6749 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6750 // If the condition (ignoring parens) is a __builtin_constant_p call,
6751 // then only the true side is actually considered in an integer constant
6752 // expression, and it is fully evaluated. This is an important GNU
6753 // extension. See GCC PR38377 for discussion.
6754 if (const CallExpr *CallCE
6755 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006756 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6757 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006758 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006759 if (CondResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00006760 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006761
Richard Smithf48fdb02011-12-09 22:58:01 +00006762 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6763 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006764
Richard Smithceb59d92012-12-28 13:25:52 +00006765 if (TrueResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00006766 return TrueResult;
Richard Smithceb59d92012-12-28 13:25:52 +00006767 if (FalseResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00006768 return FalseResult;
Richard Smithceb59d92012-12-28 13:25:52 +00006769 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCalld905f5a2010-05-07 05:32:02 +00006770 return CondResult;
Richard Smithceb59d92012-12-28 13:25:52 +00006771 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCalld905f5a2010-05-07 05:32:02 +00006772 return NoDiag();
6773 // Rare case where the diagnostics depend on which side is evaluated
6774 // Note that if we get here, CondResult is 0, and at least one of
6775 // TrueResult and FalseResult is non-zero.
Richard Smithceb59d92012-12-28 13:25:52 +00006776 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCalld905f5a2010-05-07 05:32:02 +00006777 return FalseResult;
John McCalld905f5a2010-05-07 05:32:02 +00006778 return TrueResult;
6779 }
6780 case Expr::CXXDefaultArgExprClass:
6781 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6782 case Expr::ChooseExprClass: {
6783 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6784 }
6785 }
6786
David Blaikie30263482012-01-20 21:50:17 +00006787 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006788}
6789
Richard Smithf48fdb02011-12-09 22:58:01 +00006790/// Evaluate an expression as a C++11 integral constant expression.
6791static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6792 const Expr *E,
6793 llvm::APSInt *Value,
6794 SourceLocation *Loc) {
6795 if (!E->getType()->isIntegralOrEnumerationType()) {
6796 if (Loc) *Loc = E->getExprLoc();
6797 return false;
6798 }
6799
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006800 APValue Result;
6801 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006802 return false;
6803
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006804 assert(Result.isInt() && "pointer cast to int is not an ICE");
6805 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006806 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006807}
6808
Richard Smithdd1f29b2011-12-12 09:28:41 +00006809bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith80ad52f2013-01-02 11:42:31 +00006810 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf48fdb02011-12-09 22:58:01 +00006811 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6812
Richard Smithceb59d92012-12-28 13:25:52 +00006813 ICEDiag D = CheckICE(this, Ctx);
6814 if (D.Kind != IK_ICE) {
6815 if (Loc) *Loc = D.Loc;
John McCalld905f5a2010-05-07 05:32:02 +00006816 return false;
6817 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006818 return true;
6819}
6820
6821bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6822 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith80ad52f2013-01-02 11:42:31 +00006823 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf48fdb02011-12-09 22:58:01 +00006824 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6825
6826 if (!isIntegerConstantExpr(Ctx, Loc))
6827 return false;
6828 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006829 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006830 return true;
6831}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006832
Richard Smith70488e22012-02-14 21:38:30 +00006833bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smithceb59d92012-12-28 13:25:52 +00006834 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith70488e22012-02-14 21:38:30 +00006835}
6836
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006837bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6838 SourceLocation *Loc) const {
6839 // We support this checking in C++98 mode in order to diagnose compatibility
6840 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006841 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006842
Richard Smith70488e22012-02-14 21:38:30 +00006843 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006844 Expr::EvalStatus Status;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006845 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006846 Status.Diag = &Diags;
6847 EvalInfo Info(Ctx, Status);
6848
6849 APValue Scratch;
6850 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6851
6852 if (!Diags.empty()) {
6853 IsConstExpr = false;
6854 if (Loc) *Loc = Diags[0].first;
6855 } else if (!IsConstExpr) {
6856 // FIXME: This shouldn't happen.
6857 if (Loc) *Loc = getExprLoc();
6858 }
6859
6860 return IsConstExpr;
6861}
Richard Smith745f5142012-01-27 01:14:48 +00006862
6863bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006864 SmallVectorImpl<
Richard Smith745f5142012-01-27 01:14:48 +00006865 PartialDiagnosticAt> &Diags) {
6866 // FIXME: It would be useful to check constexpr function templates, but at the
6867 // moment the constant expression evaluator cannot cope with the non-rigorous
6868 // ASTs which we build for dependent expressions.
6869 if (FD->isDependentContext())
6870 return true;
6871
6872 Expr::EvalStatus Status;
6873 Status.Diag = &Diags;
6874
6875 EvalInfo Info(FD->getASTContext(), Status);
6876 Info.CheckingPotentialConstantExpression = true;
6877
6878 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6879 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6880
6881 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6882 // is a temporary being used as the 'this' pointer.
6883 LValue This;
6884 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006885 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006886
Richard Smith745f5142012-01-27 01:14:48 +00006887 ArrayRef<const Expr*> Args;
6888
6889 SourceLocation Loc = FD->getLocation();
6890
Richard Smith1aa0be82012-03-03 22:46:17 +00006891 APValue Scratch;
6892 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006893 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006894 else
Richard Smith745f5142012-01-27 01:14:48 +00006895 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6896 Args, FD->getBody(), Info, Scratch);
6897
6898 return Diags.empty();
6899}