blob: 6023a678e2aeecd0a61cea262ef6ae30048e81f3 [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith745f5142012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlssonc44eec62008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000038#include "clang/AST/CharUnits.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000039#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000040#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000041#include "clang/AST/TypeLoc.h"
Chris Lattner500d3292009-01-29 05:15:15 +000042#include "clang/AST/ASTDiagnostic.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/Expr.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Mike Stump4572bab2009-05-30 03:56:50 +000047#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000048#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000049
Anders Carlssonc44eec62008-07-03 04:20:39 +000050using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000051using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000052using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000053
Richard Smith83587db2012-02-15 02:18:13 +000054static bool IsGlobalLValue(APValue::LValueBase B);
55
John McCallf4cf1a12010-05-07 17:22:02 +000056namespace {
Richard Smith180f4792011-11-10 06:34:14 +000057 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000058 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000059 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000060
Richard Smith83587db2012-02-15 02:18:13 +000061 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000062 if (!B) return QualType();
63 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
64 return D->getType();
65 return B.get<const Expr*>()->getType();
66 }
67
Richard Smith180f4792011-11-10 06:34:14 +000068 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000069 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000070 static
Richard Smithf15fda02012-02-02 01:16:57 +000071 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000072 APValue::BaseOrMemberType Value;
73 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000074 return Value;
75 }
76
77 /// Get an LValue path entry, which is known to not be an array index, as a
78 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000079 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000080 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000081 }
82 /// Get an LValue path entry, which is known to not be an array index, as a
83 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000084 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000085 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000086 }
87 /// Determine whether this LValue path entry for a base class names a virtual
88 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000089 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000090 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000091 }
92
Richard Smithb4e85ed2012-01-06 16:39:00 +000093 /// Find the path length and type of the most-derived subobject in the given
94 /// path, and find the size of the containing array, if any.
95 static
96 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
97 ArrayRef<APValue::LValuePathEntry> Path,
98 uint64_t &ArraySize, QualType &Type) {
99 unsigned MostDerivedLength = 0;
100 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000101 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000102 if (Type->isArrayType()) {
103 const ConstantArrayType *CAT =
104 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
105 Type = CAT->getElementType();
106 ArraySize = CAT->getSize().getZExtValue();
107 MostDerivedLength = I + 1;
Richard Smith86024012012-02-18 22:04:06 +0000108 } else if (Type->isAnyComplexType()) {
109 const ComplexType *CT = Type->castAs<ComplexType>();
110 Type = CT->getElementType();
111 ArraySize = 2;
112 MostDerivedLength = I + 1;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000113 } else if (const FieldDecl *FD = getAsField(Path[I])) {
114 Type = FD->getType();
115 ArraySize = 0;
116 MostDerivedLength = I + 1;
117 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000118 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000119 ArraySize = 0;
120 }
Richard Smith9a17a682011-11-07 05:07:52 +0000121 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000122 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000123 }
124
Richard Smithb4e85ed2012-01-06 16:39:00 +0000125 // The order of this enum is important for diagnostics.
126 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000127 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith86024012012-02-18 22:04:06 +0000128 CSK_This, CSK_Real, CSK_Imag
Richard Smithb4e85ed2012-01-06 16:39:00 +0000129 };
130
Richard Smith0a3bdb62011-11-04 02:25:55 +0000131 /// A path from a glvalue to a subobject of that glvalue.
132 struct SubobjectDesignator {
133 /// True if the subobject was named in a manner not supported by C++11. Such
134 /// lvalues can still be folded, but they are not core constant expressions
135 /// and we cannot perform lvalue-to-rvalue conversions on them.
136 bool Invalid : 1;
137
Richard Smithb4e85ed2012-01-06 16:39:00 +0000138 /// Is this a pointer one past the end of an object?
139 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000140
Richard Smithb4e85ed2012-01-06 16:39:00 +0000141 /// The length of the path to the most-derived object of which this is a
142 /// subobject.
143 unsigned MostDerivedPathLength : 30;
144
145 /// The size of the array of which the most-derived object is an element, or
146 /// 0 if the most-derived object is not an array element.
147 uint64_t MostDerivedArraySize;
148
149 /// The type of the most derived object referred to by this address.
150 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000151
Richard Smith9a17a682011-11-07 05:07:52 +0000152 typedef APValue::LValuePathEntry PathEntry;
153
Richard Smith0a3bdb62011-11-04 02:25:55 +0000154 /// The entries on the path from the glvalue to the designated subobject.
155 SmallVector<PathEntry, 8> Entries;
156
Richard Smithb4e85ed2012-01-06 16:39:00 +0000157 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000158
Richard Smithb4e85ed2012-01-06 16:39:00 +0000159 explicit SubobjectDesignator(QualType T)
160 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
161 MostDerivedArraySize(0), MostDerivedType(T) {}
162
163 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
164 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
165 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000166 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000167 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000168 ArrayRef<PathEntry> VEntries = V.getLValuePath();
169 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
170 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000171 MostDerivedPathLength =
172 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
173 V.getLValuePath(), MostDerivedArraySize,
174 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000175 }
176 }
177
Richard Smith0a3bdb62011-11-04 02:25:55 +0000178 void setInvalid() {
179 Invalid = true;
180 Entries.clear();
181 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000182
183 /// Determine whether this is a one-past-the-end pointer.
184 bool isOnePastTheEnd() const {
185 if (IsOnePastTheEnd)
186 return true;
187 if (MostDerivedArraySize &&
188 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
189 return true;
190 return false;
191 }
192
193 /// Check that this refers to a valid subobject.
194 bool isValidSubobject() const {
195 if (Invalid)
196 return false;
197 return !isOnePastTheEnd();
198 }
199 /// Check that this refers to a valid subobject, and if not, produce a
200 /// relevant diagnostic and set the designator as invalid.
201 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
202
203 /// Update this designator to refer to the first element within this array.
204 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000205 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000206 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000207 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000208
209 // This is a most-derived object.
210 MostDerivedType = CAT->getElementType();
211 MostDerivedArraySize = CAT->getSize().getZExtValue();
212 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000213 }
214 /// Update this designator to refer to the given base or member of this
215 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000216 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000217 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000218 APValue::BaseOrMemberType Value(D, Virtual);
219 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000220 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000221
222 // If this isn't a base class, it's a new most-derived object.
223 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
224 MostDerivedType = FD->getType();
225 MostDerivedArraySize = 0;
226 MostDerivedPathLength = Entries.size();
227 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000228 }
Richard Smith86024012012-02-18 22:04:06 +0000229 /// Update this designator to refer to the given complex component.
230 void addComplexUnchecked(QualType EltTy, bool Imag) {
231 PathEntry Entry;
232 Entry.ArrayIndex = Imag;
233 Entries.push_back(Entry);
234
235 // This is technically a most-derived object, though in practice this
236 // is unlikely to matter.
237 MostDerivedType = EltTy;
238 MostDerivedArraySize = 2;
239 MostDerivedPathLength = Entries.size();
240 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000241 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000242 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000243 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000244 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000245 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000246 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000247 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
248 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
249 setInvalid();
250 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000251 return;
252 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000253 // [expr.add]p4: For the purposes of these operators, a pointer to a
254 // nonarray object behaves the same as a pointer to the first element of
255 // an array of length one with the type of the object as its element type.
256 if (IsOnePastTheEnd && N == (uint64_t)-1)
257 IsOnePastTheEnd = false;
258 else if (!IsOnePastTheEnd && N == 1)
259 IsOnePastTheEnd = true;
260 else if (N != 0) {
261 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000262 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000263 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000264 }
265 };
266
Richard Smithd0dccea2011-10-28 22:34:42 +0000267 /// A stack frame in the constexpr call stack.
268 struct CallStackFrame {
269 EvalInfo &Info;
270
271 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000272 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000273
Richard Smith08d6e032011-12-16 19:06:07 +0000274 /// CallLoc - The location of the call expression for this call.
275 SourceLocation CallLoc;
276
277 /// Callee - The function which was called.
278 const FunctionDecl *Callee;
279
Richard Smith83587db2012-02-15 02:18:13 +0000280 /// Index - The call index of this call.
281 unsigned Index;
282
Richard Smith180f4792011-11-10 06:34:14 +0000283 /// This - The binding for the this pointer in this call, if any.
284 const LValue *This;
285
Richard Smithd0dccea2011-10-28 22:34:42 +0000286 /// ParmBindings - Parameter bindings for this function call, indexed by
287 /// parameters' function scope indices.
Richard Smith1aa0be82012-03-03 22:46:17 +0000288 const APValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000289
Richard Smith1aa0be82012-03-03 22:46:17 +0000290 typedef llvm::DenseMap<const Expr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000291 typedef MapTy::const_iterator temp_iterator;
292 /// Temporaries - Temporary lvalues materialized within this stack frame.
293 MapTy Temporaries;
294
Richard Smith08d6e032011-12-16 19:06:07 +0000295 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
296 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000297 const APValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000298 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000299 };
300
Richard Smithdd1f29b2011-12-12 09:28:41 +0000301 /// A partial diagnostic which we might know in advance that we are not going
302 /// to emit.
303 class OptionalDiagnostic {
304 PartialDiagnostic *Diag;
305
306 public:
307 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
308
309 template<typename T>
310 OptionalDiagnostic &operator<<(const T &v) {
311 if (Diag)
312 *Diag << v;
313 return *this;
314 }
Richard Smith789f9b62012-01-31 04:08:20 +0000315
316 OptionalDiagnostic &operator<<(const APSInt &I) {
317 if (Diag) {
318 llvm::SmallVector<char, 32> Buffer;
319 I.toString(Buffer);
320 *Diag << StringRef(Buffer.data(), Buffer.size());
321 }
322 return *this;
323 }
324
325 OptionalDiagnostic &operator<<(const APFloat &F) {
326 if (Diag) {
327 llvm::SmallVector<char, 32> Buffer;
328 F.toString(Buffer);
329 *Diag << StringRef(Buffer.data(), Buffer.size());
330 }
331 return *this;
332 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000333 };
334
Richard Smith83587db2012-02-15 02:18:13 +0000335 /// EvalInfo - This is a private struct used by the evaluator to capture
336 /// information about a subexpression as it is folded. It retains information
337 /// about the AST context, but also maintains information about the folded
338 /// expression.
339 ///
340 /// If an expression could be evaluated, it is still possible it is not a C
341 /// "integer constant expression" or constant expression. If not, this struct
342 /// captures information about how and why not.
343 ///
344 /// One bit of information passed *into* the request for constant folding
345 /// indicates whether the subexpression is "evaluated" or not according to C
346 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
347 /// evaluate the expression regardless of what the RHS is, but C only allows
348 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000349 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000350 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000351
Richard Smithbd552ef2011-10-31 05:52:43 +0000352 /// EvalStatus - Contains information about the evaluation.
353 Expr::EvalStatus &EvalStatus;
354
355 /// CurrentCall - The top of the constexpr call stack.
356 CallStackFrame *CurrentCall;
357
Richard Smithbd552ef2011-10-31 05:52:43 +0000358 /// CallStackDepth - The number of calls in the call stack right now.
359 unsigned CallStackDepth;
360
Richard Smith83587db2012-02-15 02:18:13 +0000361 /// NextCallIndex - The next call index to assign.
362 unsigned NextCallIndex;
363
Richard Smith1aa0be82012-03-03 22:46:17 +0000364 typedef llvm::DenseMap<const OpaqueValueExpr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000365 /// OpaqueValues - Values used as the common expression in a
366 /// BinaryConditionalOperator.
367 MapTy OpaqueValues;
368
369 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000370 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000371 CallStackFrame BottomFrame;
372
Richard Smith180f4792011-11-10 06:34:14 +0000373 /// EvaluatingDecl - This is the declaration whose initializer is being
374 /// evaluated, if any.
375 const VarDecl *EvaluatingDecl;
376
377 /// EvaluatingDeclValue - This is the value being constructed for the
378 /// declaration whose initializer is being evaluated, if any.
379 APValue *EvaluatingDeclValue;
380
Richard Smithc1c5f272011-12-13 06:39:58 +0000381 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
382 /// notes attached to it will also be stored, otherwise they will not be.
383 bool HasActiveDiagnostic;
384
Richard Smith745f5142012-01-27 01:14:48 +0000385 /// CheckingPotentialConstantExpression - Are we checking whether the
386 /// expression is a potential constant expression? If so, some diagnostics
387 /// are suppressed.
388 bool CheckingPotentialConstantExpression;
389
Richard Smithbd552ef2011-10-31 05:52:43 +0000390 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000391 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000392 CallStackDepth(0), NextCallIndex(1),
393 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000394 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Argyrios Kyrtzidis649dfbc2012-03-15 18:07:13 +0000395 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000396
Richard Smith1aa0be82012-03-03 22:46:17 +0000397 const APValue *getOpaqueValue(const OpaqueValueExpr *e) const {
Richard Smithbd552ef2011-10-31 05:52:43 +0000398 MapTy::const_iterator i = OpaqueValues.find(e);
399 if (i == OpaqueValues.end()) return 0;
400 return &i->second;
401 }
402
Richard Smith180f4792011-11-10 06:34:14 +0000403 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
404 EvaluatingDecl = VD;
405 EvaluatingDeclValue = &Value;
406 }
407
David Blaikie4e4d0842012-03-11 07:00:24 +0000408 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000409
Richard Smithc1c5f272011-12-13 06:39:58 +0000410 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000411 // Don't perform any constexpr calls (other than the call we're checking)
412 // when checking a potential constant expression.
413 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
414 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000415 if (NextCallIndex == 0) {
416 // NextCallIndex has wrapped around.
417 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
418 return false;
419 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000420 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
421 return true;
422 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
423 << getLangOpts().ConstexprCallDepth;
424 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000425 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000426
Richard Smith83587db2012-02-15 02:18:13 +0000427 CallStackFrame *getCallFrame(unsigned CallIndex) {
428 assert(CallIndex && "no call index in getCallFrame");
429 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
430 // be null in this loop.
431 CallStackFrame *Frame = CurrentCall;
432 while (Frame->Index > CallIndex)
433 Frame = Frame->Caller;
434 return (Frame->Index == CallIndex) ? Frame : 0;
435 }
436
Richard Smithc1c5f272011-12-13 06:39:58 +0000437 private:
438 /// Add a diagnostic to the diagnostics list.
439 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
440 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
441 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
442 return EvalStatus.Diag->back().second;
443 }
444
Richard Smith08d6e032011-12-16 19:06:07 +0000445 /// Add notes containing a call stack to the current point of evaluation.
446 void addCallStack(unsigned Limit);
447
Richard Smithc1c5f272011-12-13 06:39:58 +0000448 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000449 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000450 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
451 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000452 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000453 // If we have a prior diagnostic, it will be noting that the expression
454 // isn't a constant expression. This diagnostic is more important.
455 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000456 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000457 unsigned CallStackNotes = CallStackDepth - 1;
458 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
459 if (Limit)
460 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000461 if (CheckingPotentialConstantExpression)
462 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000463
Richard Smithc1c5f272011-12-13 06:39:58 +0000464 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000465 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000466 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
467 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000468 if (!CheckingPotentialConstantExpression)
469 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000470 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000471 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000472 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000473 return OptionalDiagnostic();
474 }
475
Richard Smith5cfc7d82012-03-15 04:53:45 +0000476 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
477 = diag::note_invalid_subexpr_in_const_expr,
478 unsigned ExtraNotes = 0) {
479 if (EvalStatus.Diag)
480 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
481 HasActiveDiagnostic = false;
482 return OptionalDiagnostic();
483 }
484
Richard Smithdd1f29b2011-12-12 09:28:41 +0000485 /// Diagnose that the evaluation does not produce a C++11 core constant
486 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000487 template<typename LocArg>
488 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000489 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000490 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000491 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000492 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
493 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000494 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000495 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000496 return Diag(Loc, DiagId, ExtraNotes);
497 }
498
499 /// Add a note to a prior diagnostic.
500 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
501 if (!HasActiveDiagnostic)
502 return OptionalDiagnostic();
503 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000504 }
Richard Smith099e7f62011-12-19 06:19:21 +0000505
506 /// Add a stack of notes to a prior diagnostic.
507 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
508 if (HasActiveDiagnostic) {
509 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
510 Diags.begin(), Diags.end());
511 }
512 }
Richard Smith745f5142012-01-27 01:14:48 +0000513
514 /// Should we continue evaluation as much as possible after encountering a
515 /// construct which can't be folded?
516 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000517 return CheckingPotentialConstantExpression &&
518 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000519 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000520 };
Richard Smithf15fda02012-02-02 01:16:57 +0000521
522 /// Object used to treat all foldable expressions as constant expressions.
523 struct FoldConstant {
524 bool Enabled;
525
526 explicit FoldConstant(EvalInfo &Info)
527 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
528 !Info.EvalStatus.HasSideEffects) {
529 }
530 // Treat the value we've computed since this object was created as constant.
531 void Fold(EvalInfo &Info) {
532 if (Enabled && !Info.EvalStatus.Diag->empty() &&
533 !Info.EvalStatus.HasSideEffects)
534 Info.EvalStatus.Diag->clear();
535 }
536 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000537
538 /// RAII object used to suppress diagnostics and side-effects from a
539 /// speculative evaluation.
540 class SpeculativeEvaluationRAII {
541 EvalInfo &Info;
542 Expr::EvalStatus Old;
543
544 public:
545 SpeculativeEvaluationRAII(EvalInfo &Info,
546 llvm::SmallVectorImpl<PartialDiagnosticAt>
547 *NewDiag = 0)
548 : Info(Info), Old(Info.EvalStatus) {
549 Info.EvalStatus.Diag = NewDiag;
550 }
551 ~SpeculativeEvaluationRAII() {
552 Info.EvalStatus = Old;
553 }
554 };
Richard Smith08d6e032011-12-16 19:06:07 +0000555}
Richard Smithbd552ef2011-10-31 05:52:43 +0000556
Richard Smithb4e85ed2012-01-06 16:39:00 +0000557bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
558 CheckSubobjectKind CSK) {
559 if (Invalid)
560 return false;
561 if (isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000562 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000563 << CSK;
564 setInvalid();
565 return false;
566 }
567 return true;
568}
569
570void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
571 const Expr *E, uint64_t N) {
572 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000573 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000574 << static_cast<int>(N) << /*array*/ 0
575 << static_cast<unsigned>(MostDerivedArraySize);
576 else
Richard Smith5cfc7d82012-03-15 04:53:45 +0000577 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000578 << static_cast<int>(N) << /*non-array*/ 1;
579 setInvalid();
580}
581
Richard Smith08d6e032011-12-16 19:06:07 +0000582CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
583 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000584 const APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000585 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000586 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000587 Info.CurrentCall = this;
588 ++Info.CallStackDepth;
589}
590
591CallStackFrame::~CallStackFrame() {
592 assert(Info.CurrentCall == this && "calls retired out of order");
593 --Info.CallStackDepth;
594 Info.CurrentCall = Caller;
595}
596
597/// Produce a string describing the given constexpr call.
598static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
599 unsigned ArgIndex = 0;
600 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000601 !isa<CXXConstructorDecl>(Frame->Callee) &&
602 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000603
604 if (!IsMemberCall)
605 Out << *Frame->Callee << '(';
606
607 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
608 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000609 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000610 Out << ", ";
611
612 const ParmVarDecl *Param = *I;
Richard Smith1aa0be82012-03-03 22:46:17 +0000613 const APValue &Arg = Frame->Arguments[ArgIndex];
614 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smith08d6e032011-12-16 19:06:07 +0000615
616 if (ArgIndex == 0 && IsMemberCall)
617 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000618 }
619
Richard Smith08d6e032011-12-16 19:06:07 +0000620 Out << ')';
621}
622
623void EvalInfo::addCallStack(unsigned Limit) {
624 // Determine which calls to skip, if any.
625 unsigned ActiveCalls = CallStackDepth - 1;
626 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
627 if (Limit && Limit < ActiveCalls) {
628 SkipStart = Limit / 2 + Limit % 2;
629 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000630 }
631
Richard Smith08d6e032011-12-16 19:06:07 +0000632 // Walk the call stack and add the diagnostics.
633 unsigned CallIdx = 0;
634 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
635 Frame = Frame->Caller, ++CallIdx) {
636 // Skip this call?
637 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
638 if (CallIdx == SkipStart) {
639 // Note that we're skipping calls.
640 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
641 << unsigned(ActiveCalls - Limit);
642 }
643 continue;
644 }
645
646 llvm::SmallVector<char, 128> Buffer;
647 llvm::raw_svector_ostream Out(Buffer);
648 describeCall(Frame, Out);
649 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
650 }
651}
652
653namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000654 struct ComplexValue {
655 private:
656 bool IsInt;
657
658 public:
659 APSInt IntReal, IntImag;
660 APFloat FloatReal, FloatImag;
661
662 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
663
664 void makeComplexFloat() { IsInt = false; }
665 bool isComplexFloat() const { return !IsInt; }
666 APFloat &getComplexFloatReal() { return FloatReal; }
667 APFloat &getComplexFloatImag() { return FloatImag; }
668
669 void makeComplexInt() { IsInt = true; }
670 bool isComplexInt() const { return IsInt; }
671 APSInt &getComplexIntReal() { return IntReal; }
672 APSInt &getComplexIntImag() { return IntImag; }
673
Richard Smith1aa0be82012-03-03 22:46:17 +0000674 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000675 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000676 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000677 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000678 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000679 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000680 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000681 assert(v.isComplexFloat() || v.isComplexInt());
682 if (v.isComplexFloat()) {
683 makeComplexFloat();
684 FloatReal = v.getComplexFloatReal();
685 FloatImag = v.getComplexFloatImag();
686 } else {
687 makeComplexInt();
688 IntReal = v.getComplexIntReal();
689 IntImag = v.getComplexIntImag();
690 }
691 }
John McCallf4cf1a12010-05-07 17:22:02 +0000692 };
John McCallefdb83e2010-05-07 21:00:08 +0000693
694 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000695 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000696 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000697 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000698 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000699
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000700 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000701 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000702 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000703 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000704 SubobjectDesignator &getLValueDesignator() { return Designator; }
705 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000706
Richard Smith1aa0be82012-03-03 22:46:17 +0000707 void moveInto(APValue &V) const {
708 if (Designator.Invalid)
709 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
710 else
711 V = APValue(Base, Offset, Designator.Entries,
712 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000713 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000714 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000715 assert(V.isLValue());
716 Base = V.getLValueBase();
717 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000718 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000719 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000720 }
721
Richard Smith83587db2012-02-15 02:18:13 +0000722 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000723 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000724 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000725 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000726 Designator = SubobjectDesignator(getType(B));
727 }
728
729 // Check that this LValue is not based on a null pointer. If it is, produce
730 // a diagnostic and mark the designator as invalid.
731 bool checkNullPointer(EvalInfo &Info, const Expr *E,
732 CheckSubobjectKind CSK) {
733 if (Designator.Invalid)
734 return false;
735 if (!Base) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000736 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000737 << CSK;
738 Designator.setInvalid();
739 return false;
740 }
741 return true;
742 }
743
744 // Check this LValue refers to an object. If not, set the designator to be
745 // invalid and emit a diagnostic.
746 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000747 // Outside C++11, do not build a designator referring to a subobject of
748 // any object: we won't use such a designator for anything.
749 if (!Info.getLangOpts().CPlusPlus0x)
750 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000751 return checkNullPointer(Info, E, CSK) &&
752 Designator.checkSubobject(Info, E, CSK);
753 }
754
755 void addDecl(EvalInfo &Info, const Expr *E,
756 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000757 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
758 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000759 }
760 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000761 if (checkSubobject(Info, E, CSK_ArrayToPointer))
762 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000763 }
Richard Smith86024012012-02-18 22:04:06 +0000764 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000765 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
766 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000767 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000768 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000769 if (checkNullPointer(Info, E, CSK_ArrayIndex))
770 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000771 }
John McCallefdb83e2010-05-07 21:00:08 +0000772 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000773
774 struct MemberPtr {
775 MemberPtr() {}
776 explicit MemberPtr(const ValueDecl *Decl) :
777 DeclAndIsDerivedMember(Decl, false), Path() {}
778
779 /// The member or (direct or indirect) field referred to by this member
780 /// pointer, or 0 if this is a null member pointer.
781 const ValueDecl *getDecl() const {
782 return DeclAndIsDerivedMember.getPointer();
783 }
784 /// Is this actually a member of some type derived from the relevant class?
785 bool isDerivedMember() const {
786 return DeclAndIsDerivedMember.getInt();
787 }
788 /// Get the class which the declaration actually lives in.
789 const CXXRecordDecl *getContainingRecord() const {
790 return cast<CXXRecordDecl>(
791 DeclAndIsDerivedMember.getPointer()->getDeclContext());
792 }
793
Richard Smith1aa0be82012-03-03 22:46:17 +0000794 void moveInto(APValue &V) const {
795 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000796 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000797 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000798 assert(V.isMemberPointer());
799 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
800 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
801 Path.clear();
802 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
803 Path.insert(Path.end(), P.begin(), P.end());
804 }
805
806 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
807 /// whether the member is a member of some class derived from the class type
808 /// of the member pointer.
809 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
810 /// Path - The path of base/derived classes from the member declaration's
811 /// class (exclusive) to the class type of the member pointer (inclusive).
812 SmallVector<const CXXRecordDecl*, 4> Path;
813
814 /// Perform a cast towards the class of the Decl (either up or down the
815 /// hierarchy).
816 bool castBack(const CXXRecordDecl *Class) {
817 assert(!Path.empty());
818 const CXXRecordDecl *Expected;
819 if (Path.size() >= 2)
820 Expected = Path[Path.size() - 2];
821 else
822 Expected = getContainingRecord();
823 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
824 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
825 // if B does not contain the original member and is not a base or
826 // derived class of the class containing the original member, the result
827 // of the cast is undefined.
828 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
829 // (D::*). We consider that to be a language defect.
830 return false;
831 }
832 Path.pop_back();
833 return true;
834 }
835 /// Perform a base-to-derived member pointer cast.
836 bool castToDerived(const CXXRecordDecl *Derived) {
837 if (!getDecl())
838 return true;
839 if (!isDerivedMember()) {
840 Path.push_back(Derived);
841 return true;
842 }
843 if (!castBack(Derived))
844 return false;
845 if (Path.empty())
846 DeclAndIsDerivedMember.setInt(false);
847 return true;
848 }
849 /// Perform a derived-to-base member pointer cast.
850 bool castToBase(const CXXRecordDecl *Base) {
851 if (!getDecl())
852 return true;
853 if (Path.empty())
854 DeclAndIsDerivedMember.setInt(true);
855 if (isDerivedMember()) {
856 Path.push_back(Base);
857 return true;
858 }
859 return castBack(Base);
860 }
861 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000862
Richard Smithb02e4622012-02-01 01:42:44 +0000863 /// Compare two member pointers, which are assumed to be of the same type.
864 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
865 if (!LHS.getDecl() || !RHS.getDecl())
866 return !LHS.getDecl() && !RHS.getDecl();
867 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
868 return false;
869 return LHS.Path == RHS.Path;
870 }
871
Richard Smithc1c5f272011-12-13 06:39:58 +0000872 /// Kinds of constant expression checking, for diagnostics.
873 enum CheckConstantExpressionKind {
874 CCEK_Constant, ///< A normal constant.
875 CCEK_ReturnValue, ///< A constexpr function return value.
876 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
877 };
John McCallf4cf1a12010-05-07 17:22:02 +0000878}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000879
Richard Smith1aa0be82012-03-03 22:46:17 +0000880static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000881static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
882 const LValue &This, const Expr *E,
883 CheckConstantExpressionKind CCEK = CCEK_Constant,
884 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000885static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
886static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000887static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
888 EvalInfo &Info);
889static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000890static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000891static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000892 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000893static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000894static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000895
896//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000897// Misc utilities
898//===----------------------------------------------------------------------===//
899
Richard Smith180f4792011-11-10 06:34:14 +0000900/// Should this call expression be treated as a string literal?
901static bool IsStringLiteralCall(const CallExpr *E) {
902 unsigned Builtin = E->isBuiltinCall();
903 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
904 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
905}
906
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000907static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000908 // C++11 [expr.const]p3 An address constant expression is a prvalue core
909 // constant expression of pointer type that evaluates to...
910
911 // ... a null pointer value, or a prvalue core constant expression of type
912 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000913 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000914
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000915 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
916 // ... the address of an object with static storage duration,
917 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
918 return VD->hasGlobalStorage();
919 // ... the address of a function,
920 return isa<FunctionDecl>(D);
921 }
922
923 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000924 switch (E->getStmtClass()) {
925 default:
926 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000927 case Expr::CompoundLiteralExprClass: {
928 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
929 return CLE->isFileScope() && CLE->isLValue();
930 }
Richard Smith180f4792011-11-10 06:34:14 +0000931 // A string literal has static storage duration.
932 case Expr::StringLiteralClass:
933 case Expr::PredefinedExprClass:
934 case Expr::ObjCStringLiteralClass:
935 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000936 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000937 return true;
938 case Expr::CallExprClass:
939 return IsStringLiteralCall(cast<CallExpr>(E));
940 // For GCC compatibility, &&label has static storage duration.
941 case Expr::AddrLabelExprClass:
942 return true;
943 // A Block literal expression may be used as the initialization value for
944 // Block variables at global or local static scope.
945 case Expr::BlockExprClass:
946 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000947 case Expr::ImplicitValueInitExprClass:
948 // FIXME:
949 // We can never form an lvalue with an implicit value initialization as its
950 // base through expression evaluation, so these only appear in one case: the
951 // implicit variable declaration we invent when checking whether a constexpr
952 // constructor can produce a constant expression. We must assume that such
953 // an expression might be a global lvalue.
954 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000955 }
John McCall42c8f872010-05-10 23:27:23 +0000956}
957
Richard Smith83587db2012-02-15 02:18:13 +0000958static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
959 assert(Base && "no location for a null lvalue");
960 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
961 if (VD)
962 Info.Note(VD->getLocation(), diag::note_declared_at);
963 else
964 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
965 diag::note_constexpr_temporary_here);
966}
967
Richard Smith9a17a682011-11-07 05:07:52 +0000968/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000969/// value for an address or reference constant expression. Return true if we
970/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000971static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
972 QualType Type, const LValue &LVal) {
973 bool IsReferenceType = Type->isReferenceType();
974
Richard Smithc1c5f272011-12-13 06:39:58 +0000975 APValue::LValueBase Base = LVal.getLValueBase();
976 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
977
Richard Smithb78ae972012-02-18 04:58:18 +0000978 // Check that the object is a global. Note that the fake 'this' object we
979 // manufacture when checking potential constant expressions is conservatively
980 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000981 if (!IsGlobalLValue(Base)) {
982 if (Info.getLangOpts().CPlusPlus0x) {
983 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000984 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
985 << IsReferenceType << !Designator.Entries.empty()
986 << !!VD << VD;
987 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000988 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000989 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000990 }
Richard Smith61e61622012-01-12 06:08:57 +0000991 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000992 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000993 }
Richard Smith83587db2012-02-15 02:18:13 +0000994 assert((Info.CheckingPotentialConstantExpression ||
995 LVal.getLValueCallIndex() == 0) &&
996 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +0000997
998 // Allow address constant expressions to be past-the-end pointers. This is
999 // an extension: the standard requires them to point to an object.
1000 if (!IsReferenceType)
1001 return true;
1002
1003 // A reference constant expression must refer to an object.
1004 if (!Base) {
1005 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001006 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001007 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001008 }
1009
Richard Smithc1c5f272011-12-13 06:39:58 +00001010 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001011 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001012 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001013 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001014 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001015 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001016 }
1017
Richard Smith9a17a682011-11-07 05:07:52 +00001018 return true;
1019}
1020
Richard Smith51201882011-12-30 21:15:51 +00001021/// Check that this core constant expression is of literal type, and if not,
1022/// produce an appropriate diagnostic.
1023static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1024 if (!E->isRValue() || E->getType()->isLiteralType())
1025 return true;
1026
1027 // Prvalue constant expressions must be of literal types.
1028 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001029 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001030 << E->getType();
1031 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001032 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001033 return false;
1034}
1035
Richard Smith47a1eed2011-10-29 20:57:55 +00001036/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001037/// constant expression. If not, report an appropriate diagnostic. Does not
1038/// check that the expression is of literal type.
1039static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1040 QualType Type, const APValue &Value) {
1041 // Core issue 1454: For a literal constant expression of array or class type,
1042 // each subobject of its value shall have been initialized by a constant
1043 // expression.
1044 if (Value.isArray()) {
1045 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1046 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1047 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1048 Value.getArrayInitializedElt(I)))
1049 return false;
1050 }
1051 if (!Value.hasArrayFiller())
1052 return true;
1053 return CheckConstantExpression(Info, DiagLoc, EltTy,
1054 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001055 }
Richard Smith83587db2012-02-15 02:18:13 +00001056 if (Value.isUnion() && Value.getUnionField()) {
1057 return CheckConstantExpression(Info, DiagLoc,
1058 Value.getUnionField()->getType(),
1059 Value.getUnionValue());
1060 }
1061 if (Value.isStruct()) {
1062 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1063 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1064 unsigned BaseIndex = 0;
1065 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1066 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1067 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1068 Value.getStructBase(BaseIndex)))
1069 return false;
1070 }
1071 }
1072 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1073 I != E; ++I) {
1074 if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
1075 Value.getStructField((*I)->getFieldIndex())))
1076 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>
1162static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1163 const T &SrcValue, QualType DestType) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001164 Info.Diag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001165 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001166 return false;
1167}
1168
1169static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1170 QualType SrcType, const APFloat &Value,
1171 QualType DestType, APSInt &Result) {
1172 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001173 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001174 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Richard Smithc1c5f272011-12-13 06:39:58 +00001176 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001177 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001178 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1179 & APFloat::opInvalidOp)
1180 return HandleOverflow(Info, E, Value, DestType);
1181 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001182}
1183
Richard Smithc1c5f272011-12-13 06:39:58 +00001184static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1185 QualType SrcType, QualType DestType,
1186 APFloat &Result) {
1187 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001188 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001189 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1190 APFloat::rmNearestTiesToEven, &ignored)
1191 & APFloat::opOverflow)
1192 return HandleOverflow(Info, E, Value, DestType);
1193 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001194}
1195
Richard Smithf72fccf2012-01-30 22:27:01 +00001196static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1197 QualType DestType, QualType SrcType,
1198 APSInt &Value) {
1199 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001200 APSInt Result = Value;
1201 // Figure out if this is a truncate, extend or noop cast.
1202 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001203 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001204 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001205 return Result;
1206}
1207
Richard Smithc1c5f272011-12-13 06:39:58 +00001208static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1209 QualType SrcType, const APSInt &Value,
1210 QualType DestType, APFloat &Result) {
1211 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1212 if (Result.convertFromAPInt(Value, Value.isSigned(),
1213 APFloat::rmNearestTiesToEven)
1214 & APFloat::opOverflow)
1215 return HandleOverflow(Info, E, Value, DestType);
1216 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001217}
1218
Eli Friedmane6a24e82011-12-22 03:51:45 +00001219static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1220 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001221 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001222 if (!Evaluate(SVal, Info, E))
1223 return false;
1224 if (SVal.isInt()) {
1225 Res = SVal.getInt();
1226 return true;
1227 }
1228 if (SVal.isFloat()) {
1229 Res = SVal.getFloat().bitcastToAPInt();
1230 return true;
1231 }
1232 if (SVal.isVector()) {
1233 QualType VecTy = E->getType();
1234 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1235 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1236 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1237 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1238 Res = llvm::APInt::getNullValue(VecSize);
1239 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1240 APValue &Elt = SVal.getVectorElt(i);
1241 llvm::APInt EltAsInt;
1242 if (Elt.isInt()) {
1243 EltAsInt = Elt.getInt();
1244 } else if (Elt.isFloat()) {
1245 EltAsInt = Elt.getFloat().bitcastToAPInt();
1246 } else {
1247 // Don't try to handle vectors of anything other than int or float
1248 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001249 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001250 return false;
1251 }
1252 unsigned BaseEltSize = EltAsInt.getBitWidth();
1253 if (BigEndian)
1254 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1255 else
1256 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1257 }
1258 return true;
1259 }
1260 // Give up if the input isn't an int, float, or vector. For example, we
1261 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001262 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001263 return false;
1264}
1265
Richard Smithb4e85ed2012-01-06 16:39:00 +00001266/// Cast an lvalue referring to a base subobject to a derived class, by
1267/// truncating the lvalue's path to the given length.
1268static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1269 const RecordDecl *TruncatedType,
1270 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001271 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001272
1273 // Check we actually point to a derived class object.
1274 if (TruncatedElements == D.Entries.size())
1275 return true;
1276 assert(TruncatedElements >= D.MostDerivedPathLength &&
1277 "not casting to a derived class");
1278 if (!Result.checkSubobject(Info, E, CSK_Derived))
1279 return false;
1280
1281 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001282 const RecordDecl *RD = TruncatedType;
1283 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
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
Richard Smithb4e85ed2012-01-06 16:39:00 +00001296static void 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) {
1300 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1301 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001302 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001303}
1304
Richard Smithb4e85ed2012-01-06 16:39:00 +00001305static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001306 const CXXRecordDecl *DerivedDecl,
1307 const CXXBaseSpecifier *Base) {
1308 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1309
1310 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001311 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001312 return true;
1313 }
1314
Richard Smithb4e85ed2012-01-06 16:39:00 +00001315 SubobjectDesignator &D = Obj.Designator;
1316 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001317 return false;
1318
Richard Smithb4e85ed2012-01-06 16:39:00 +00001319 // Extract most-derived object and corresponding type.
1320 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1321 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1322 return false;
1323
1324 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001325 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1326 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001327 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001328 return true;
1329}
1330
1331/// Update LVal to refer to the given field, which must be a member of the type
1332/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001333static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001334 const FieldDecl *FD,
1335 const ASTRecordLayout *RL = 0) {
1336 if (!RL)
1337 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1338
1339 unsigned I = FD->getFieldIndex();
1340 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001341 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001342}
1343
Richard Smithd9b02e72012-01-25 22:15:11 +00001344/// Update LVal to refer to the given indirect field.
1345static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1346 LValue &LVal,
1347 const IndirectFieldDecl *IFD) {
1348 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1349 CE = IFD->chain_end(); C != CE; ++C)
1350 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1351}
1352
Richard Smith180f4792011-11-10 06:34:14 +00001353/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001354static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1355 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001356 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1357 // extension.
1358 if (Type->isVoidType() || Type->isFunctionType()) {
1359 Size = CharUnits::One();
1360 return true;
1361 }
1362
1363 if (!Type->isConstantSizeType()) {
1364 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001365 // FIXME: Better diagnostic.
1366 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001367 return false;
1368 }
1369
1370 Size = Info.Ctx.getTypeSizeInChars(Type);
1371 return true;
1372}
1373
1374/// Update a pointer value to model pointer arithmetic.
1375/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001376/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001377/// \param LVal - The pointer value to be updated.
1378/// \param EltTy - The pointee type represented by LVal.
1379/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001380static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1381 LValue &LVal, QualType EltTy,
1382 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001383 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001384 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001385 return false;
1386
1387 // Compute the new offset in the appropriate width.
1388 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001389 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001390 return true;
1391}
1392
Richard Smith86024012012-02-18 22:04:06 +00001393/// Update an lvalue to refer to a component of a complex number.
1394/// \param Info - Information about the ongoing evaluation.
1395/// \param LVal - The lvalue to be updated.
1396/// \param EltTy - The complex number's component type.
1397/// \param Imag - False for the real component, true for the imaginary.
1398static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1399 LValue &LVal, QualType EltTy,
1400 bool Imag) {
1401 if (Imag) {
1402 CharUnits SizeOfComponent;
1403 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1404 return false;
1405 LVal.Offset += SizeOfComponent;
1406 }
1407 LVal.addComplex(Info, E, EltTy, Imag);
1408 return true;
1409}
1410
Richard Smith03f96112011-10-24 17:54:18 +00001411/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001412static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1413 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001414 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001415 // If this is a parameter to an active constexpr function call, perform
1416 // argument substitution.
1417 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001418 // Assume arguments of a potential constant expression are unknown
1419 // constant expressions.
1420 if (Info.CheckingPotentialConstantExpression)
1421 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001422 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001423 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001424 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001425 }
Richard Smith177dce72011-11-01 16:57:24 +00001426 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1427 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001428 }
Richard Smith03f96112011-10-24 17:54:18 +00001429
Richard Smith099e7f62011-12-19 06:19:21 +00001430 // Dig out the initializer, and use the declaration which it's attached to.
1431 const Expr *Init = VD->getAnyInitializer(VD);
1432 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001433 // If we're checking a potential constant expression, the variable could be
1434 // initialized later.
1435 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001436 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001437 return false;
1438 }
1439
Richard Smith180f4792011-11-10 06:34:14 +00001440 // If we're currently evaluating the initializer of this declaration, use that
1441 // in-flight value.
1442 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001443 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001444 return !Result.isUninit();
1445 }
1446
Richard Smith65ac5982011-11-01 21:06:14 +00001447 // Never evaluate the initializer of a weak variable. We can't be sure that
1448 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001449 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001450 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001451 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001452 }
Richard Smith65ac5982011-11-01 21:06:14 +00001453
Richard Smith099e7f62011-12-19 06:19:21 +00001454 // Check that we can fold the initializer. In C++, we will have already done
1455 // this in the cases where it matters for conformance.
1456 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1457 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001458 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001459 Notes.size() + 1) << VD;
1460 Info.Note(VD->getLocation(), diag::note_declared_at);
1461 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001462 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001463 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001464 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001465 Notes.size() + 1) << VD;
1466 Info.Note(VD->getLocation(), diag::note_declared_at);
1467 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001468 }
Richard Smith03f96112011-10-24 17:54:18 +00001469
Richard Smith1aa0be82012-03-03 22:46:17 +00001470 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001471 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001472}
1473
Richard Smithc49bd112011-10-28 17:51:58 +00001474static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001475 Qualifiers Quals = T.getQualifiers();
1476 return Quals.hasConst() && !Quals.hasVolatile();
1477}
1478
Richard Smith59efe262011-11-11 04:05:33 +00001479/// Get the base index of the given base class within an APValue representing
1480/// the given derived class.
1481static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1482 const CXXRecordDecl *Base) {
1483 Base = Base->getCanonicalDecl();
1484 unsigned Index = 0;
1485 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1486 E = Derived->bases_end(); I != E; ++I, ++Index) {
1487 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1488 return Index;
1489 }
1490
1491 llvm_unreachable("base class missing from derived class's bases list");
1492}
1493
Richard Smithf3908f22012-02-17 03:35:37 +00001494/// Extract the value of a character from a string literal.
1495static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1496 uint64_t Index) {
1497 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1498 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1499 assert(S && "unexpected string literal expression kind");
1500
1501 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1502 Lit->getType()->getArrayElementTypeNoTypeQual()->isUnsignedIntegerType());
1503 if (Index < S->getLength())
1504 Value = S->getCodeUnit(Index);
1505 return Value;
1506}
1507
Richard Smithcc5d4f62011-11-07 09:22:26 +00001508/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001509static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001510 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001511 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001512 if (Sub.Invalid)
1513 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001514 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001515 if (Sub.isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001516 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001517 (unsigned)diag::note_constexpr_read_past_end :
1518 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001519 return false;
1520 }
Richard Smithf64699e2011-11-11 08:28:03 +00001521 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001522 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001523 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1524 // This object might be initialized later.
1525 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001526
Richard Smith0069b842012-03-10 00:28:11 +00001527 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001528 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001529 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001530 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001531 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001532 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001533 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001534 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001535 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001536 // Note, it should not be possible to form a pointer with a valid
1537 // designator which points more than one past the end of the array.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001538 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001539 (unsigned)diag::note_constexpr_read_past_end :
1540 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001541 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001542 }
Richard Smithf3908f22012-02-17 03:35:37 +00001543 // An array object is represented as either an Array APValue or as an
1544 // LValue which refers to a string literal.
1545 if (O->isLValue()) {
1546 assert(I == N - 1 && "extracting subobject of character?");
1547 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001548 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithf3908f22012-02-17 03:35:37 +00001549 Info, O->getLValueBase().get<const Expr*>(), Index));
1550 return true;
1551 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001552 O = &O->getArrayInitializedElt(Index);
1553 else
1554 O = &O->getArrayFiller();
1555 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001556 } else if (ObjType->isAnyComplexType()) {
1557 // Next subobject is a complex number.
1558 uint64_t Index = Sub.Entries[I].ArrayIndex;
1559 if (Index > 1) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001560 Info.Diag(E, Info.getLangOpts().CPlusPlus0x ?
Richard Smith86024012012-02-18 22:04:06 +00001561 (unsigned)diag::note_constexpr_read_past_end :
1562 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1563 return false;
1564 }
1565 assert(I == N - 1 && "extracting subobject of scalar?");
1566 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001567 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001568 : O->getComplexIntReal());
1569 } else {
1570 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001571 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001572 : O->getComplexFloatReal());
1573 }
1574 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001575 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001576 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001577 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001578 << Field;
1579 Info.Note(Field->getLocation(), diag::note_declared_at);
1580 return false;
1581 }
1582
Richard Smith180f4792011-11-10 06:34:14 +00001583 // Next subobject is a class, struct or union field.
1584 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1585 if (RD->isUnion()) {
1586 const FieldDecl *UnionField = O->getUnionField();
1587 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001588 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001589 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001590 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001591 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001592 }
Richard Smith180f4792011-11-10 06:34:14 +00001593 O = &O->getUnionValue();
1594 } else
1595 O = &O->getStructField(Field->getFieldIndex());
1596 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001597
1598 if (ObjType.isVolatileQualified()) {
1599 if (Info.getLangOpts().CPlusPlus) {
1600 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001601 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001602 << 2 << Field;
1603 Info.Note(Field->getLocation(), diag::note_declared_at);
1604 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001605 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001606 }
1607 return false;
1608 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001609 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001610 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001611 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1612 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1613 O = &O->getStructBase(getBaseIndex(Derived, Base));
1614 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001615 }
Richard Smith180f4792011-11-10 06:34:14 +00001616
Richard Smithf48fdb02011-12-09 22:58:01 +00001617 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001618 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001619 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001620 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001621 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001622 }
1623
Richard Smith0069b842012-03-10 00:28:11 +00001624 // This may look super-stupid, but it serves an important purpose: if we just
1625 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1626 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1627 // object, which is destroyed by Tmp's destructor.
1628 APValue Tmp;
1629 O->swap(Tmp);
1630 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001631 return true;
1632}
1633
Richard Smithf15fda02012-02-02 01:16:57 +00001634/// Find the position where two subobject designators diverge, or equivalently
1635/// the length of the common initial subsequence.
1636static unsigned FindDesignatorMismatch(QualType ObjType,
1637 const SubobjectDesignator &A,
1638 const SubobjectDesignator &B,
1639 bool &WasArrayIndex) {
1640 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1641 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001642 if (!ObjType.isNull() &&
1643 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001644 // Next subobject is an array element.
1645 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1646 WasArrayIndex = true;
1647 return I;
1648 }
Richard Smith86024012012-02-18 22:04:06 +00001649 if (ObjType->isAnyComplexType())
1650 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1651 else
1652 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001653 } else {
1654 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1655 WasArrayIndex = false;
1656 return I;
1657 }
1658 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1659 // Next subobject is a field.
1660 ObjType = FD->getType();
1661 else
1662 // Next subobject is a base class.
1663 ObjType = QualType();
1664 }
1665 }
1666 WasArrayIndex = false;
1667 return I;
1668}
1669
1670/// Determine whether the given subobject designators refer to elements of the
1671/// same array object.
1672static bool AreElementsOfSameArray(QualType ObjType,
1673 const SubobjectDesignator &A,
1674 const SubobjectDesignator &B) {
1675 if (A.Entries.size() != B.Entries.size())
1676 return false;
1677
1678 bool IsArray = A.MostDerivedArraySize != 0;
1679 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1680 // A is a subobject of the array element.
1681 return false;
1682
1683 // If A (and B) designates an array element, the last entry will be the array
1684 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1685 // of length 1' case, and the entire path must match.
1686 bool WasArrayIndex;
1687 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1688 return CommonLength >= A.Entries.size() - IsArray;
1689}
1690
Richard Smith180f4792011-11-10 06:34:14 +00001691/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1692/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1693/// for looking up the glvalue referred to by an entity of reference type.
1694///
1695/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001696/// \param Conv - The expression for which we are performing the conversion.
1697/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001698/// \param Type - The type we expect this conversion to produce, before
1699/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001700/// \param LVal - The glvalue on which we are attempting to perform this action.
1701/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001702static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1703 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001704 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001705 if (LVal.Designator.Invalid)
1706 // A diagnostic will have already been produced.
1707 return false;
1708
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001709 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001710
Richard Smithf48fdb02011-12-09 22:58:01 +00001711 if (!LVal.Base) {
1712 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001713 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001714 return false;
1715 }
1716
Richard Smith83587db2012-02-15 02:18:13 +00001717 CallStackFrame *Frame = 0;
1718 if (LVal.CallIndex) {
1719 Frame = Info.getCallFrame(LVal.CallIndex);
1720 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001721 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001722 NoteLValueLocation(Info, LVal.Base);
1723 return false;
1724 }
1725 }
1726
Richard Smith7098cbd2011-12-21 05:04:46 +00001727 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1728 // is not a constant expression (even if the object is non-volatile). We also
1729 // apply this rule to C++98, in order to conform to the expected 'volatile'
1730 // semantics.
1731 if (Type.isVolatileQualified()) {
1732 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001733 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001734 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001735 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001736 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001737 }
Richard Smithc49bd112011-10-28 17:51:58 +00001738
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001739 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001740 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1741 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001742 // expressions are constant expressions too. Inside constexpr functions,
1743 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001744 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001745 const VarDecl *VD = dyn_cast<VarDecl>(D);
Daniel Dunbar3d13c5a2012-03-09 01:51:51 +00001746 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
Richard Smithf15fda02012-02-02 01:16:57 +00001747 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001748 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001749 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001750 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001751 }
1752
Richard Smith7098cbd2011-12-21 05:04:46 +00001753 // DR1313: If the object is volatile-qualified but the glvalue was not,
1754 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001755 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001756 if (VT.isVolatileQualified()) {
1757 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001758 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001759 Info.Note(VD->getLocation(), diag::note_declared_at);
1760 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001761 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001762 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001763 return false;
1764 }
1765
1766 if (!isa<ParmVarDecl>(VD)) {
1767 if (VD->isConstexpr()) {
1768 // OK, we can read this variable.
1769 } else if (VT->isIntegralOrEnumerationType()) {
1770 if (!VT.isConstQualified()) {
1771 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001772 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001773 Info.Note(VD->getLocation(), diag::note_declared_at);
1774 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001775 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001776 }
1777 return false;
1778 }
1779 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1780 // We support folding of const floating-point types, in order to make
1781 // static const data members of such types (supported as an extension)
1782 // more useful.
1783 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001784 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001785 Info.Note(VD->getLocation(), diag::note_declared_at);
1786 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001787 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001788 }
1789 } else {
1790 // FIXME: Allow folding of values of any literal type in all languages.
1791 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001792 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001793 Info.Note(VD->getLocation(), diag::note_declared_at);
1794 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001795 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001796 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001797 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001798 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001799 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001800
Richard Smithf48fdb02011-12-09 22:58:01 +00001801 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001802 return false;
1803
Richard Smith47a1eed2011-10-29 20:57:55 +00001804 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001805 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001806
1807 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1808 // conversion. This happens when the declaration and the lvalue should be
1809 // considered synonymous, for instance when initializing an array of char
1810 // from a string literal. Continue as if the initializer lvalue was the
1811 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001812 assert(RVal.getLValueOffset().isZero() &&
1813 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001814 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001815
1816 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1817 Frame = Info.getCallFrame(CallIndex);
1818 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001819 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001820 NoteLValueLocation(Info, RVal.getLValueBase());
1821 return false;
1822 }
1823 } else {
1824 Frame = 0;
1825 }
Richard Smithc49bd112011-10-28 17:51:58 +00001826 }
1827
Richard Smith7098cbd2011-12-21 05:04:46 +00001828 // Volatile temporary objects cannot be read in constant expressions.
1829 if (Base->getType().isVolatileQualified()) {
1830 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001831 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001832 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1833 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001834 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001835 }
1836 return false;
1837 }
1838
Richard Smithcc5d4f62011-11-07 09:22:26 +00001839 if (Frame) {
1840 // If this is a temporary expression with a nontrivial initializer, grab the
1841 // value from the relevant stack frame.
1842 RVal = Frame->Temporaries[Base];
1843 } else if (const CompoundLiteralExpr *CLE
1844 = dyn_cast<CompoundLiteralExpr>(Base)) {
1845 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1846 // initializer until now for such expressions. Such an expression can't be
1847 // an ICE in C, so this only matters for fold.
1848 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1849 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1850 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001851 } else if (isa<StringLiteral>(Base)) {
1852 // We represent a string literal array as an lvalue pointing at the
1853 // corresponding expression, rather than building an array of chars.
1854 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001855 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001856 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001857 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001858 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001859 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001860
Richard Smithf48fdb02011-12-09 22:58:01 +00001861 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1862 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001863}
1864
Richard Smith59efe262011-11-11 04:05:33 +00001865/// Build an lvalue for the object argument of a member function call.
1866static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1867 LValue &This) {
1868 if (Object->getType()->isPointerType())
1869 return EvaluatePointer(Object, This, Info);
1870
1871 if (Object->isGLValue())
1872 return EvaluateLValue(Object, This, Info);
1873
Richard Smithe24f5fc2011-11-17 22:56:20 +00001874 if (Object->getType()->isLiteralType())
1875 return EvaluateTemporary(Object, This, Info);
1876
1877 return false;
1878}
1879
1880/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1881/// lvalue referring to the result.
1882///
1883/// \param Info - Information about the ongoing evaluation.
1884/// \param BO - The member pointer access operation.
1885/// \param LV - Filled in with a reference to the resulting object.
1886/// \param IncludeMember - Specifies whether the member itself is included in
1887/// the resulting LValue subobject designator. This is not possible when
1888/// creating a bound member function.
1889/// \return The field or method declaration to which the member pointer refers,
1890/// or 0 if evaluation fails.
1891static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1892 const BinaryOperator *BO,
1893 LValue &LV,
1894 bool IncludeMember = true) {
1895 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1896
Richard Smith745f5142012-01-27 01:14:48 +00001897 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1898 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001899 return 0;
1900
1901 MemberPtr MemPtr;
1902 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1903 return 0;
1904
1905 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1906 // member value, the behavior is undefined.
1907 if (!MemPtr.getDecl())
1908 return 0;
1909
Richard Smith745f5142012-01-27 01:14:48 +00001910 if (!EvalObjOK)
1911 return 0;
1912
Richard Smithe24f5fc2011-11-17 22:56:20 +00001913 if (MemPtr.isDerivedMember()) {
1914 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001915 // The end of the derived-to-base path for the base object must match the
1916 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001917 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001918 LV.Designator.Entries.size())
1919 return 0;
1920 unsigned PathLengthToMember =
1921 LV.Designator.Entries.size() - MemPtr.Path.size();
1922 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1923 const CXXRecordDecl *LVDecl = getAsBaseClass(
1924 LV.Designator.Entries[PathLengthToMember + I]);
1925 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1926 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1927 return 0;
1928 }
1929
1930 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001931 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1932 PathLengthToMember))
1933 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001934 } else if (!MemPtr.Path.empty()) {
1935 // Extend the LValue path with the member pointer's path.
1936 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1937 MemPtr.Path.size() + IncludeMember);
1938
1939 // Walk down to the appropriate base class.
1940 QualType LVType = BO->getLHS()->getType();
1941 if (const PointerType *PT = LVType->getAs<PointerType>())
1942 LVType = PT->getPointeeType();
1943 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1944 assert(RD && "member pointer access on non-class-type expression");
1945 // The first class in the path is that of the lvalue.
1946 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1947 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00001948 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001949 RD = Base;
1950 }
1951 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001952 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00001953 }
1954
1955 // Add the member. Note that we cannot build bound member functions here.
1956 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00001957 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
1958 HandleLValueMember(Info, BO, LV, FD);
1959 else if (const IndirectFieldDecl *IFD =
1960 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
1961 HandleLValueIndirectMember(Info, BO, LV, IFD);
1962 else
1963 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00001964 }
1965
1966 return MemPtr.getDecl();
1967}
1968
1969/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1970/// the provided lvalue, which currently refers to the base object.
1971static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
1972 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001973 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001974 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00001975 return false;
1976
Richard Smithb4e85ed2012-01-06 16:39:00 +00001977 QualType TargetQT = E->getType();
1978 if (const PointerType *PT = TargetQT->getAs<PointerType>())
1979 TargetQT = PT->getPointeeType();
1980
1981 // Check this cast lands within the final derived-to-base subobject path.
1982 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001983 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00001984 << D.MostDerivedType << TargetQT;
1985 return false;
1986 }
1987
Richard Smithe24f5fc2011-11-17 22:56:20 +00001988 // Check the type of the final cast. We don't need to check the path,
1989 // since a cast can only be formed if the path is unique.
1990 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00001991 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
1992 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001993 if (NewEntriesSize == D.MostDerivedPathLength)
1994 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
1995 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00001996 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001997 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001998 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00001999 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002000 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002001 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002002
2003 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002004 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002005}
2006
Mike Stumpc4c90452009-10-27 22:09:17 +00002007namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002008enum EvalStmtResult {
2009 /// Evaluation failed.
2010 ESR_Failed,
2011 /// Hit a 'return' statement.
2012 ESR_Returned,
2013 /// Evaluation succeeded.
2014 ESR_Succeeded
2015};
2016}
2017
2018// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002019static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002020 const Stmt *S) {
2021 switch (S->getStmtClass()) {
2022 default:
2023 return ESR_Failed;
2024
2025 case Stmt::NullStmtClass:
2026 case Stmt::DeclStmtClass:
2027 return ESR_Succeeded;
2028
Richard Smithc1c5f272011-12-13 06:39:58 +00002029 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002030 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002031 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002032 return ESR_Failed;
2033 return ESR_Returned;
2034 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002035
2036 case Stmt::CompoundStmtClass: {
2037 const CompoundStmt *CS = cast<CompoundStmt>(S);
2038 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2039 BE = CS->body_end(); BI != BE; ++BI) {
2040 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2041 if (ESR != ESR_Succeeded)
2042 return ESR;
2043 }
2044 return ESR_Succeeded;
2045 }
2046 }
2047}
2048
Richard Smith61802452011-12-22 02:22:31 +00002049/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2050/// default constructor. If so, we'll fold it whether or not it's marked as
2051/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2052/// so we need special handling.
2053static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002054 const CXXConstructorDecl *CD,
2055 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002056 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2057 return false;
2058
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002059 // Value-initialization does not call a trivial default constructor, so such a
2060 // call is a core constant expression whether or not the constructor is
2061 // constexpr.
2062 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002063 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002064 // FIXME: If DiagDecl is an implicitly-declared special member function,
2065 // we should be much more explicit about why it's not constexpr.
2066 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2067 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2068 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002069 } else {
2070 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2071 }
2072 }
2073 return true;
2074}
2075
Richard Smithc1c5f272011-12-13 06:39:58 +00002076/// CheckConstexprFunction - Check that a function can be called in a constant
2077/// expression.
2078static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2079 const FunctionDecl *Declaration,
2080 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002081 // Potential constant expressions can contain calls to declared, but not yet
2082 // defined, constexpr functions.
2083 if (Info.CheckingPotentialConstantExpression && !Definition &&
2084 Declaration->isConstexpr())
2085 return false;
2086
Richard Smithc1c5f272011-12-13 06:39:58 +00002087 // Can we evaluate this function call?
2088 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2089 return true;
2090
2091 if (Info.getLangOpts().CPlusPlus0x) {
2092 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002093 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2094 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002095 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2096 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2097 << DiagDecl;
2098 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2099 } else {
2100 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2101 }
2102 return false;
2103}
2104
Richard Smith180f4792011-11-10 06:34:14 +00002105namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002106typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002107}
2108
2109/// EvaluateArgs - Evaluate the arguments to a function call.
2110static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2111 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002112 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002113 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002114 I != E; ++I) {
2115 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2116 // If we're checking for a potential constant expression, evaluate all
2117 // initializers even if some of them fail.
2118 if (!Info.keepEvaluatingAfterFailure())
2119 return false;
2120 Success = false;
2121 }
2122 }
2123 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002124}
2125
Richard Smithd0dccea2011-10-28 22:34:42 +00002126/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002127static bool HandleFunctionCall(SourceLocation CallLoc,
2128 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002129 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002130 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002131 ArgVector ArgValues(Args.size());
2132 if (!EvaluateArgs(Args, ArgValues, Info))
2133 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002134
Richard Smith745f5142012-01-27 01:14:48 +00002135 if (!Info.CheckCallLimit(CallLoc))
2136 return false;
2137
2138 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002139 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2140}
2141
Richard Smith180f4792011-11-10 06:34:14 +00002142/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002143static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002144 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002145 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002146 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002147 ArgVector ArgValues(Args.size());
2148 if (!EvaluateArgs(Args, ArgValues, Info))
2149 return false;
2150
Richard Smith745f5142012-01-27 01:14:48 +00002151 if (!Info.CheckCallLimit(CallLoc))
2152 return false;
2153
Richard Smith86c3ae42012-02-13 03:54:03 +00002154 const CXXRecordDecl *RD = Definition->getParent();
2155 if (RD->getNumVBases()) {
2156 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2157 return false;
2158 }
2159
Richard Smith745f5142012-01-27 01:14:48 +00002160 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002161
2162 // If it's a delegating constructor, just delegate.
2163 if (Definition->isDelegatingConstructor()) {
2164 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002165 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002166 }
2167
Richard Smith610a60c2012-01-10 04:32:03 +00002168 // For a trivial copy or move constructor, perform an APValue copy. This is
2169 // essential for unions, where the operations performed by the constructor
2170 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002171 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002172 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2173 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002174 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002175 RHS.setFrom(Info.Ctx, ArgValues[0]);
2176 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2177 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002178 }
2179
2180 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002181 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002182 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2183 std::distance(RD->field_begin(), RD->field_end()));
2184
2185 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2186
Richard Smith745f5142012-01-27 01:14:48 +00002187 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002188 unsigned BasesSeen = 0;
2189#ifndef NDEBUG
2190 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2191#endif
2192 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2193 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002194 LValue Subobject = This;
2195 APValue *Value = &Result;
2196
2197 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002198 if ((*I)->isBaseInitializer()) {
2199 QualType BaseType((*I)->getBaseClass(), 0);
2200#ifndef NDEBUG
2201 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002202 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002203 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2204 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2205 "base class initializers not in expected order");
2206 ++BaseIt;
2207#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002208 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002209 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002210 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002211 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002212 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002213 if (RD->isUnion()) {
2214 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002215 Value = &Result.getUnionValue();
2216 } else {
2217 Value = &Result.getStructField(FD->getFieldIndex());
2218 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002219 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002220 // Walk the indirect field decl's chain to find the object to initialize,
2221 // and make sure we've initialized every step along it.
2222 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2223 CE = IFD->chain_end();
2224 C != CE; ++C) {
2225 FieldDecl *FD = cast<FieldDecl>(*C);
2226 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2227 // Switch the union field if it differs. This happens if we had
2228 // preceding zero-initialization, and we're now initializing a union
2229 // subobject other than the first.
2230 // FIXME: In this case, the values of the other subobjects are
2231 // specified, since zero-initialization sets all padding bits to zero.
2232 if (Value->isUninit() ||
2233 (Value->isUnion() && Value->getUnionField() != FD)) {
2234 if (CD->isUnion())
2235 *Value = APValue(FD);
2236 else
2237 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2238 std::distance(CD->field_begin(), CD->field_end()));
2239 }
Richard Smith745f5142012-01-27 01:14:48 +00002240 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002241 if (CD->isUnion())
2242 Value = &Value->getUnionValue();
2243 else
2244 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002245 }
Richard Smith180f4792011-11-10 06:34:14 +00002246 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002247 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002248 }
Richard Smith745f5142012-01-27 01:14:48 +00002249
Richard Smith83587db2012-02-15 02:18:13 +00002250 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2251 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002252 ? CCEK_Constant : CCEK_MemberInit)) {
2253 // If we're checking for a potential constant expression, evaluate all
2254 // initializers even if some of them fail.
2255 if (!Info.keepEvaluatingAfterFailure())
2256 return false;
2257 Success = false;
2258 }
Richard Smith180f4792011-11-10 06:34:14 +00002259 }
2260
Richard Smith745f5142012-01-27 01:14:48 +00002261 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002262}
2263
Richard Smithd0dccea2011-10-28 22:34:42 +00002264namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002265class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002266 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002267 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002268public:
2269
Richard Smith1e12c592011-10-16 21:26:27 +00002270 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002271
2272 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002273 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002274 return true;
2275 }
2276
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002277 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2278 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002279 return Visit(E->getResultExpr());
2280 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002281 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002282 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002283 return true;
2284 return false;
2285 }
John McCallf85e1932011-06-15 23:02:42 +00002286 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002287 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002288 return true;
2289 return false;
2290 }
John McCallf85e1932011-06-15 23:02:42 +00002291
Mike Stumpc4c90452009-10-27 22:09:17 +00002292 // We don't want to evaluate BlockExprs multiple times, as they generate
2293 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002294 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2295 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2296 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002297 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002298 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2299 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2300 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2301 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2302 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2303 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002304 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002305 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002306 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002307 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002308 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002309 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2310 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2311 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2312 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002313 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002314 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2315 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2316 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2317 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2318 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002319 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002320 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002321 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002322 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002323 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002324
2325 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002326 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002327 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2328 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002329 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002330 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002331 return false;
2332 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002333
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002334 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002335};
2336
John McCall56ca35d2011-02-17 10:25:35 +00002337class OpaqueValueEvaluation {
2338 EvalInfo &info;
2339 OpaqueValueExpr *opaqueValue;
2340
2341public:
2342 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2343 Expr *value)
2344 : info(info), opaqueValue(opaqueValue) {
2345
2346 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002347 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002348 this->opaqueValue = 0;
2349 return;
2350 }
John McCall56ca35d2011-02-17 10:25:35 +00002351 }
2352
2353 bool hasError() const { return opaqueValue == 0; }
2354
2355 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002356 // FIXME: For a recursive constexpr call, an outer stack frame might have
2357 // been using this opaque value too, and will now have to re-evaluate the
2358 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002359 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2360 }
2361};
2362
Mike Stumpc4c90452009-10-27 22:09:17 +00002363} // end anonymous namespace
2364
Eli Friedman4efaa272008-11-12 09:44:48 +00002365//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002366// Generic Evaluation
2367//===----------------------------------------------------------------------===//
2368namespace {
2369
Richard Smithf48fdb02011-12-09 22:58:01 +00002370// FIXME: RetTy is always bool. Remove it.
2371template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002372class ExprEvaluatorBase
2373 : public ConstStmtVisitor<Derived, RetTy> {
2374private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002375 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002376 return static_cast<Derived*>(this)->Success(V, E);
2377 }
Richard Smith51201882011-12-30 21:15:51 +00002378 RetTy DerivedZeroInitialization(const Expr *E) {
2379 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002380 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002381
Richard Smith74e1ad92012-02-16 02:46:34 +00002382 // Check whether a conditional operator with a non-constant condition is a
2383 // potential constant expression. If neither arm is a potential constant
2384 // expression, then the conditional operator is not either.
2385 template<typename ConditionalOperator>
2386 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2387 assert(Info.CheckingPotentialConstantExpression);
2388
2389 // Speculatively evaluate both arms.
2390 {
2391 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2392 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2393
2394 StmtVisitorTy::Visit(E->getFalseExpr());
2395 if (Diag.empty())
2396 return;
2397
2398 Diag.clear();
2399 StmtVisitorTy::Visit(E->getTrueExpr());
2400 if (Diag.empty())
2401 return;
2402 }
2403
2404 Error(E, diag::note_constexpr_conditional_never_const);
2405 }
2406
2407
2408 template<typename ConditionalOperator>
2409 bool HandleConditionalOperator(const ConditionalOperator *E) {
2410 bool BoolResult;
2411 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2412 if (Info.CheckingPotentialConstantExpression)
2413 CheckPotentialConstantConditional(E);
2414 return false;
2415 }
2416
2417 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2418 return StmtVisitorTy::Visit(EvalExpr);
2419 }
2420
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002421protected:
2422 EvalInfo &Info;
2423 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2424 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2425
Richard Smithdd1f29b2011-12-12 09:28:41 +00002426 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002427 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002428 }
2429
2430 /// Report an evaluation error. This should only be called when an error is
2431 /// first discovered. When propagating an error, just return false.
2432 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002433 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002434 return false;
2435 }
2436 bool Error(const Expr *E) {
2437 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2438 }
2439
Richard Smith51201882011-12-30 21:15:51 +00002440 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002441
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002442public:
2443 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2444
2445 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002446 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002447 }
2448 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002449 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002450 }
2451
2452 RetTy VisitParenExpr(const ParenExpr *E)
2453 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2454 RetTy VisitUnaryExtension(const UnaryOperator *E)
2455 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2456 RetTy VisitUnaryPlus(const UnaryOperator *E)
2457 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2458 RetTy VisitChooseExpr(const ChooseExpr *E)
2459 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2460 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2461 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002462 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2463 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002464 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2465 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002466 // We cannot create any objects for which cleanups are required, so there is
2467 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2468 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2469 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002470
Richard Smithc216a012011-12-12 12:46:16 +00002471 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2472 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2473 return static_cast<Derived*>(this)->VisitCastExpr(E);
2474 }
2475 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2476 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2477 return static_cast<Derived*>(this)->VisitCastExpr(E);
2478 }
2479
Richard Smithe24f5fc2011-11-17 22:56:20 +00002480 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2481 switch (E->getOpcode()) {
2482 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002483 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002484
2485 case BO_Comma:
2486 VisitIgnoredValue(E->getLHS());
2487 return StmtVisitorTy::Visit(E->getRHS());
2488
2489 case BO_PtrMemD:
2490 case BO_PtrMemI: {
2491 LValue Obj;
2492 if (!HandleMemberPointerAccess(Info, E, Obj))
2493 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002494 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002495 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002496 return false;
2497 return DerivedSuccess(Result, E);
2498 }
2499 }
2500 }
2501
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002502 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002503 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002504 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2505 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002506 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002507
Richard Smith74e1ad92012-02-16 02:46:34 +00002508 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002509 }
2510
2511 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002512 bool IsBcpCall = false;
2513 // If the condition (ignoring parens) is a __builtin_constant_p call,
2514 // the result is a constant expression if it can be folded without
2515 // side-effects. This is an important GNU extension. See GCC PR38377
2516 // for discussion.
2517 if (const CallExpr *CallCE =
2518 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2519 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2520 IsBcpCall = true;
2521
2522 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2523 // constant expression; we can't check whether it's potentially foldable.
2524 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2525 return false;
2526
2527 FoldConstant Fold(Info);
2528
Richard Smith74e1ad92012-02-16 02:46:34 +00002529 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002530 return false;
2531
2532 if (IsBcpCall)
2533 Fold.Fold(Info);
2534
2535 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002536 }
2537
2538 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002539 const APValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002540 if (!Value) {
2541 const Expr *Source = E->getSourceExpr();
2542 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002543 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002544 if (Source == E) { // sanity checking.
2545 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002546 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002547 }
2548 return StmtVisitorTy::Visit(Source);
2549 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002550 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002551 }
Richard Smithf10d9172011-10-11 21:43:33 +00002552
Richard Smithd0dccea2011-10-28 22:34:42 +00002553 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002554 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002555 QualType CalleeType = Callee->getType();
2556
Richard Smithd0dccea2011-10-28 22:34:42 +00002557 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002558 LValue *This = 0, ThisVal;
2559 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002560 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002561
Richard Smith59efe262011-11-11 04:05:33 +00002562 // Extract function decl and 'this' pointer from the callee.
2563 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002564 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002565 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2566 // Explicit bound member calls, such as x.f() or p->g();
2567 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002568 return false;
2569 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002570 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002571 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002572 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2573 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002574 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2575 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002576 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002577 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002578 return Error(Callee);
2579
2580 FD = dyn_cast<FunctionDecl>(Member);
2581 if (!FD)
2582 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002583 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002584 LValue Call;
2585 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002586 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002587
Richard Smithb4e85ed2012-01-06 16:39:00 +00002588 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002589 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002590 FD = dyn_cast_or_null<FunctionDecl>(
2591 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002592 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002593 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002594
2595 // Overloaded operator calls to member functions are represented as normal
2596 // calls with '*this' as the first argument.
2597 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2598 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002599 // FIXME: When selecting an implicit conversion for an overloaded
2600 // operator delete, we sometimes try to evaluate calls to conversion
2601 // operators without a 'this' parameter!
2602 if (Args.empty())
2603 return Error(E);
2604
Richard Smith59efe262011-11-11 04:05:33 +00002605 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2606 return false;
2607 This = &ThisVal;
2608 Args = Args.slice(1);
2609 }
2610
2611 // Don't call function pointers which have been cast to some other type.
2612 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002613 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002614 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002615 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002616
Richard Smithb04035a2012-02-01 02:39:43 +00002617 if (This && !This->checkSubobject(Info, E, CSK_This))
2618 return false;
2619
Richard Smith86c3ae42012-02-13 03:54:03 +00002620 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2621 // calls to such functions in constant expressions.
2622 if (This && !HasQualifier &&
2623 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2624 return Error(E, diag::note_constexpr_virtual_call);
2625
Richard Smithc1c5f272011-12-13 06:39:58 +00002626 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002627 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002628 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002629
Richard Smithc1c5f272011-12-13 06:39:58 +00002630 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002631 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2632 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002633 return false;
2634
Richard Smith83587db2012-02-15 02:18:13 +00002635 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002636 }
2637
Richard Smithc49bd112011-10-28 17:51:58 +00002638 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2639 return StmtVisitorTy::Visit(E->getInitializer());
2640 }
Richard Smithf10d9172011-10-11 21:43:33 +00002641 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002642 if (E->getNumInits() == 0)
2643 return DerivedZeroInitialization(E);
2644 if (E->getNumInits() == 1)
2645 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002646 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002647 }
2648 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002649 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002650 }
2651 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002652 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002653 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002654 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002655 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002656 }
Richard Smithf10d9172011-10-11 21:43:33 +00002657
Richard Smith180f4792011-11-10 06:34:14 +00002658 /// A member expression where the object is a prvalue is itself a prvalue.
2659 RetTy VisitMemberExpr(const MemberExpr *E) {
2660 assert(!E->isArrow() && "missing call to bound member function?");
2661
Richard Smith1aa0be82012-03-03 22:46:17 +00002662 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002663 if (!Evaluate(Val, Info, E->getBase()))
2664 return false;
2665
2666 QualType BaseTy = E->getBase()->getType();
2667
2668 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002669 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002670 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2671 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2672 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2673
Richard Smithb4e85ed2012-01-06 16:39:00 +00002674 SubobjectDesignator Designator(BaseTy);
2675 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002676
Richard Smithf48fdb02011-12-09 22:58:01 +00002677 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002678 DerivedSuccess(Val, E);
2679 }
2680
Richard Smithc49bd112011-10-28 17:51:58 +00002681 RetTy VisitCastExpr(const CastExpr *E) {
2682 switch (E->getCastKind()) {
2683 default:
2684 break;
2685
David Chisnall7a7ee302012-01-16 17:27:18 +00002686 case CK_AtomicToNonAtomic:
2687 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002688 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002689 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002690 return StmtVisitorTy::Visit(E->getSubExpr());
2691
2692 case CK_LValueToRValue: {
2693 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002694 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2695 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002696 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002697 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2698 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2699 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002700 return false;
2701 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002702 }
2703 }
2704
Richard Smithf48fdb02011-12-09 22:58:01 +00002705 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002706 }
2707
Richard Smith8327fad2011-10-24 18:44:57 +00002708 /// Visit a value which is evaluated, but whose value is ignored.
2709 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002710 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002711 if (!Evaluate(Scratch, Info, E))
2712 Info.EvalStatus.HasSideEffects = true;
2713 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002714};
2715
2716}
2717
2718//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002719// Common base class for lvalue and temporary evaluation.
2720//===----------------------------------------------------------------------===//
2721namespace {
2722template<class Derived>
2723class LValueExprEvaluatorBase
2724 : public ExprEvaluatorBase<Derived, bool> {
2725protected:
2726 LValue &Result;
2727 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2728 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2729
2730 bool Success(APValue::LValueBase B) {
2731 Result.set(B);
2732 return true;
2733 }
2734
2735public:
2736 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2737 ExprEvaluatorBaseTy(Info), Result(Result) {}
2738
Richard Smith1aa0be82012-03-03 22:46:17 +00002739 bool Success(const APValue &V, const Expr *E) {
2740 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002741 return true;
2742 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002743
Richard Smithe24f5fc2011-11-17 22:56:20 +00002744 bool VisitMemberExpr(const MemberExpr *E) {
2745 // Handle non-static data members.
2746 QualType BaseTy;
2747 if (E->isArrow()) {
2748 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2749 return false;
2750 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002751 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002752 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002753 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2754 return false;
2755 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002756 } else {
2757 if (!this->Visit(E->getBase()))
2758 return false;
2759 BaseTy = E->getBase()->getType();
2760 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002761
Richard Smithd9b02e72012-01-25 22:15:11 +00002762 const ValueDecl *MD = E->getMemberDecl();
2763 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2764 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2765 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2766 (void)BaseTy;
2767 HandleLValueMember(this->Info, E, Result, FD);
2768 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2769 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2770 } else
2771 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002772
Richard Smithd9b02e72012-01-25 22:15:11 +00002773 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002774 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002775 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002776 RefValue))
2777 return false;
2778 return Success(RefValue, E);
2779 }
2780 return true;
2781 }
2782
2783 bool VisitBinaryOperator(const BinaryOperator *E) {
2784 switch (E->getOpcode()) {
2785 default:
2786 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2787
2788 case BO_PtrMemD:
2789 case BO_PtrMemI:
2790 return HandleMemberPointerAccess(this->Info, E, Result);
2791 }
2792 }
2793
2794 bool VisitCastExpr(const CastExpr *E) {
2795 switch (E->getCastKind()) {
2796 default:
2797 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2798
2799 case CK_DerivedToBase:
2800 case CK_UncheckedDerivedToBase: {
2801 if (!this->Visit(E->getSubExpr()))
2802 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002803
2804 // Now figure out the necessary offset to add to the base LV to get from
2805 // the derived class to the base class.
2806 QualType Type = E->getSubExpr()->getType();
2807
2808 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2809 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002810 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002811 *PathI))
2812 return false;
2813 Type = (*PathI)->getType();
2814 }
2815
2816 return true;
2817 }
2818 }
2819 }
2820};
2821}
2822
2823//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002824// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002825//
2826// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2827// function designators (in C), decl references to void objects (in C), and
2828// temporaries (if building with -Wno-address-of-temporary).
2829//
2830// LValue evaluation produces values comprising a base expression of one of the
2831// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002832// - Declarations
2833// * VarDecl
2834// * FunctionDecl
2835// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002836// * CompoundLiteralExpr in C
2837// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002838// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002839// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002840// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002841// * ObjCEncodeExpr
2842// * AddrLabelExpr
2843// * BlockExpr
2844// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002845// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002846// * Any Expr, with a CallIndex indicating the function in which the temporary
2847// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002848// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002849//===----------------------------------------------------------------------===//
2850namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002851class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002852 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002853public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002854 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2855 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002856
Richard Smithc49bd112011-10-28 17:51:58 +00002857 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2858
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002859 bool VisitDeclRefExpr(const DeclRefExpr *E);
2860 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002861 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002862 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2863 bool VisitMemberExpr(const MemberExpr *E);
2864 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2865 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002866 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002867 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2868 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002869 bool VisitUnaryReal(const UnaryOperator *E);
2870 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002871
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002872 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002873 switch (E->getCastKind()) {
2874 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002875 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002876
Eli Friedmandb924222011-10-11 00:13:24 +00002877 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002878 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002879 if (!Visit(E->getSubExpr()))
2880 return false;
2881 Result.Designator.setInvalid();
2882 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002883
Richard Smithe24f5fc2011-11-17 22:56:20 +00002884 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002885 if (!Visit(E->getSubExpr()))
2886 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002887 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002888 }
2889 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002890};
2891} // end anonymous namespace
2892
Richard Smithc49bd112011-10-28 17:51:58 +00002893/// Evaluate an expression as an lvalue. This can be legitimately called on
2894/// expressions which are not glvalues, in a few cases:
2895/// * function designators in C,
2896/// * "extern void" objects,
2897/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002898static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002899 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2900 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2901 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002902 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002903}
2904
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002905bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002906 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2907 return Success(FD);
2908 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002909 return VisitVarDecl(E, VD);
2910 return Error(E);
2911}
Richard Smith436c8892011-10-24 23:14:33 +00002912
Richard Smithc49bd112011-10-28 17:51:58 +00002913bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002914 if (!VD->getType()->isReferenceType()) {
2915 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002916 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002917 return true;
2918 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002919 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002920 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002921
Richard Smith1aa0be82012-03-03 22:46:17 +00002922 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002923 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2924 return false;
2925 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002926}
2927
Richard Smithbd552ef2011-10-31 05:52:43 +00002928bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2929 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002930 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002931 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002932 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2933
Richard Smith83587db2012-02-15 02:18:13 +00002934 Result.set(E, Info.CurrentCall->Index);
2935 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2936 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002937 }
2938
2939 // Materialization of an lvalue temporary occurs when we need to force a copy
2940 // (for instance, if it's a bitfield).
2941 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2942 if (!Visit(E->GetTemporaryExpr()))
2943 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00002944 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002945 Info.CurrentCall->Temporaries[E]))
2946 return false;
Richard Smith83587db2012-02-15 02:18:13 +00002947 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002948 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00002949}
2950
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002951bool
2952LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002953 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2954 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2955 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002956 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002957}
2958
Richard Smith47d21452011-12-27 12:18:28 +00002959bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
2960 if (E->isTypeOperand())
2961 return Success(E);
2962 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
2963 if (RD && RD->isPolymorphic()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002964 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith47d21452011-12-27 12:18:28 +00002965 << E->getExprOperand()->getType()
2966 << E->getExprOperand()->getSourceRange();
2967 return false;
2968 }
2969 return Success(E);
2970}
2971
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002972bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002973 // Handle static data members.
2974 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2975 VisitIgnoredValue(E->getBase());
2976 return VisitVarDecl(E, VD);
2977 }
2978
Richard Smithd0dccea2011-10-28 22:34:42 +00002979 // Handle static member functions.
2980 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2981 if (MD->isStatic()) {
2982 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002983 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002984 }
2985 }
2986
Richard Smith180f4792011-11-10 06:34:14 +00002987 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002988 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002989}
2990
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002991bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002992 // FIXME: Deal with vectors as array subscript bases.
2993 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002994 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002995
Anders Carlsson3068d112008-11-16 19:01:22 +00002996 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002997 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002998
Anders Carlsson3068d112008-11-16 19:01:22 +00002999 APSInt Index;
3000 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003001 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003002 int64_t IndexValue
3003 = Index.isSigned() ? Index.getSExtValue()
3004 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003005
Richard Smithb4e85ed2012-01-06 16:39:00 +00003006 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003007}
Eli Friedman4efaa272008-11-12 09:44:48 +00003008
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003009bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003010 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003011}
3012
Richard Smith86024012012-02-18 22:04:06 +00003013bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3014 if (!Visit(E->getSubExpr()))
3015 return false;
3016 // __real is a no-op on scalar lvalues.
3017 if (E->getSubExpr()->getType()->isAnyComplexType())
3018 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3019 return true;
3020}
3021
3022bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3023 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3024 "lvalue __imag__ on scalar?");
3025 if (!Visit(E->getSubExpr()))
3026 return false;
3027 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3028 return true;
3029}
3030
Eli Friedman4efaa272008-11-12 09:44:48 +00003031//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003032// Pointer Evaluation
3033//===----------------------------------------------------------------------===//
3034
Anders Carlssonc754aa62008-07-08 05:13:58 +00003035namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003036class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003037 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003038 LValue &Result;
3039
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003040 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003041 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003042 return true;
3043 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003044public:
Mike Stump1eb44332009-09-09 15:08:12 +00003045
John McCallefdb83e2010-05-07 21:00:08 +00003046 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003047 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003048
Richard Smith1aa0be82012-03-03 22:46:17 +00003049 bool Success(const APValue &V, const Expr *E) {
3050 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003051 return true;
3052 }
Richard Smith51201882011-12-30 21:15:51 +00003053 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003054 return Success((Expr*)0);
3055 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003056
John McCallefdb83e2010-05-07 21:00:08 +00003057 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003058 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003059 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003060 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003061 { return Success(E); }
Ted Kremenekebcb57a2012-03-06 20:05:56 +00003062 bool VisitObjCNumericLiteral(const ObjCNumericLiteral *E)
3063 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003064 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003065 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003066 bool VisitCallExpr(const CallExpr *E);
3067 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003068 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003069 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003070 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003071 }
Richard Smith180f4792011-11-10 06:34:14 +00003072 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3073 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003074 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003075 Result = *Info.CurrentCall->This;
3076 return true;
3077 }
John McCall56ca35d2011-02-17 10:25:35 +00003078
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003079 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003080};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003081} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003082
John McCallefdb83e2010-05-07 21:00:08 +00003083static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003084 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003085 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003086}
3087
John McCallefdb83e2010-05-07 21:00:08 +00003088bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003089 if (E->getOpcode() != BO_Add &&
3090 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003091 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003092
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003093 const Expr *PExp = E->getLHS();
3094 const Expr *IExp = E->getRHS();
3095 if (IExp->getType()->isPointerType())
3096 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003097
Richard Smith745f5142012-01-27 01:14:48 +00003098 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3099 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003100 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003101
John McCallefdb83e2010-05-07 21:00:08 +00003102 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003103 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003104 return false;
3105 int64_t AdditionalOffset
3106 = Offset.isSigned() ? Offset.getSExtValue()
3107 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003108 if (E->getOpcode() == BO_Sub)
3109 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003110
Richard Smith180f4792011-11-10 06:34:14 +00003111 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003112 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3113 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003114}
Eli Friedman4efaa272008-11-12 09:44:48 +00003115
John McCallefdb83e2010-05-07 21:00:08 +00003116bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3117 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003118}
Mike Stump1eb44332009-09-09 15:08:12 +00003119
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003120bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3121 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003122
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003123 switch (E->getCastKind()) {
3124 default:
3125 break;
3126
John McCall2de56d12010-08-25 11:45:40 +00003127 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003128 case CK_CPointerToObjCPointerCast:
3129 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003130 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003131 if (!Visit(SubExpr))
3132 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003133 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3134 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3135 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003136 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003137 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003138 if (SubExpr->getType()->isVoidPointerType())
3139 CCEDiag(E, diag::note_constexpr_invalid_cast)
3140 << 3 << SubExpr->getType();
3141 else
3142 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3143 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003144 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003145
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003146 case CK_DerivedToBase:
3147 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003148 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003149 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003150 if (!Result.Base && Result.Offset.isZero())
3151 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003152
Richard Smith180f4792011-11-10 06:34:14 +00003153 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003154 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003155 QualType Type =
3156 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003157
Richard Smith180f4792011-11-10 06:34:14 +00003158 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003159 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003160 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3161 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003162 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003163 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003164 }
3165
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003166 return true;
3167 }
3168
Richard Smithe24f5fc2011-11-17 22:56:20 +00003169 case CK_BaseToDerived:
3170 if (!Visit(E->getSubExpr()))
3171 return false;
3172 if (!Result.Base && Result.Offset.isZero())
3173 return true;
3174 return HandleBaseToDerivedCast(Info, E, Result);
3175
Richard Smith47a1eed2011-10-29 20:57:55 +00003176 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003177 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003178
John McCall2de56d12010-08-25 11:45:40 +00003179 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003180 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3181
Richard Smith1aa0be82012-03-03 22:46:17 +00003182 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003183 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003184 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003185
John McCallefdb83e2010-05-07 21:00:08 +00003186 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003187 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3188 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003189 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003190 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003191 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003192 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003193 return true;
3194 } else {
3195 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003196 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003197 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003198 }
3199 }
John McCall2de56d12010-08-25 11:45:40 +00003200 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003201 if (SubExpr->isGLValue()) {
3202 if (!EvaluateLValue(SubExpr, Result, Info))
3203 return false;
3204 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003205 Result.set(SubExpr, Info.CurrentCall->Index);
3206 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3207 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003208 return false;
3209 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003210 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003211 if (const ConstantArrayType *CAT
3212 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3213 Result.addArray(Info, E, CAT);
3214 else
3215 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003216 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003217
John McCall2de56d12010-08-25 11:45:40 +00003218 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003219 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003220 }
3221
Richard Smithc49bd112011-10-28 17:51:58 +00003222 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003223}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003224
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003225bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003226 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003227 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003228
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003229 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003230}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003231
3232//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003233// Member Pointer Evaluation
3234//===----------------------------------------------------------------------===//
3235
3236namespace {
3237class MemberPointerExprEvaluator
3238 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3239 MemberPtr &Result;
3240
3241 bool Success(const ValueDecl *D) {
3242 Result = MemberPtr(D);
3243 return true;
3244 }
3245public:
3246
3247 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3248 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3249
Richard Smith1aa0be82012-03-03 22:46:17 +00003250 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003251 Result.setFrom(V);
3252 return true;
3253 }
Richard Smith51201882011-12-30 21:15:51 +00003254 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003255 return Success((const ValueDecl*)0);
3256 }
3257
3258 bool VisitCastExpr(const CastExpr *E);
3259 bool VisitUnaryAddrOf(const UnaryOperator *E);
3260};
3261} // end anonymous namespace
3262
3263static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3264 EvalInfo &Info) {
3265 assert(E->isRValue() && E->getType()->isMemberPointerType());
3266 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3267}
3268
3269bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3270 switch (E->getCastKind()) {
3271 default:
3272 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3273
3274 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003275 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003276
3277 case CK_BaseToDerivedMemberPointer: {
3278 if (!Visit(E->getSubExpr()))
3279 return false;
3280 if (E->path_empty())
3281 return true;
3282 // Base-to-derived member pointer casts store the path in derived-to-base
3283 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3284 // the wrong end of the derived->base arc, so stagger the path by one class.
3285 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3286 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3287 PathI != PathE; ++PathI) {
3288 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3289 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3290 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003291 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003292 }
3293 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3294 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003295 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003296 return true;
3297 }
3298
3299 case CK_DerivedToBaseMemberPointer:
3300 if (!Visit(E->getSubExpr()))
3301 return false;
3302 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3303 PathE = E->path_end(); PathI != PathE; ++PathI) {
3304 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3305 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3306 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003307 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003308 }
3309 return true;
3310 }
3311}
3312
3313bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3314 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3315 // member can be formed.
3316 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3317}
3318
3319//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003320// Record Evaluation
3321//===----------------------------------------------------------------------===//
3322
3323namespace {
3324 class RecordExprEvaluator
3325 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3326 const LValue &This;
3327 APValue &Result;
3328 public:
3329
3330 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3331 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3332
Richard Smith1aa0be82012-03-03 22:46:17 +00003333 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003334 Result = V;
3335 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003336 }
Richard Smith51201882011-12-30 21:15:51 +00003337 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003338
Richard Smith59efe262011-11-11 04:05:33 +00003339 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003340 bool VisitInitListExpr(const InitListExpr *E);
3341 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3342 };
3343}
3344
Richard Smith51201882011-12-30 21:15:51 +00003345/// Perform zero-initialization on an object of non-union class type.
3346/// C++11 [dcl.init]p5:
3347/// To zero-initialize an object or reference of type T means:
3348/// [...]
3349/// -- if T is a (possibly cv-qualified) non-union class type,
3350/// each non-static data member and each base-class subobject is
3351/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003352static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3353 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003354 const LValue &This, APValue &Result) {
3355 assert(!RD->isUnion() && "Expected non-union class type");
3356 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3357 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3358 std::distance(RD->field_begin(), RD->field_end()));
3359
3360 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3361
3362 if (CD) {
3363 unsigned Index = 0;
3364 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003365 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003366 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3367 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003368 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3369 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003370 Result.getStructBase(Index)))
3371 return false;
3372 }
3373 }
3374
Richard Smithb4e85ed2012-01-06 16:39:00 +00003375 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3376 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003377 // -- if T is a reference type, no initialization is performed.
3378 if ((*I)->getType()->isReferenceType())
3379 continue;
3380
3381 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003382 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003383
3384 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003385 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003386 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3387 return false;
3388 }
3389
3390 return true;
3391}
3392
3393bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3394 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3395 if (RD->isUnion()) {
3396 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3397 // object's first non-static named data member is zero-initialized
3398 RecordDecl::field_iterator I = RD->field_begin();
3399 if (I == RD->field_end()) {
3400 Result = APValue((const FieldDecl*)0);
3401 return true;
3402 }
3403
3404 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003405 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003406 Result = APValue(*I);
3407 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003408 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003409 }
3410
Richard Smithce582fe2012-02-17 00:44:16 +00003411 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003412 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003413 return false;
3414 }
3415
Richard Smithb4e85ed2012-01-06 16:39:00 +00003416 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003417}
3418
Richard Smith59efe262011-11-11 04:05:33 +00003419bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3420 switch (E->getCastKind()) {
3421 default:
3422 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3423
3424 case CK_ConstructorConversion:
3425 return Visit(E->getSubExpr());
3426
3427 case CK_DerivedToBase:
3428 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003429 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003430 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003431 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003432 if (!DerivedObject.isStruct())
3433 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003434
3435 // Derived-to-base rvalue conversion: just slice off the derived part.
3436 APValue *Value = &DerivedObject;
3437 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3438 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3439 PathE = E->path_end(); PathI != PathE; ++PathI) {
3440 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3441 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3442 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3443 RD = Base;
3444 }
3445 Result = *Value;
3446 return true;
3447 }
3448 }
3449}
3450
Richard Smith180f4792011-11-10 06:34:14 +00003451bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003452 // Cannot constant-evaluate std::initializer_list inits.
3453 if (E->initializesStdInitializerList())
3454 return false;
3455
Richard Smith180f4792011-11-10 06:34:14 +00003456 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3457 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3458
3459 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003460 const FieldDecl *Field = E->getInitializedFieldInUnion();
3461 Result = APValue(Field);
3462 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003463 return true;
Richard Smithec789162012-01-12 18:54:33 +00003464
3465 // If the initializer list for a union does not contain any elements, the
3466 // first element of the union is value-initialized.
3467 ImplicitValueInitExpr VIE(Field->getType());
3468 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3469
Richard Smith180f4792011-11-10 06:34:14 +00003470 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003471 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003472 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003473 }
3474
3475 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3476 "initializer list for class with base classes");
3477 Result = APValue(APValue::UninitStruct(), 0,
3478 std::distance(RD->field_begin(), RD->field_end()));
3479 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003480 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003481 for (RecordDecl::field_iterator Field = RD->field_begin(),
3482 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3483 // Anonymous bit-fields are not considered members of the class for
3484 // purposes of aggregate initialization.
3485 if (Field->isUnnamedBitfield())
3486 continue;
3487
3488 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003489
Richard Smith745f5142012-01-27 01:14:48 +00003490 bool HaveInit = ElementNo < E->getNumInits();
3491
3492 // FIXME: Diagnostics here should point to the end of the initializer
3493 // list, not the start.
3494 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3495 *Field, &Layout);
3496
3497 // Perform an implicit value-initialization for members beyond the end of
3498 // the initializer list.
3499 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3500
Richard Smith83587db2012-02-15 02:18:13 +00003501 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003502 Result.getStructField((*Field)->getFieldIndex()),
3503 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3504 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003505 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003506 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003507 }
3508 }
3509
Richard Smith745f5142012-01-27 01:14:48 +00003510 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003511}
3512
3513bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3514 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003515 bool ZeroInit = E->requiresZeroInitialization();
3516 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003517 // If we've already performed zero-initialization, we're already done.
3518 if (!Result.isUninit())
3519 return true;
3520
Richard Smith51201882011-12-30 21:15:51 +00003521 if (ZeroInit)
3522 return ZeroInitialization(E);
3523
Richard Smith61802452011-12-22 02:22:31 +00003524 const CXXRecordDecl *RD = FD->getParent();
3525 if (RD->isUnion())
3526 Result = APValue((FieldDecl*)0);
3527 else
3528 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3529 std::distance(RD->field_begin(), RD->field_end()));
3530 return true;
3531 }
3532
Richard Smith180f4792011-11-10 06:34:14 +00003533 const FunctionDecl *Definition = 0;
3534 FD->getBody(Definition);
3535
Richard Smithc1c5f272011-12-13 06:39:58 +00003536 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3537 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003538
Richard Smith610a60c2012-01-10 04:32:03 +00003539 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003540 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003541 if (const MaterializeTemporaryExpr *ME
3542 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3543 return Visit(ME->GetTemporaryExpr());
3544
Richard Smith51201882011-12-30 21:15:51 +00003545 if (ZeroInit && !ZeroInitialization(E))
3546 return false;
3547
Richard Smith180f4792011-11-10 06:34:14 +00003548 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003549 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003550 cast<CXXConstructorDecl>(Definition), Info,
3551 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003552}
3553
3554static bool EvaluateRecord(const Expr *E, const LValue &This,
3555 APValue &Result, EvalInfo &Info) {
3556 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003557 "can't evaluate expression as a record rvalue");
3558 return RecordExprEvaluator(Info, This, Result).Visit(E);
3559}
3560
3561//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003562// Temporary Evaluation
3563//
3564// Temporaries are represented in the AST as rvalues, but generally behave like
3565// lvalues. The full-object of which the temporary is a subobject is implicitly
3566// materialized so that a reference can bind to it.
3567//===----------------------------------------------------------------------===//
3568namespace {
3569class TemporaryExprEvaluator
3570 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3571public:
3572 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3573 LValueExprEvaluatorBaseTy(Info, Result) {}
3574
3575 /// Visit an expression which constructs the value of this temporary.
3576 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003577 Result.set(E, Info.CurrentCall->Index);
3578 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003579 }
3580
3581 bool VisitCastExpr(const CastExpr *E) {
3582 switch (E->getCastKind()) {
3583 default:
3584 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3585
3586 case CK_ConstructorConversion:
3587 return VisitConstructExpr(E->getSubExpr());
3588 }
3589 }
3590 bool VisitInitListExpr(const InitListExpr *E) {
3591 return VisitConstructExpr(E);
3592 }
3593 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3594 return VisitConstructExpr(E);
3595 }
3596 bool VisitCallExpr(const CallExpr *E) {
3597 return VisitConstructExpr(E);
3598 }
3599};
3600} // end anonymous namespace
3601
3602/// Evaluate an expression of record type as a temporary.
3603static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003604 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003605 return TemporaryExprEvaluator(Info, Result).Visit(E);
3606}
3607
3608//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003609// Vector Evaluation
3610//===----------------------------------------------------------------------===//
3611
3612namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003613 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003614 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3615 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003616 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003617
Richard Smith07fc6572011-10-22 21:10:00 +00003618 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3619 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003620
Richard Smith07fc6572011-10-22 21:10:00 +00003621 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3622 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3623 // FIXME: remove this APValue copy.
3624 Result = APValue(V.data(), V.size());
3625 return true;
3626 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003627 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003628 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003629 Result = V;
3630 return true;
3631 }
Richard Smith51201882011-12-30 21:15:51 +00003632 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003633
Richard Smith07fc6572011-10-22 21:10:00 +00003634 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003635 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003636 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003637 bool VisitInitListExpr(const InitListExpr *E);
3638 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003639 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003640 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003641 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003642 };
3643} // end anonymous namespace
3644
3645static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003646 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003647 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003648}
3649
Richard Smith07fc6572011-10-22 21:10:00 +00003650bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3651 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003652 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003653
Richard Smithd62ca372011-12-06 22:44:34 +00003654 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003655 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003656
Eli Friedman46a52322011-03-25 00:43:55 +00003657 switch (E->getCastKind()) {
3658 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003659 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003660 if (SETy->isIntegerType()) {
3661 APSInt IntResult;
3662 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003663 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003664 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003665 } else if (SETy->isRealFloatingType()) {
3666 APFloat F(0.0);
3667 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003668 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003669 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003670 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003671 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003672 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003673
3674 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003675 SmallVector<APValue, 4> Elts(NElts, Val);
3676 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003677 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003678 case CK_BitCast: {
3679 // Evaluate the operand into an APInt we can extract from.
3680 llvm::APInt SValInt;
3681 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3682 return false;
3683 // Extract the elements
3684 QualType EltTy = VTy->getElementType();
3685 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3686 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3687 SmallVector<APValue, 4> Elts;
3688 if (EltTy->isRealFloatingType()) {
3689 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3690 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3691 unsigned FloatEltSize = EltSize;
3692 if (&Sem == &APFloat::x87DoubleExtended)
3693 FloatEltSize = 80;
3694 for (unsigned i = 0; i < NElts; i++) {
3695 llvm::APInt Elt;
3696 if (BigEndian)
3697 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3698 else
3699 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3700 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3701 }
3702 } else if (EltTy->isIntegerType()) {
3703 for (unsigned i = 0; i < NElts; i++) {
3704 llvm::APInt Elt;
3705 if (BigEndian)
3706 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3707 else
3708 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3709 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3710 }
3711 } else {
3712 return Error(E);
3713 }
3714 return Success(Elts, E);
3715 }
Eli Friedman46a52322011-03-25 00:43:55 +00003716 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003717 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003718 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003719}
3720
Richard Smith07fc6572011-10-22 21:10:00 +00003721bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003722VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003723 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003724 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003725 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003726
Nate Begeman59b5da62009-01-18 03:20:47 +00003727 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003728 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003729
Eli Friedman3edd5a92012-01-03 23:24:20 +00003730 // The number of initializers can be less than the number of
3731 // vector elements. For OpenCL, this can be due to nested vector
3732 // initialization. For GCC compatibility, missing trailing elements
3733 // should be initialized with zeroes.
3734 unsigned CountInits = 0, CountElts = 0;
3735 while (CountElts < NumElements) {
3736 // Handle nested vector initialization.
3737 if (CountInits < NumInits
3738 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3739 APValue v;
3740 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3741 return Error(E);
3742 unsigned vlen = v.getVectorLength();
3743 for (unsigned j = 0; j < vlen; j++)
3744 Elements.push_back(v.getVectorElt(j));
3745 CountElts += vlen;
3746 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003747 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003748 if (CountInits < NumInits) {
3749 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003750 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003751 } else // trailing integer zero.
3752 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3753 Elements.push_back(APValue(sInt));
3754 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003755 } else {
3756 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003757 if (CountInits < NumInits) {
3758 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003759 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003760 } else // trailing float zero.
3761 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3762 Elements.push_back(APValue(f));
3763 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003764 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003765 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003766 }
Richard Smith07fc6572011-10-22 21:10:00 +00003767 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003768}
3769
Richard Smith07fc6572011-10-22 21:10:00 +00003770bool
Richard Smith51201882011-12-30 21:15:51 +00003771VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003772 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003773 QualType EltTy = VT->getElementType();
3774 APValue ZeroElement;
3775 if (EltTy->isIntegerType())
3776 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3777 else
3778 ZeroElement =
3779 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3780
Chris Lattner5f9e2722011-07-23 10:55:15 +00003781 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003782 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003783}
3784
Richard Smith07fc6572011-10-22 21:10:00 +00003785bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003786 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003787 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003788}
3789
Nate Begeman59b5da62009-01-18 03:20:47 +00003790//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003791// Array Evaluation
3792//===----------------------------------------------------------------------===//
3793
3794namespace {
3795 class ArrayExprEvaluator
3796 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003797 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003798 APValue &Result;
3799 public:
3800
Richard Smith180f4792011-11-10 06:34:14 +00003801 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3802 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003803
3804 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003805 assert((V.isArray() || V.isLValue()) &&
3806 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003807 Result = V;
3808 return true;
3809 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003810
Richard Smith51201882011-12-30 21:15:51 +00003811 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003812 const ConstantArrayType *CAT =
3813 Info.Ctx.getAsConstantArrayType(E->getType());
3814 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003815 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003816
3817 Result = APValue(APValue::UninitArray(), 0,
3818 CAT->getSize().getZExtValue());
3819 if (!Result.hasArrayFiller()) return true;
3820
Richard Smith51201882011-12-30 21:15:51 +00003821 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003822 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003823 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003824 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003825 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003826 }
3827
Richard Smithcc5d4f62011-11-07 09:22:26 +00003828 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003829 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003830 };
3831} // end anonymous namespace
3832
Richard Smith180f4792011-11-10 06:34:14 +00003833static bool EvaluateArray(const Expr *E, const LValue &This,
3834 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003835 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003836 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003837}
3838
3839bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3840 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3841 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003842 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003843
Richard Smith974c5f92011-12-22 01:07:19 +00003844 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3845 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003846 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003847 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3848 LValue LV;
3849 if (!EvaluateLValue(E->getInit(0), LV, Info))
3850 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003851 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003852 LV.moveInto(Val);
3853 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003854 }
3855
Richard Smith745f5142012-01-27 01:14:48 +00003856 bool Success = true;
3857
Richard Smithcc5d4f62011-11-07 09:22:26 +00003858 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3859 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003860 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003861 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003862 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003863 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003864 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003865 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3866 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003867 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3868 CAT->getElementType(), 1)) {
3869 if (!Info.keepEvaluatingAfterFailure())
3870 return false;
3871 Success = false;
3872 }
Richard Smith180f4792011-11-10 06:34:14 +00003873 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003874
Richard Smith745f5142012-01-27 01:14:48 +00003875 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003876 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003877 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3878 // but sometimes does:
3879 // struct S { constexpr S() : p(&p) {} void *p; };
3880 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003881 return EvaluateInPlace(Result.getArrayFiller(), Info,
3882 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003883}
3884
Richard Smithe24f5fc2011-11-17 22:56:20 +00003885bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3886 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3887 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003888 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003889
Richard Smithec789162012-01-12 18:54:33 +00003890 bool HadZeroInit = !Result.isUninit();
3891 if (!HadZeroInit)
3892 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003893 if (!Result.hasArrayFiller())
3894 return true;
3895
3896 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003897
Richard Smith51201882011-12-30 21:15:51 +00003898 bool ZeroInit = E->requiresZeroInitialization();
3899 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003900 if (HadZeroInit)
3901 return true;
3902
Richard Smith51201882011-12-30 21:15:51 +00003903 if (ZeroInit) {
3904 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003905 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003906 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003907 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003908 }
3909
Richard Smith61802452011-12-22 02:22:31 +00003910 const CXXRecordDecl *RD = FD->getParent();
3911 if (RD->isUnion())
3912 Result.getArrayFiller() = APValue((FieldDecl*)0);
3913 else
3914 Result.getArrayFiller() =
3915 APValue(APValue::UninitStruct(), RD->getNumBases(),
3916 std::distance(RD->field_begin(), RD->field_end()));
3917 return true;
3918 }
3919
Richard Smithe24f5fc2011-11-17 22:56:20 +00003920 const FunctionDecl *Definition = 0;
3921 FD->getBody(Definition);
3922
Richard Smithc1c5f272011-12-13 06:39:58 +00003923 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3924 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003925
3926 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3927 // but sometimes does:
3928 // struct S { constexpr S() : p(&p) {} void *p; };
3929 // S s[10];
3930 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003931 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003932
Richard Smithec789162012-01-12 18:54:33 +00003933 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003934 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003935 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003936 return false;
3937 }
3938
Richard Smithe24f5fc2011-11-17 22:56:20 +00003939 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003940 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003941 cast<CXXConstructorDecl>(Definition),
3942 Info, Result.getArrayFiller());
3943}
3944
Richard Smithcc5d4f62011-11-07 09:22:26 +00003945//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003946// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003947//
3948// As a GNU extension, we support casting pointers to sufficiently-wide integer
3949// types and back in constant folding. Integer values are thus represented
3950// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003951//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003952
3953namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003954class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003955 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003956 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003957public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003958 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003959 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003960
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003961 bool Success(const llvm::APSInt &SI, const Expr *E) {
3962 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003963 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003964 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003965 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003966 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003967 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003968 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003969 return true;
3970 }
3971
Daniel Dunbar131eb432009-02-19 09:06:44 +00003972 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003973 assert(E->getType()->isIntegralOrEnumerationType() &&
3974 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003975 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003976 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003977 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003978 Result.getInt().setIsUnsigned(
3979 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003980 return true;
3981 }
3982
3983 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003984 assert(E->getType()->isIntegralOrEnumerationType() &&
3985 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003986 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003987 return true;
3988 }
3989
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003990 bool Success(CharUnits Size, const Expr *E) {
3991 return Success(Size.getQuantity(), E);
3992 }
3993
Richard Smith1aa0be82012-03-03 22:46:17 +00003994 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003995 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003996 Result = V;
3997 return true;
3998 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003999 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004000 }
Mike Stump1eb44332009-09-09 15:08:12 +00004001
Richard Smith51201882011-12-30 21:15:51 +00004002 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004003
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004004 //===--------------------------------------------------------------------===//
4005 // Visitor Methods
4006 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004007
Chris Lattner4c4867e2008-07-12 00:38:25 +00004008 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004009 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004010 }
4011 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004012 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004013 }
Eli Friedman04309752009-11-24 05:28:59 +00004014
4015 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4016 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004017 if (CheckReferencedDecl(E, E->getDecl()))
4018 return true;
4019
4020 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004021 }
4022 bool VisitMemberExpr(const MemberExpr *E) {
4023 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004024 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004025 return true;
4026 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004027
4028 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004029 }
4030
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004031 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004032 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004033 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004034 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004035
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004036 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004037 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004038
Anders Carlsson3068d112008-11-16 19:01:22 +00004039 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004040 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004041 }
Mike Stump1eb44332009-09-09 15:08:12 +00004042
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004043 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4044 return Success(E->getValue(), E);
4045 }
4046
Richard Smithf10d9172011-10-11 21:43:33 +00004047 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004048 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004049 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004050 }
4051
Sebastian Redl64b45f72009-01-05 20:52:13 +00004052 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004053 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004054 }
4055
Francois Pichet6ad6f282010-12-07 00:08:36 +00004056 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4057 return Success(E->getValue(), E);
4058 }
4059
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004060 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4061 return Success(E->getValue(), E);
4062 }
4063
John Wiegley21ff2e52011-04-28 00:16:57 +00004064 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4065 return Success(E->getValue(), E);
4066 }
4067
John Wiegley55262202011-04-25 06:54:41 +00004068 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4069 return Success(E->getValue(), E);
4070 }
4071
Eli Friedman722c7172009-02-28 03:59:05 +00004072 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004073 bool VisitUnaryImag(const UnaryOperator *E);
4074
Sebastian Redl295995c2010-09-10 20:55:47 +00004075 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004076 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004077
Chris Lattnerfcee0012008-07-11 21:24:13 +00004078private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004079 CharUnits GetAlignOfExpr(const Expr *E);
4080 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004081 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004082 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004083 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004084};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004085} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004086
Richard Smithc49bd112011-10-28 17:51:58 +00004087/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4088/// produce either the integer value or a pointer.
4089///
4090/// GCC has a heinous extension which folds casts between pointer types and
4091/// pointer-sized integral types. We support this by allowing the evaluation of
4092/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4093/// Some simple arithmetic on such values is supported (they are treated much
4094/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004095static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004096 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004097 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004098 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004099}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004100
Richard Smithf48fdb02011-12-09 22:58:01 +00004101static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004102 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004103 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004104 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004105 if (!Val.isInt()) {
4106 // FIXME: It would be better to produce the diagnostic for casting
4107 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004108 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004109 return false;
4110 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004111 Result = Val.getInt();
4112 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004113}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004114
Richard Smithf48fdb02011-12-09 22:58:01 +00004115/// Check whether the given declaration can be directly converted to an integral
4116/// rvalue. If not, no diagnostic is produced; there are other things we can
4117/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004118bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004119 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004120 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004121 // Check for signedness/width mismatches between E type and ECD value.
4122 bool SameSign = (ECD->getInitVal().isSigned()
4123 == E->getType()->isSignedIntegerOrEnumerationType());
4124 bool SameWidth = (ECD->getInitVal().getBitWidth()
4125 == Info.Ctx.getIntWidth(E->getType()));
4126 if (SameSign && SameWidth)
4127 return Success(ECD->getInitVal(), E);
4128 else {
4129 // Get rid of mismatch (otherwise Success assertions will fail)
4130 // by computing a new value matching the type of E.
4131 llvm::APSInt Val = ECD->getInitVal();
4132 if (!SameSign)
4133 Val.setIsSigned(!ECD->getInitVal().isSigned());
4134 if (!SameWidth)
4135 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4136 return Success(Val, E);
4137 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004138 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004139 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004140}
4141
Chris Lattnera4d55d82008-10-06 06:40:35 +00004142/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4143/// as GCC.
4144static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4145 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004146 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004147 enum gcc_type_class {
4148 no_type_class = -1,
4149 void_type_class, integer_type_class, char_type_class,
4150 enumeral_type_class, boolean_type_class,
4151 pointer_type_class, reference_type_class, offset_type_class,
4152 real_type_class, complex_type_class,
4153 function_type_class, method_type_class,
4154 record_type_class, union_type_class,
4155 array_type_class, string_type_class,
4156 lang_type_class
4157 };
Mike Stump1eb44332009-09-09 15:08:12 +00004158
4159 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004160 // ideal, however it is what gcc does.
4161 if (E->getNumArgs() == 0)
4162 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004163
Chris Lattnera4d55d82008-10-06 06:40:35 +00004164 QualType ArgTy = E->getArg(0)->getType();
4165 if (ArgTy->isVoidType())
4166 return void_type_class;
4167 else if (ArgTy->isEnumeralType())
4168 return enumeral_type_class;
4169 else if (ArgTy->isBooleanType())
4170 return boolean_type_class;
4171 else if (ArgTy->isCharType())
4172 return string_type_class; // gcc doesn't appear to use char_type_class
4173 else if (ArgTy->isIntegerType())
4174 return integer_type_class;
4175 else if (ArgTy->isPointerType())
4176 return pointer_type_class;
4177 else if (ArgTy->isReferenceType())
4178 return reference_type_class;
4179 else if (ArgTy->isRealType())
4180 return real_type_class;
4181 else if (ArgTy->isComplexType())
4182 return complex_type_class;
4183 else if (ArgTy->isFunctionType())
4184 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004185 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004186 return record_type_class;
4187 else if (ArgTy->isUnionType())
4188 return union_type_class;
4189 else if (ArgTy->isArrayType())
4190 return array_type_class;
4191 else if (ArgTy->isUnionType())
4192 return union_type_class;
4193 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004194 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004195}
4196
Richard Smith80d4b552011-12-28 19:48:30 +00004197/// EvaluateBuiltinConstantPForLValue - Determine the result of
4198/// __builtin_constant_p when applied to the given lvalue.
4199///
4200/// An lvalue is only "constant" if it is a pointer or reference to the first
4201/// character of a string literal.
4202template<typename LValue>
4203static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004204 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004205 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4206}
4207
4208/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4209/// GCC as we can manage.
4210static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4211 QualType ArgType = Arg->getType();
4212
4213 // __builtin_constant_p always has one operand. The rules which gcc follows
4214 // are not precisely documented, but are as follows:
4215 //
4216 // - If the operand is of integral, floating, complex or enumeration type,
4217 // and can be folded to a known value of that type, it returns 1.
4218 // - If the operand and can be folded to a pointer to the first character
4219 // of a string literal (or such a pointer cast to an integral type), it
4220 // returns 1.
4221 //
4222 // Otherwise, it returns 0.
4223 //
4224 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4225 // its support for this does not currently work.
4226 if (ArgType->isIntegralOrEnumerationType()) {
4227 Expr::EvalResult Result;
4228 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4229 return false;
4230
4231 APValue &V = Result.Val;
4232 if (V.getKind() == APValue::Int)
4233 return true;
4234
4235 return EvaluateBuiltinConstantPForLValue(V);
4236 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4237 return Arg->isEvaluatable(Ctx);
4238 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4239 LValue LV;
4240 Expr::EvalStatus Status;
4241 EvalInfo Info(Ctx, Status);
4242 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4243 : EvaluatePointer(Arg, LV, Info)) &&
4244 !Status.HasSideEffects)
4245 return EvaluateBuiltinConstantPForLValue(LV);
4246 }
4247
4248 // Anything else isn't considered to be sufficiently constant.
4249 return false;
4250}
4251
John McCall42c8f872010-05-10 23:27:23 +00004252/// Retrieves the "underlying object type" of the given expression,
4253/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004254QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4255 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4256 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004257 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004258 } else if (const Expr *E = B.get<const Expr*>()) {
4259 if (isa<CompoundLiteralExpr>(E))
4260 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004261 }
4262
4263 return QualType();
4264}
4265
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004266bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004267 // TODO: Perhaps we should let LLVM lower this?
4268 LValue Base;
4269 if (!EvaluatePointer(E->getArg(0), Base, Info))
4270 return false;
4271
4272 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004273 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004274
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004275 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004276 if (T.isNull() ||
4277 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004278 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004279 T->isVariablyModifiedType() ||
4280 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004281 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004282
4283 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4284 CharUnits Offset = Base.getLValueOffset();
4285
4286 if (!Offset.isNegative() && Offset <= Size)
4287 Size -= Offset;
4288 else
4289 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004290 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004291}
4292
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004293bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004294 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004295 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004296 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004297
4298 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004299 if (TryEvaluateBuiltinObjectSize(E))
4300 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004301
Eric Christopherb2aaf512010-01-19 22:58:35 +00004302 // If evaluating the argument has side-effects we can't determine
4303 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004304 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004305 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004306 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004307 return Success(0, E);
4308 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004309
Richard Smithf48fdb02011-12-09 22:58:01 +00004310 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004311 }
4312
Chris Lattner019f4e82008-10-06 05:28:25 +00004313 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004314 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004315
Richard Smith80d4b552011-12-28 19:48:30 +00004316 case Builtin::BI__builtin_constant_p:
4317 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004318
Chris Lattner21fb98e2009-09-23 06:06:36 +00004319 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004320 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004321 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004322 return Success(Operand, E);
4323 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004324
4325 case Builtin::BI__builtin_expect:
4326 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004327
Douglas Gregor5726d402010-09-10 06:27:15 +00004328 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004329 // A call to strlen is not a constant expression.
4330 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004331 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004332 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4333 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004334 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004335 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004336 case Builtin::BI__builtin_strlen:
4337 // As an extension, we support strlen() and __builtin_strlen() as constant
4338 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004339 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004340 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4341 // The string literal may have embedded null characters. Find the first
4342 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004343 StringRef Str = S->getString();
4344 StringRef::size_type Pos = Str.find(0);
4345 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004346 Str = Str.substr(0, Pos);
4347
4348 return Success(Str.size(), E);
4349 }
4350
Richard Smithf48fdb02011-12-09 22:58:01 +00004351 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004352
4353 case Builtin::BI__atomic_is_lock_free: {
4354 APSInt SizeVal;
4355 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4356 return false;
4357
4358 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4359 // of two less than the maximum inline atomic width, we know it is
4360 // lock-free. If the size isn't a power of two, or greater than the
4361 // maximum alignment where we promote atomics, we know it is not lock-free
4362 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4363 // the answer can only be determined at runtime; for example, 16-byte
4364 // atomics have lock-free implementations on some, but not all,
4365 // x86-64 processors.
4366
4367 // Check power-of-two.
4368 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4369 if (!Size.isPowerOfTwo())
4370#if 0
4371 // FIXME: Suppress this folding until the ABI for the promotion width
4372 // settles.
4373 return Success(0, E);
4374#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004375 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004376#endif
4377
4378#if 0
4379 // Check against promotion width.
4380 // FIXME: Suppress this folding until the ABI for the promotion width
4381 // settles.
4382 unsigned PromoteWidthBits =
4383 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4384 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4385 return Success(0, E);
4386#endif
4387
4388 // Check against inlining width.
4389 unsigned InlineWidthBits =
4390 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4391 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4392 return Success(1, E);
4393
Richard Smithf48fdb02011-12-09 22:58:01 +00004394 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004395 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004396 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004397}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004398
Richard Smith625b8072011-10-31 01:37:14 +00004399static bool HasSameBase(const LValue &A, const LValue &B) {
4400 if (!A.getLValueBase())
4401 return !B.getLValueBase();
4402 if (!B.getLValueBase())
4403 return false;
4404
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004405 if (A.getLValueBase().getOpaqueValue() !=
4406 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004407 const Decl *ADecl = GetLValueBaseDecl(A);
4408 if (!ADecl)
4409 return false;
4410 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004411 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004412 return false;
4413 }
4414
4415 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004416 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004417}
4418
Richard Smith7b48a292012-02-01 05:53:12 +00004419/// Perform the given integer operation, which is known to need at most BitWidth
4420/// bits, and check for overflow in the original type (if that type was not an
4421/// unsigned type).
4422template<typename Operation>
4423static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4424 const APSInt &LHS, const APSInt &RHS,
4425 unsigned BitWidth, Operation Op) {
4426 if (LHS.isUnsigned())
4427 return Op(LHS, RHS);
4428
4429 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4430 APSInt Result = Value.trunc(LHS.getBitWidth());
4431 if (Result.extend(BitWidth) != Value)
4432 HandleOverflow(Info, E, Value, E->getType());
4433 return Result;
4434}
4435
Chris Lattnerb542afe2008-07-11 19:10:17 +00004436bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004437 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004438 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004439
John McCall2de56d12010-08-25 11:45:40 +00004440 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004441 VisitIgnoredValue(E->getLHS());
4442 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004443 }
4444
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004445 if (E->isLogicalOp()) {
4446 // These need to be handled specially because the operands aren't
4447 // necessarily integral nor evaluated.
4448 bool lhsResult, rhsResult;
4449
4450 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
4451 // We were able to evaluate the LHS, see if we can get away with not
4452 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
4453 if (lhsResult == (E->getOpcode() == BO_LOr))
4454 return Success(lhsResult, E);
4455
4456 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4457 if (E->getOpcode() == BO_LOr)
4458 return Success(lhsResult || rhsResult, E);
4459 else
4460 return Success(lhsResult && rhsResult, E);
4461 }
4462 } else {
4463 // Since we weren't able to evaluate the left hand side, it
4464 // must have had side effects.
4465 Info.EvalStatus.HasSideEffects = true;
4466
4467 // Suppress diagnostics from this arm.
4468 SpeculativeEvaluationRAII Speculative(Info);
4469 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
4470 // We can't evaluate the LHS; however, sometimes the result
4471 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4472 if (rhsResult == (E->getOpcode() == BO_LOr))
4473 return Success(rhsResult, E);
4474 }
4475 }
4476
4477 return false;
4478 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004479
Anders Carlsson286f85e2008-11-16 07:17:21 +00004480 QualType LHSTy = E->getLHS()->getType();
4481 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004482
4483 if (LHSTy->isAnyComplexType()) {
4484 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004485 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004486
Richard Smith745f5142012-01-27 01:14:48 +00004487 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4488 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004489 return false;
4490
Richard Smith745f5142012-01-27 01:14:48 +00004491 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004492 return false;
4493
4494 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004495 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004496 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004497 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004498 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4499
John McCall2de56d12010-08-25 11:45:40 +00004500 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004501 return Success((CR_r == APFloat::cmpEqual &&
4502 CR_i == APFloat::cmpEqual), E);
4503 else {
John McCall2de56d12010-08-25 11:45:40 +00004504 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004505 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004506 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004507 CR_r == APFloat::cmpLessThan ||
4508 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004509 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004510 CR_i == APFloat::cmpLessThan ||
4511 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004512 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004513 } else {
John McCall2de56d12010-08-25 11:45:40 +00004514 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004515 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4516 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4517 else {
John McCall2de56d12010-08-25 11:45:40 +00004518 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004519 "Invalid compex comparison.");
4520 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4521 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4522 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004523 }
4524 }
Mike Stump1eb44332009-09-09 15:08:12 +00004525
Anders Carlsson286f85e2008-11-16 07:17:21 +00004526 if (LHSTy->isRealFloatingType() &&
4527 RHSTy->isRealFloatingType()) {
4528 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004529
Richard Smith745f5142012-01-27 01:14:48 +00004530 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4531 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004532 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004533
Richard Smith745f5142012-01-27 01:14:48 +00004534 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004535 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004536
Anders Carlsson286f85e2008-11-16 07:17:21 +00004537 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004538
Anders Carlsson286f85e2008-11-16 07:17:21 +00004539 switch (E->getOpcode()) {
4540 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004541 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004542 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004543 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004544 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004545 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004546 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004547 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004548 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004549 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004550 E);
John McCall2de56d12010-08-25 11:45:40 +00004551 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004552 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004553 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004554 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004555 || CR == APFloat::cmpLessThan
4556 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004557 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004558 }
Mike Stump1eb44332009-09-09 15:08:12 +00004559
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004560 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004561 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004562 LValue LHSValue, RHSValue;
4563
4564 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4565 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004566 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004567
Richard Smith745f5142012-01-27 01:14:48 +00004568 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004569 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004570
Richard Smith625b8072011-10-31 01:37:14 +00004571 // Reject differing bases from the normal codepath; we special-case
4572 // comparisons to null.
4573 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004574 if (E->getOpcode() == BO_Sub) {
4575 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004576 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4577 return false;
4578 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4579 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4580 if (!LHSExpr || !RHSExpr)
4581 return false;
4582 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4583 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4584 if (!LHSAddrExpr || !RHSAddrExpr)
4585 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004586 // Make sure both labels come from the same function.
4587 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4588 RHSAddrExpr->getLabel()->getDeclContext())
4589 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004590 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004591 return true;
4592 }
Richard Smith9e36b532011-10-31 05:11:32 +00004593 // Inequalities and subtractions between unrelated pointers have
4594 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004595 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004596 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004597 // A constant address may compare equal to the address of a symbol.
4598 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004599 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004600 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4601 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004602 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004603 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004604 // distinct addresses. In clang, the result of such a comparison is
4605 // unspecified, so it is not a constant expression. However, we do know
4606 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004607 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4608 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004609 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004610 // We can't tell whether weak symbols will end up pointing to the same
4611 // object.
4612 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004613 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004614 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004615 // (Note that clang defaults to -fmerge-all-constants, which can
4616 // lead to inconsistent results for comparisons involving the address
4617 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004618 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004619 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004620
Richard Smith15efc4d2012-02-01 08:10:20 +00004621 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4622 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4623
Richard Smithf15fda02012-02-02 01:16:57 +00004624 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4625 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4626
John McCall2de56d12010-08-25 11:45:40 +00004627 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004628 // C++11 [expr.add]p6:
4629 // Unless both pointers point to elements of the same array object, or
4630 // one past the last element of the array object, the behavior is
4631 // undefined.
4632 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4633 !AreElementsOfSameArray(getType(LHSValue.Base),
4634 LHSDesignator, RHSDesignator))
4635 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4636
Chris Lattner4992bdd2010-04-20 17:13:14 +00004637 QualType Type = E->getLHS()->getType();
4638 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004639
Richard Smith180f4792011-11-10 06:34:14 +00004640 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004641 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004642 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004643
Richard Smith15efc4d2012-02-01 08:10:20 +00004644 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4645 // and produce incorrect results when it overflows. Such behavior
4646 // appears to be non-conforming, but is common, so perhaps we should
4647 // assume the standard intended for such cases to be undefined behavior
4648 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004649
Richard Smith15efc4d2012-02-01 08:10:20 +00004650 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4651 // overflow in the final conversion to ptrdiff_t.
4652 APSInt LHS(
4653 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4654 APSInt RHS(
4655 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4656 APSInt ElemSize(
4657 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4658 APSInt TrueResult = (LHS - RHS) / ElemSize;
4659 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4660
4661 if (Result.extend(65) != TrueResult)
4662 HandleOverflow(Info, E, TrueResult, E->getType());
4663 return Success(Result, E);
4664 }
Richard Smith82f28582012-01-31 06:41:30 +00004665
4666 // C++11 [expr.rel]p3:
4667 // Pointers to void (after pointer conversions) can be compared, with a
4668 // result defined as follows: If both pointers represent the same
4669 // address or are both the null pointer value, the result is true if the
4670 // operator is <= or >= and false otherwise; otherwise the result is
4671 // unspecified.
4672 // We interpret this as applying to pointers to *cv* void.
4673 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004674 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004675 CCEDiag(E, diag::note_constexpr_void_comparison);
4676
Richard Smithf15fda02012-02-02 01:16:57 +00004677 // C++11 [expr.rel]p2:
4678 // - If two pointers point to non-static data members of the same object,
4679 // or to subobjects or array elements fo such members, recursively, the
4680 // pointer to the later declared member compares greater provided the
4681 // two members have the same access control and provided their class is
4682 // not a union.
4683 // [...]
4684 // - Otherwise pointer comparisons are unspecified.
4685 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4686 E->isRelationalOp()) {
4687 bool WasArrayIndex;
4688 unsigned Mismatch =
4689 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4690 RHSDesignator, WasArrayIndex);
4691 // At the point where the designators diverge, the comparison has a
4692 // specified value if:
4693 // - we are comparing array indices
4694 // - we are comparing fields of a union, or fields with the same access
4695 // Otherwise, the result is unspecified and thus the comparison is not a
4696 // constant expression.
4697 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4698 Mismatch < RHSDesignator.Entries.size()) {
4699 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4700 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4701 if (!LF && !RF)
4702 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4703 else if (!LF)
4704 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4705 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4706 << RF->getParent() << RF;
4707 else if (!RF)
4708 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4709 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4710 << LF->getParent() << LF;
4711 else if (!LF->getParent()->isUnion() &&
4712 LF->getAccess() != RF->getAccess())
4713 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4714 << LF << LF->getAccess() << RF << RF->getAccess()
4715 << LF->getParent();
4716 }
4717 }
4718
Richard Smith625b8072011-10-31 01:37:14 +00004719 switch (E->getOpcode()) {
4720 default: llvm_unreachable("missing comparison operator");
4721 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4722 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4723 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4724 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4725 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4726 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004727 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004728 }
4729 }
Richard Smithb02e4622012-02-01 01:42:44 +00004730
4731 if (LHSTy->isMemberPointerType()) {
4732 assert(E->isEqualityOp() && "unexpected member pointer operation");
4733 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4734
4735 MemberPtr LHSValue, RHSValue;
4736
4737 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4738 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4739 return false;
4740
4741 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4742 return false;
4743
4744 // C++11 [expr.eq]p2:
4745 // If both operands are null, they compare equal. Otherwise if only one is
4746 // null, they compare unequal.
4747 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4748 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4749 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4750 }
4751
4752 // Otherwise if either is a pointer to a virtual member function, the
4753 // result is unspecified.
4754 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4755 if (MD->isVirtual())
4756 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4757 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4758 if (MD->isVirtual())
4759 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4760
4761 // Otherwise they compare equal if and only if they would refer to the
4762 // same member of the same most derived object or the same subobject if
4763 // they were dereferenced with a hypothetical object of the associated
4764 // class type.
4765 bool Equal = LHSValue == RHSValue;
4766 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4767 }
4768
Richard Smith26f2cac2012-02-14 22:35:28 +00004769 if (LHSTy->isNullPtrType()) {
4770 assert(E->isComparisonOp() && "unexpected nullptr operation");
4771 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
4772 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
4773 // are compared, the result is true of the operator is <=, >= or ==, and
4774 // false otherwise.
4775 BinaryOperator::Opcode Opcode = E->getOpcode();
4776 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
4777 }
4778
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004779 if (!LHSTy->isIntegralOrEnumerationType() ||
4780 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004781 // We can't continue from here for non-integral types.
4782 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004783 }
4784
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004785 // The LHS of a constant expr is always evaluated and needed.
Richard Smith1aa0be82012-03-03 22:46:17 +00004786 APValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004787
4788 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4789 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004790 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004791
Richard Smith745f5142012-01-27 01:14:48 +00004792 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004793 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004794
Richard Smith1aa0be82012-03-03 22:46:17 +00004795 APValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004796
4797 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004798 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004799 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4800 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004801 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004802 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004803 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004804 LHSVal.getLValueOffset() -= AdditionalOffset;
4805 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004806 return true;
4807 }
4808
4809 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004810 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004811 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004812 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4813 LHSVal.getInt().getZExtValue());
4814 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004815 return true;
4816 }
4817
Eli Friedman65639282012-01-04 23:13:47 +00004818 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4819 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004820 if (!LHSVal.getLValueOffset().isZero() ||
4821 !RHSVal.getLValueOffset().isZero())
4822 return false;
4823 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4824 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4825 if (!LHSExpr || !RHSExpr)
4826 return false;
4827 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4828 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4829 if (!LHSAddrExpr || !RHSAddrExpr)
4830 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004831 // Make sure both labels come from the same function.
4832 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4833 RHSAddrExpr->getLabel()->getDeclContext())
4834 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004835 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004836 return true;
4837 }
4838
Eli Friedman42edd0d2009-03-24 01:14:50 +00004839 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004840 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004841 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004842
Richard Smithc49bd112011-10-28 17:51:58 +00004843 APSInt &LHS = LHSVal.getInt();
4844 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004845
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004846 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004847 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004848 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004849 case BO_Mul:
4850 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4851 LHS.getBitWidth() * 2,
4852 std::multiplies<APSInt>()), E);
4853 case BO_Add:
4854 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4855 LHS.getBitWidth() + 1,
4856 std::plus<APSInt>()), E);
4857 case BO_Sub:
4858 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4859 LHS.getBitWidth() + 1,
4860 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004861 case BO_And: return Success(LHS & RHS, E);
4862 case BO_Xor: return Success(LHS ^ RHS, E);
4863 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004864 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004865 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004866 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004867 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004868 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4869 // actually undefined behavior in C++11 due to a language defect.
4870 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4871 LHS.isSigned() && LHS.isMinSignedValue())
4872 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4873 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004874 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004875 // During constant-folding, a negative shift is an opposite shift. Such a
4876 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004877 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004878 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004879 RHS = -RHS;
4880 goto shift_right;
4881 }
4882
4883 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004884 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4885 // shifted type.
4886 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4887 if (SA != RHS) {
4888 CCEDiag(E, diag::note_constexpr_large_shift)
4889 << RHS << E->getType() << LHS.getBitWidth();
4890 } else if (LHS.isSigned()) {
4891 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
Richard Smith925d8e72012-02-08 06:14:53 +00004892 // operand, and must not overflow the corresponding unsigned type.
Richard Smith789f9b62012-01-31 04:08:20 +00004893 if (LHS.isNegative())
4894 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
Richard Smith925d8e72012-02-08 06:14:53 +00004895 else if (LHS.countLeadingZeros() < SA)
4896 CCEDiag(E, diag::note_constexpr_lshift_discards);
Richard Smith789f9b62012-01-31 04:08:20 +00004897 }
4898
Richard Smithc49bd112011-10-28 17:51:58 +00004899 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004900 }
John McCall2de56d12010-08-25 11:45:40 +00004901 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004902 // During constant-folding, a negative shift is an opposite shift. Such a
4903 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004904 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004905 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004906 RHS = -RHS;
4907 goto shift_left;
4908 }
4909
4910 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004911 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4912 // shifted type.
4913 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4914 if (SA != RHS)
4915 CCEDiag(E, diag::note_constexpr_large_shift)
4916 << RHS << E->getType() << LHS.getBitWidth();
4917
Richard Smithc49bd112011-10-28 17:51:58 +00004918 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004919 }
Mike Stump1eb44332009-09-09 15:08:12 +00004920
Richard Smithc49bd112011-10-28 17:51:58 +00004921 case BO_LT: return Success(LHS < RHS, E);
4922 case BO_GT: return Success(LHS > RHS, E);
4923 case BO_LE: return Success(LHS <= RHS, E);
4924 case BO_GE: return Success(LHS >= RHS, E);
4925 case BO_EQ: return Success(LHS == RHS, E);
4926 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004927 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004928}
4929
Ken Dyck8b752f12010-01-27 17:10:57 +00004930CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004931 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4932 // result shall be the alignment of the referenced type."
4933 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4934 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004935
4936 // __alignof is defined to return the preferred alignment.
4937 return Info.Ctx.toCharUnitsFromBits(
4938 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004939}
4940
Ken Dyck8b752f12010-01-27 17:10:57 +00004941CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004942 E = E->IgnoreParens();
4943
4944 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00004945 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00004946 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004947 return Info.Ctx.getDeclAlign(DRE->getDecl(),
4948 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00004949
Chris Lattneraf707ab2009-01-24 21:53:27 +00004950 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00004951 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
4952 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00004953
Chris Lattnere9feb472009-01-24 21:09:06 +00004954 return GetAlignOfType(E->getType());
4955}
4956
4957
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004958/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
4959/// a result as the expression's type.
4960bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
4961 const UnaryExprOrTypeTraitExpr *E) {
4962 switch(E->getKind()) {
4963 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00004964 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004965 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004966 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004967 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00004968 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004969
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004970 case UETT_VecStep: {
4971 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00004972
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004973 if (Ty->isVectorType()) {
4974 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00004975
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004976 // The vec_step built-in functions that take a 3-component
4977 // vector return 4. (OpenCL 1.1 spec 6.11.12)
4978 if (n == 3)
4979 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00004980
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004981 return Success(n, E);
4982 } else
4983 return Success(1, E);
4984 }
4985
4986 case UETT_SizeOf: {
4987 QualType SrcTy = E->getTypeOfArgument();
4988 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
4989 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004990 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
4991 SrcTy = Ref->getPointeeType();
4992
Richard Smith180f4792011-11-10 06:34:14 +00004993 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00004994 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004995 return false;
Richard Smith180f4792011-11-10 06:34:14 +00004996 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004997 }
4998 }
4999
5000 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005001}
5002
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005003bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005004 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005005 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005006 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005007 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005008 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005009 for (unsigned i = 0; i != n; ++i) {
5010 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5011 switch (ON.getKind()) {
5012 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005013 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005014 APSInt IdxResult;
5015 if (!EvaluateInteger(Idx, IdxResult, Info))
5016 return false;
5017 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5018 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005019 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005020 CurrentType = AT->getElementType();
5021 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5022 Result += IdxResult.getSExtValue() * ElementSize;
5023 break;
5024 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005025
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005026 case OffsetOfExpr::OffsetOfNode::Field: {
5027 FieldDecl *MemberDecl = ON.getField();
5028 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005029 if (!RT)
5030 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005031 RecordDecl *RD = RT->getDecl();
5032 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005033 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005034 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005035 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005036 CurrentType = MemberDecl->getType().getNonReferenceType();
5037 break;
5038 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005039
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005040 case OffsetOfExpr::OffsetOfNode::Identifier:
5041 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005042
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005043 case OffsetOfExpr::OffsetOfNode::Base: {
5044 CXXBaseSpecifier *BaseSpec = ON.getBase();
5045 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005046 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005047
5048 // Find the layout of the class whose base we are looking into.
5049 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005050 if (!RT)
5051 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005052 RecordDecl *RD = RT->getDecl();
5053 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5054
5055 // Find the base class itself.
5056 CurrentType = BaseSpec->getType();
5057 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5058 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005059 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005060
5061 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005062 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005063 break;
5064 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005065 }
5066 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005067 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005068}
5069
Chris Lattnerb542afe2008-07-11 19:10:17 +00005070bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005071 switch (E->getOpcode()) {
5072 default:
5073 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5074 // See C99 6.6p3.
5075 return Error(E);
5076 case UO_Extension:
5077 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5078 // If so, we could clear the diagnostic ID.
5079 return Visit(E->getSubExpr());
5080 case UO_Plus:
5081 // The result is just the value.
5082 return Visit(E->getSubExpr());
5083 case UO_Minus: {
5084 if (!Visit(E->getSubExpr()))
5085 return false;
5086 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005087 const APSInt &Value = Result.getInt();
5088 if (Value.isSigned() && Value.isMinSignedValue())
5089 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5090 E->getType());
5091 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005092 }
5093 case UO_Not: {
5094 if (!Visit(E->getSubExpr()))
5095 return false;
5096 if (!Result.isInt()) return Error(E);
5097 return Success(~Result.getInt(), E);
5098 }
5099 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005100 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005101 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005102 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005103 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005104 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005105 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005106}
Mike Stump1eb44332009-09-09 15:08:12 +00005107
Chris Lattner732b2232008-07-12 01:15:53 +00005108/// HandleCast - This is used to evaluate implicit or explicit casts where the
5109/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005110bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5111 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005112 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005113 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005114
Eli Friedman46a52322011-03-25 00:43:55 +00005115 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005116 case CK_BaseToDerived:
5117 case CK_DerivedToBase:
5118 case CK_UncheckedDerivedToBase:
5119 case CK_Dynamic:
5120 case CK_ToUnion:
5121 case CK_ArrayToPointerDecay:
5122 case CK_FunctionToPointerDecay:
5123 case CK_NullToPointer:
5124 case CK_NullToMemberPointer:
5125 case CK_BaseToDerivedMemberPointer:
5126 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005127 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005128 case CK_ConstructorConversion:
5129 case CK_IntegralToPointer:
5130 case CK_ToVoid:
5131 case CK_VectorSplat:
5132 case CK_IntegralToFloating:
5133 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005134 case CK_CPointerToObjCPointerCast:
5135 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005136 case CK_AnyPointerToBlockPointerCast:
5137 case CK_ObjCObjectLValueCast:
5138 case CK_FloatingRealToComplex:
5139 case CK_FloatingComplexToReal:
5140 case CK_FloatingComplexCast:
5141 case CK_FloatingComplexToIntegralComplex:
5142 case CK_IntegralRealToComplex:
5143 case CK_IntegralComplexCast:
5144 case CK_IntegralComplexToFloatingComplex:
5145 llvm_unreachable("invalid cast kind for integral value");
5146
Eli Friedmane50c2972011-03-25 19:07:11 +00005147 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005148 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005149 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005150 case CK_ARCProduceObject:
5151 case CK_ARCConsumeObject:
5152 case CK_ARCReclaimReturnedObject:
5153 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005154 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005155 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005156
Richard Smith7d580a42012-01-17 21:17:26 +00005157 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005158 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005159 case CK_AtomicToNonAtomic:
5160 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005161 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005162 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005163
5164 case CK_MemberPointerToBoolean:
5165 case CK_PointerToBoolean:
5166 case CK_IntegralToBoolean:
5167 case CK_FloatingToBoolean:
5168 case CK_FloatingComplexToBoolean:
5169 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005170 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005171 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005172 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005173 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005174 }
5175
Eli Friedman46a52322011-03-25 00:43:55 +00005176 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005177 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005178 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005179
Eli Friedmanbe265702009-02-20 01:15:07 +00005180 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005181 // Allow casts of address-of-label differences if they are no-ops
5182 // or narrowing. (The narrowing case isn't actually guaranteed to
5183 // be constant-evaluatable except in some narrow cases which are hard
5184 // to detect here. We let it through on the assumption the user knows
5185 // what they are doing.)
5186 if (Result.isAddrLabelDiff())
5187 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005188 // Only allow casts of lvalues if they are lossless.
5189 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5190 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005191
Richard Smithf72fccf2012-01-30 22:27:01 +00005192 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5193 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005194 }
Mike Stump1eb44332009-09-09 15:08:12 +00005195
Eli Friedman46a52322011-03-25 00:43:55 +00005196 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005197 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5198
John McCallefdb83e2010-05-07 21:00:08 +00005199 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005200 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005201 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005202
Daniel Dunbardd211642009-02-19 22:24:01 +00005203 if (LV.getLValueBase()) {
5204 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005205 // FIXME: Allow a larger integer size than the pointer size, and allow
5206 // narrowing back down to pointer width in subsequent integral casts.
5207 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005208 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005209 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005210
Richard Smithb755a9d2011-11-16 07:18:12 +00005211 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005212 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005213 return true;
5214 }
5215
Ken Dycka7305832010-01-15 12:37:54 +00005216 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5217 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005218 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005219 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005220
Eli Friedman46a52322011-03-25 00:43:55 +00005221 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005222 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005223 if (!EvaluateComplex(SubExpr, C, Info))
5224 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005225 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005226 }
Eli Friedman2217c872009-02-22 11:46:18 +00005227
Eli Friedman46a52322011-03-25 00:43:55 +00005228 case CK_FloatingToIntegral: {
5229 APFloat F(0.0);
5230 if (!EvaluateFloat(SubExpr, F, Info))
5231 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005232
Richard Smithc1c5f272011-12-13 06:39:58 +00005233 APSInt Value;
5234 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5235 return false;
5236 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005237 }
5238 }
Mike Stump1eb44332009-09-09 15:08:12 +00005239
Eli Friedman46a52322011-03-25 00:43:55 +00005240 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005241}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005242
Eli Friedman722c7172009-02-28 03:59:05 +00005243bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5244 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005245 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005246 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5247 return false;
5248 if (!LV.isComplexInt())
5249 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005250 return Success(LV.getComplexIntReal(), E);
5251 }
5252
5253 return Visit(E->getSubExpr());
5254}
5255
Eli Friedman664a1042009-02-27 04:45:43 +00005256bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005257 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005258 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005259 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5260 return false;
5261 if (!LV.isComplexInt())
5262 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005263 return Success(LV.getComplexIntImag(), E);
5264 }
5265
Richard Smith8327fad2011-10-24 18:44:57 +00005266 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005267 return Success(0, E);
5268}
5269
Douglas Gregoree8aff02011-01-04 17:33:58 +00005270bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5271 return Success(E->getPackLength(), E);
5272}
5273
Sebastian Redl295995c2010-09-10 20:55:47 +00005274bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5275 return Success(E->getValue(), E);
5276}
5277
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005278//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005279// Float Evaluation
5280//===----------------------------------------------------------------------===//
5281
5282namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005283class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005284 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005285 APFloat &Result;
5286public:
5287 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005288 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005289
Richard Smith1aa0be82012-03-03 22:46:17 +00005290 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005291 Result = V.getFloat();
5292 return true;
5293 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005294
Richard Smith51201882011-12-30 21:15:51 +00005295 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005296 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5297 return true;
5298 }
5299
Chris Lattner019f4e82008-10-06 05:28:25 +00005300 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005301
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005302 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005303 bool VisitBinaryOperator(const BinaryOperator *E);
5304 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005305 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005306
John McCallabd3a852010-05-07 22:08:54 +00005307 bool VisitUnaryReal(const UnaryOperator *E);
5308 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005309
Richard Smith51201882011-12-30 21:15:51 +00005310 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005311};
5312} // end anonymous namespace
5313
5314static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005315 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005316 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005317}
5318
Jay Foad4ba2a172011-01-12 09:06:06 +00005319static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005320 QualType ResultTy,
5321 const Expr *Arg,
5322 bool SNaN,
5323 llvm::APFloat &Result) {
5324 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5325 if (!S) return false;
5326
5327 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5328
5329 llvm::APInt fill;
5330
5331 // Treat empty strings as if they were zero.
5332 if (S->getString().empty())
5333 fill = llvm::APInt(32, 0);
5334 else if (S->getString().getAsInteger(0, fill))
5335 return false;
5336
5337 if (SNaN)
5338 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5339 else
5340 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5341 return true;
5342}
5343
Chris Lattner019f4e82008-10-06 05:28:25 +00005344bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005345 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005346 default:
5347 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5348
Chris Lattner019f4e82008-10-06 05:28:25 +00005349 case Builtin::BI__builtin_huge_val:
5350 case Builtin::BI__builtin_huge_valf:
5351 case Builtin::BI__builtin_huge_vall:
5352 case Builtin::BI__builtin_inf:
5353 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005354 case Builtin::BI__builtin_infl: {
5355 const llvm::fltSemantics &Sem =
5356 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005357 Result = llvm::APFloat::getInf(Sem);
5358 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005359 }
Mike Stump1eb44332009-09-09 15:08:12 +00005360
John McCalldb7b72a2010-02-28 13:00:19 +00005361 case Builtin::BI__builtin_nans:
5362 case Builtin::BI__builtin_nansf:
5363 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005364 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5365 true, Result))
5366 return Error(E);
5367 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005368
Chris Lattner9e621712008-10-06 06:31:58 +00005369 case Builtin::BI__builtin_nan:
5370 case Builtin::BI__builtin_nanf:
5371 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005372 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005373 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005374 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5375 false, Result))
5376 return Error(E);
5377 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005378
5379 case Builtin::BI__builtin_fabs:
5380 case Builtin::BI__builtin_fabsf:
5381 case Builtin::BI__builtin_fabsl:
5382 if (!EvaluateFloat(E->getArg(0), Result, Info))
5383 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005384
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005385 if (Result.isNegative())
5386 Result.changeSign();
5387 return true;
5388
Mike Stump1eb44332009-09-09 15:08:12 +00005389 case Builtin::BI__builtin_copysign:
5390 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005391 case Builtin::BI__builtin_copysignl: {
5392 APFloat RHS(0.);
5393 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5394 !EvaluateFloat(E->getArg(1), RHS, Info))
5395 return false;
5396 Result.copySign(RHS);
5397 return true;
5398 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005399 }
5400}
5401
John McCallabd3a852010-05-07 22:08:54 +00005402bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005403 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5404 ComplexValue CV;
5405 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5406 return false;
5407 Result = CV.FloatReal;
5408 return true;
5409 }
5410
5411 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005412}
5413
5414bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005415 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5416 ComplexValue CV;
5417 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5418 return false;
5419 Result = CV.FloatImag;
5420 return true;
5421 }
5422
Richard Smith8327fad2011-10-24 18:44:57 +00005423 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005424 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5425 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005426 return true;
5427}
5428
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005429bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005430 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005431 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005432 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005433 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005434 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005435 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5436 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005437 Result.changeSign();
5438 return true;
5439 }
5440}
Chris Lattner019f4e82008-10-06 05:28:25 +00005441
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005442bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005443 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5444 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005445
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005446 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005447 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5448 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005449 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005450 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005451 return false;
5452
5453 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005454 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005455 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005456 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005457 break;
John McCall2de56d12010-08-25 11:45:40 +00005458 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005459 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005460 break;
John McCall2de56d12010-08-25 11:45:40 +00005461 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005462 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005463 break;
John McCall2de56d12010-08-25 11:45:40 +00005464 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005465 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005466 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005467 }
Richard Smith7b48a292012-02-01 05:53:12 +00005468
5469 if (Result.isInfinity() || Result.isNaN())
5470 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5471 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005472}
5473
5474bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5475 Result = E->getValue();
5476 return true;
5477}
5478
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005479bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5480 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005481
Eli Friedman2a523ee2011-03-25 00:54:52 +00005482 switch (E->getCastKind()) {
5483 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005484 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005485
5486 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005487 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005488 return EvaluateInteger(SubExpr, IntResult, Info) &&
5489 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5490 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005491 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005492
5493 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005494 if (!Visit(SubExpr))
5495 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005496 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5497 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005498 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005499
Eli Friedman2a523ee2011-03-25 00:54:52 +00005500 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005501 ComplexValue V;
5502 if (!EvaluateComplex(SubExpr, V, Info))
5503 return false;
5504 Result = V.getComplexFloatReal();
5505 return true;
5506 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005507 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005508}
5509
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005510//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005511// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005512//===----------------------------------------------------------------------===//
5513
5514namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005515class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005516 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005517 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005518
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005519public:
John McCallf4cf1a12010-05-07 17:22:02 +00005520 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005521 : ExprEvaluatorBaseTy(info), Result(Result) {}
5522
Richard Smith1aa0be82012-03-03 22:46:17 +00005523 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005524 Result.setFrom(V);
5525 return true;
5526 }
Mike Stump1eb44332009-09-09 15:08:12 +00005527
Eli Friedman7ead5c72012-01-10 04:58:17 +00005528 bool ZeroInitialization(const Expr *E);
5529
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005530 //===--------------------------------------------------------------------===//
5531 // Visitor Methods
5532 //===--------------------------------------------------------------------===//
5533
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005534 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005535 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005536 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005537 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005538 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005539};
5540} // end anonymous namespace
5541
John McCallf4cf1a12010-05-07 17:22:02 +00005542static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5543 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005544 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005545 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005546}
5547
Eli Friedman7ead5c72012-01-10 04:58:17 +00005548bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005549 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005550 if (ElemTy->isRealFloatingType()) {
5551 Result.makeComplexFloat();
5552 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5553 Result.FloatReal = Zero;
5554 Result.FloatImag = Zero;
5555 } else {
5556 Result.makeComplexInt();
5557 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5558 Result.IntReal = Zero;
5559 Result.IntImag = Zero;
5560 }
5561 return true;
5562}
5563
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005564bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5565 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005566
5567 if (SubExpr->getType()->isRealFloatingType()) {
5568 Result.makeComplexFloat();
5569 APFloat &Imag = Result.FloatImag;
5570 if (!EvaluateFloat(SubExpr, Imag, Info))
5571 return false;
5572
5573 Result.FloatReal = APFloat(Imag.getSemantics());
5574 return true;
5575 } else {
5576 assert(SubExpr->getType()->isIntegerType() &&
5577 "Unexpected imaginary literal.");
5578
5579 Result.makeComplexInt();
5580 APSInt &Imag = Result.IntImag;
5581 if (!EvaluateInteger(SubExpr, Imag, Info))
5582 return false;
5583
5584 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5585 return true;
5586 }
5587}
5588
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005589bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005590
John McCall8786da72010-12-14 17:51:41 +00005591 switch (E->getCastKind()) {
5592 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005593 case CK_BaseToDerived:
5594 case CK_DerivedToBase:
5595 case CK_UncheckedDerivedToBase:
5596 case CK_Dynamic:
5597 case CK_ToUnion:
5598 case CK_ArrayToPointerDecay:
5599 case CK_FunctionToPointerDecay:
5600 case CK_NullToPointer:
5601 case CK_NullToMemberPointer:
5602 case CK_BaseToDerivedMemberPointer:
5603 case CK_DerivedToBaseMemberPointer:
5604 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005605 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005606 case CK_ConstructorConversion:
5607 case CK_IntegralToPointer:
5608 case CK_PointerToIntegral:
5609 case CK_PointerToBoolean:
5610 case CK_ToVoid:
5611 case CK_VectorSplat:
5612 case CK_IntegralCast:
5613 case CK_IntegralToBoolean:
5614 case CK_IntegralToFloating:
5615 case CK_FloatingToIntegral:
5616 case CK_FloatingToBoolean:
5617 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005618 case CK_CPointerToObjCPointerCast:
5619 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005620 case CK_AnyPointerToBlockPointerCast:
5621 case CK_ObjCObjectLValueCast:
5622 case CK_FloatingComplexToReal:
5623 case CK_FloatingComplexToBoolean:
5624 case CK_IntegralComplexToReal:
5625 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005626 case CK_ARCProduceObject:
5627 case CK_ARCConsumeObject:
5628 case CK_ARCReclaimReturnedObject:
5629 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005630 case CK_CopyAndAutoreleaseBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005631 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005632
John McCall8786da72010-12-14 17:51:41 +00005633 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005634 case CK_AtomicToNonAtomic:
5635 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005636 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005637 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005638
5639 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005640 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005641 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005642 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005643
5644 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005645 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005646 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005647 return false;
5648
John McCall8786da72010-12-14 17:51:41 +00005649 Result.makeComplexFloat();
5650 Result.FloatImag = APFloat(Real.getSemantics());
5651 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005652 }
5653
John McCall8786da72010-12-14 17:51:41 +00005654 case CK_FloatingComplexCast: {
5655 if (!Visit(E->getSubExpr()))
5656 return false;
5657
5658 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5659 QualType From
5660 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5661
Richard Smithc1c5f272011-12-13 06:39:58 +00005662 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5663 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005664 }
5665
5666 case CK_FloatingComplexToIntegralComplex: {
5667 if (!Visit(E->getSubExpr()))
5668 return false;
5669
5670 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5671 QualType From
5672 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5673 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005674 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5675 To, Result.IntReal) &&
5676 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5677 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005678 }
5679
5680 case CK_IntegralRealToComplex: {
5681 APSInt &Real = Result.IntReal;
5682 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5683 return false;
5684
5685 Result.makeComplexInt();
5686 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5687 return true;
5688 }
5689
5690 case CK_IntegralComplexCast: {
5691 if (!Visit(E->getSubExpr()))
5692 return false;
5693
5694 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5695 QualType From
5696 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5697
Richard Smithf72fccf2012-01-30 22:27:01 +00005698 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5699 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005700 return true;
5701 }
5702
5703 case CK_IntegralComplexToFloatingComplex: {
5704 if (!Visit(E->getSubExpr()))
5705 return false;
5706
5707 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5708 QualType From
5709 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5710 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005711 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5712 To, Result.FloatReal) &&
5713 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5714 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005715 }
5716 }
5717
5718 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005719}
5720
John McCallf4cf1a12010-05-07 17:22:02 +00005721bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005722 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005723 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5724
Richard Smith745f5142012-01-27 01:14:48 +00005725 bool LHSOK = Visit(E->getLHS());
5726 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005727 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005728
John McCallf4cf1a12010-05-07 17:22:02 +00005729 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005730 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005731 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005732
Daniel Dunbar3f279872009-01-29 01:32:56 +00005733 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5734 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005735 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005736 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005737 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005738 if (Result.isComplexFloat()) {
5739 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5740 APFloat::rmNearestTiesToEven);
5741 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5742 APFloat::rmNearestTiesToEven);
5743 } else {
5744 Result.getComplexIntReal() += RHS.getComplexIntReal();
5745 Result.getComplexIntImag() += RHS.getComplexIntImag();
5746 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005747 break;
John McCall2de56d12010-08-25 11:45:40 +00005748 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005749 if (Result.isComplexFloat()) {
5750 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5751 APFloat::rmNearestTiesToEven);
5752 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5753 APFloat::rmNearestTiesToEven);
5754 } else {
5755 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5756 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5757 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005758 break;
John McCall2de56d12010-08-25 11:45:40 +00005759 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005760 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005761 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005762 APFloat &LHS_r = LHS.getComplexFloatReal();
5763 APFloat &LHS_i = LHS.getComplexFloatImag();
5764 APFloat &RHS_r = RHS.getComplexFloatReal();
5765 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005766
Daniel Dunbar3f279872009-01-29 01:32:56 +00005767 APFloat Tmp = LHS_r;
5768 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5769 Result.getComplexFloatReal() = Tmp;
5770 Tmp = LHS_i;
5771 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5772 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5773
5774 Tmp = LHS_r;
5775 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5776 Result.getComplexFloatImag() = Tmp;
5777 Tmp = LHS_i;
5778 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5779 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5780 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005781 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005782 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005783 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5784 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005785 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005786 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5787 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5788 }
5789 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005790 case BO_Div:
5791 if (Result.isComplexFloat()) {
5792 ComplexValue LHS = Result;
5793 APFloat &LHS_r = LHS.getComplexFloatReal();
5794 APFloat &LHS_i = LHS.getComplexFloatImag();
5795 APFloat &RHS_r = RHS.getComplexFloatReal();
5796 APFloat &RHS_i = RHS.getComplexFloatImag();
5797 APFloat &Res_r = Result.getComplexFloatReal();
5798 APFloat &Res_i = Result.getComplexFloatImag();
5799
5800 APFloat Den = RHS_r;
5801 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5802 APFloat Tmp = RHS_i;
5803 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5804 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5805
5806 Res_r = LHS_r;
5807 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5808 Tmp = LHS_i;
5809 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5810 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5811 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5812
5813 Res_i = LHS_i;
5814 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5815 Tmp = LHS_r;
5816 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5817 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5818 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5819 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005820 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5821 return Error(E, diag::note_expr_divide_by_zero);
5822
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005823 ComplexValue LHS = Result;
5824 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5825 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5826 Result.getComplexIntReal() =
5827 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5828 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5829 Result.getComplexIntImag() =
5830 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5831 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5832 }
5833 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005834 }
5835
John McCallf4cf1a12010-05-07 17:22:02 +00005836 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005837}
5838
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005839bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5840 // Get the operand value into 'Result'.
5841 if (!Visit(E->getSubExpr()))
5842 return false;
5843
5844 switch (E->getOpcode()) {
5845 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005846 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005847 case UO_Extension:
5848 return true;
5849 case UO_Plus:
5850 // The result is always just the subexpr.
5851 return true;
5852 case UO_Minus:
5853 if (Result.isComplexFloat()) {
5854 Result.getComplexFloatReal().changeSign();
5855 Result.getComplexFloatImag().changeSign();
5856 }
5857 else {
5858 Result.getComplexIntReal() = -Result.getComplexIntReal();
5859 Result.getComplexIntImag() = -Result.getComplexIntImag();
5860 }
5861 return true;
5862 case UO_Not:
5863 if (Result.isComplexFloat())
5864 Result.getComplexFloatImag().changeSign();
5865 else
5866 Result.getComplexIntImag() = -Result.getComplexIntImag();
5867 return true;
5868 }
5869}
5870
Eli Friedman7ead5c72012-01-10 04:58:17 +00005871bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5872 if (E->getNumInits() == 2) {
5873 if (E->getType()->isComplexType()) {
5874 Result.makeComplexFloat();
5875 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5876 return false;
5877 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5878 return false;
5879 } else {
5880 Result.makeComplexInt();
5881 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5882 return false;
5883 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5884 return false;
5885 }
5886 return true;
5887 }
5888 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5889}
5890
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005891//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005892// Void expression evaluation, primarily for a cast to void on the LHS of a
5893// comma operator
5894//===----------------------------------------------------------------------===//
5895
5896namespace {
5897class VoidExprEvaluator
5898 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5899public:
5900 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5901
Richard Smith1aa0be82012-03-03 22:46:17 +00005902 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005903
5904 bool VisitCastExpr(const CastExpr *E) {
5905 switch (E->getCastKind()) {
5906 default:
5907 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5908 case CK_ToVoid:
5909 VisitIgnoredValue(E->getSubExpr());
5910 return true;
5911 }
5912 }
5913};
5914} // end anonymous namespace
5915
5916static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5917 assert(E->isRValue() && E->getType()->isVoidType());
5918 return VoidExprEvaluator(Info).Visit(E);
5919}
5920
5921//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005922// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005923//===----------------------------------------------------------------------===//
5924
Richard Smith1aa0be82012-03-03 22:46:17 +00005925static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005926 // In C, function designators are not lvalues, but we evaluate them as if they
5927 // are.
5928 if (E->isGLValue() || E->getType()->isFunctionType()) {
5929 LValue LV;
5930 if (!EvaluateLValue(E, LV, Info))
5931 return false;
5932 LV.moveInto(Result);
5933 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005934 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005935 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005936 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005937 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005938 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005939 } else if (E->getType()->hasPointerRepresentation()) {
5940 LValue LV;
5941 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005942 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005943 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005944 } else if (E->getType()->isRealFloatingType()) {
5945 llvm::APFloat F(0.0);
5946 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005947 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00005948 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00005949 } else if (E->getType()->isAnyComplexType()) {
5950 ComplexValue C;
5951 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005952 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005953 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00005954 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005955 MemberPtr P;
5956 if (!EvaluateMemberPointer(E, P, Info))
5957 return false;
5958 P.moveInto(Result);
5959 return true;
Richard Smith51201882011-12-30 21:15:51 +00005960 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005961 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005962 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005963 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00005964 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005965 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00005966 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00005967 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00005968 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00005969 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
5970 return false;
5971 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00005972 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00005973 if (Info.getLangOpts().CPlusPlus0x)
Richard Smith5cfc7d82012-03-15 04:53:45 +00005974 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00005975 << E->getType();
5976 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00005977 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00005978 if (!EvaluateVoid(E, Info))
5979 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005980 } else if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00005981 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00005982 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005983 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00005984 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00005985 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00005986 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005987
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00005988 return true;
5989}
5990
Richard Smith83587db2012-02-15 02:18:13 +00005991/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
5992/// cases, the in-place evaluation is essential, since later initializers for
5993/// an object can indirectly refer to subobjects which were initialized earlier.
5994static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
5995 const Expr *E, CheckConstantExpressionKind CCEK,
5996 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00005997 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00005998 return false;
5999
6000 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006001 // Evaluate arrays and record types in-place, so that later initializers can
6002 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006003 if (E->getType()->isArrayType())
6004 return EvaluateArray(E, This, Result, Info);
6005 else if (E->getType()->isRecordType())
6006 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006007 }
6008
6009 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006010 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006011}
6012
Richard Smithf48fdb02011-12-09 22:58:01 +00006013/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6014/// lvalue-to-rvalue cast if it is an lvalue.
6015static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006016 if (!CheckLiteralType(Info, E))
6017 return false;
6018
Richard Smith1aa0be82012-03-03 22:46:17 +00006019 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006020 return false;
6021
6022 if (E->isGLValue()) {
6023 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006024 LV.setFrom(Info.Ctx, Result);
6025 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006026 return false;
6027 }
6028
Richard Smith1aa0be82012-03-03 22:46:17 +00006029 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006030 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006031}
Richard Smithc49bd112011-10-28 17:51:58 +00006032
Richard Smith51f47082011-10-29 00:50:52 +00006033/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006034/// any crazy technique (that has nothing to do with language standards) that
6035/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006036/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6037/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006038bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006039 // Fast-path evaluations of integer literals, since we sometimes see files
6040 // containing vast quantities of these.
6041 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6042 Result.Val = APValue(APSInt(L->getValue(),
6043 L->getType()->isUnsignedIntegerType()));
6044 return true;
6045 }
6046
Richard Smith2d6a5672012-01-14 04:30:29 +00006047 // FIXME: Evaluating values of large array and record types can cause
6048 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006049 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006050 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006051 return false;
6052
Richard Smithf48fdb02011-12-09 22:58:01 +00006053 EvalInfo Info(Ctx, Result);
6054 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006055}
6056
Jay Foad4ba2a172011-01-12 09:06:06 +00006057bool Expr::EvaluateAsBooleanCondition(bool &Result,
6058 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006059 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006060 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006061 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006062}
6063
Richard Smith80d4b552011-12-28 19:48:30 +00006064bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6065 SideEffectsKind AllowSideEffects) const {
6066 if (!getType()->isIntegralOrEnumerationType())
6067 return false;
6068
Richard Smithc49bd112011-10-28 17:51:58 +00006069 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006070 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6071 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006072 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006073
Richard Smithc49bd112011-10-28 17:51:58 +00006074 Result = ExprResult.Val.getInt();
6075 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006076}
6077
Jay Foad4ba2a172011-01-12 09:06:06 +00006078bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006079 EvalInfo Info(Ctx, Result);
6080
John McCallefdb83e2010-05-07 21:00:08 +00006081 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006082 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6083 !CheckLValueConstantExpression(Info, getExprLoc(),
6084 Ctx.getLValueReferenceType(getType()), LV))
6085 return false;
6086
Richard Smith1aa0be82012-03-03 22:46:17 +00006087 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006088 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006089}
6090
Richard Smith099e7f62011-12-19 06:19:21 +00006091bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6092 const VarDecl *VD,
6093 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006094 // FIXME: Evaluating initializers for large array and record types can cause
6095 // performance problems. Only do so in C++11 for now.
6096 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
David Blaikie4e4d0842012-03-11 07:00:24 +00006097 !Ctx.getLangOpts().CPlusPlus0x)
Richard Smith2d6a5672012-01-14 04:30:29 +00006098 return false;
6099
Richard Smith099e7f62011-12-19 06:19:21 +00006100 Expr::EvalStatus EStatus;
6101 EStatus.Diag = &Notes;
6102
6103 EvalInfo InitInfo(Ctx, EStatus);
6104 InitInfo.setEvaluatingDecl(VD, Value);
6105
6106 LValue LVal;
6107 LVal.set(VD);
6108
Richard Smith51201882011-12-30 21:15:51 +00006109 // C++11 [basic.start.init]p2:
6110 // Variables with static storage duration or thread storage duration shall be
6111 // zero-initialized before any other initialization takes place.
6112 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006113 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006114 !VD->getType()->isReferenceType()) {
6115 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006116 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6117 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006118 return false;
6119 }
6120
Richard Smith83587db2012-02-15 02:18:13 +00006121 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6122 /*AllowNonLiteralTypes=*/true) ||
6123 EStatus.HasSideEffects)
6124 return false;
6125
6126 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6127 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006128}
6129
Richard Smith51f47082011-10-29 00:50:52 +00006130/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6131/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006132bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006133 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006134 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006135}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006136
Jay Foad4ba2a172011-01-12 09:06:06 +00006137bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006138 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006139}
6140
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006141APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006142 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006143 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006144 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006145 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006146 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006147
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006148 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006149}
John McCalld905f5a2010-05-07 05:32:02 +00006150
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006151 bool Expr::EvalResult::isGlobalLValue() const {
6152 assert(Val.isLValue());
6153 return IsGlobalLValue(Val.getLValueBase());
6154 }
6155
6156
John McCalld905f5a2010-05-07 05:32:02 +00006157/// isIntegerConstantExpr - this recursive routine will test if an expression is
6158/// an integer constant expression.
6159
6160/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6161/// comma, etc
6162///
6163/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6164/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6165/// cast+dereference.
6166
6167// CheckICE - This function does the fundamental ICE checking: the returned
6168// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6169// Note that to reduce code duplication, this helper does no evaluation
6170// itself; the caller checks whether the expression is evaluatable, and
6171// in the rare cases where CheckICE actually cares about the evaluated
6172// value, it calls into Evalute.
6173//
6174// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006175// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006176// 1: This expression is not an ICE, but if it isn't evaluated, it's
6177// a legal subexpression for an ICE. This return value is used to handle
6178// the comma operator in C99 mode.
6179// 2: This expression is not an ICE, and is not a legal subexpression for one.
6180
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006181namespace {
6182
John McCalld905f5a2010-05-07 05:32:02 +00006183struct ICEDiag {
6184 unsigned Val;
6185 SourceLocation Loc;
6186
6187 public:
6188 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6189 ICEDiag() : Val(0) {}
6190};
6191
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006192}
6193
6194static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006195
6196static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6197 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006198 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006199 !EVResult.Val.isInt()) {
6200 return ICEDiag(2, E->getLocStart());
6201 }
6202 return NoDiag();
6203}
6204
6205static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6206 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006207 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006208 return ICEDiag(2, E->getLocStart());
6209 }
6210
6211 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006212#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006213#define STMT(Node, Base) case Expr::Node##Class:
6214#define EXPR(Node, Base)
6215#include "clang/AST/StmtNodes.inc"
6216 case Expr::PredefinedExprClass:
6217 case Expr::FloatingLiteralClass:
6218 case Expr::ImaginaryLiteralClass:
6219 case Expr::StringLiteralClass:
6220 case Expr::ArraySubscriptExprClass:
6221 case Expr::MemberExprClass:
6222 case Expr::CompoundAssignOperatorClass:
6223 case Expr::CompoundLiteralExprClass:
6224 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006225 case Expr::DesignatedInitExprClass:
6226 case Expr::ImplicitValueInitExprClass:
6227 case Expr::ParenListExprClass:
6228 case Expr::VAArgExprClass:
6229 case Expr::AddrLabelExprClass:
6230 case Expr::StmtExprClass:
6231 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006232 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006233 case Expr::CXXDynamicCastExprClass:
6234 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006235 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006236 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006237 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006238 case Expr::CXXThisExprClass:
6239 case Expr::CXXThrowExprClass:
6240 case Expr::CXXNewExprClass:
6241 case Expr::CXXDeleteExprClass:
6242 case Expr::CXXPseudoDestructorExprClass:
6243 case Expr::UnresolvedLookupExprClass:
6244 case Expr::DependentScopeDeclRefExprClass:
6245 case Expr::CXXConstructExprClass:
6246 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006247 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006248 case Expr::CXXTemporaryObjectExprClass:
6249 case Expr::CXXUnresolvedConstructExprClass:
6250 case Expr::CXXDependentScopeMemberExprClass:
6251 case Expr::UnresolvedMemberExprClass:
6252 case Expr::ObjCStringLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006253 case Expr::ObjCNumericLiteralClass:
6254 case Expr::ObjCArrayLiteralClass:
6255 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006256 case Expr::ObjCEncodeExprClass:
6257 case Expr::ObjCMessageExprClass:
6258 case Expr::ObjCSelectorExprClass:
6259 case Expr::ObjCProtocolExprClass:
6260 case Expr::ObjCIvarRefExprClass:
6261 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006262 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006263 case Expr::ObjCIsaExprClass:
6264 case Expr::ShuffleVectorExprClass:
6265 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006266 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006267 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006268 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006269 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006270 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006271 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006272 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006273 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006274 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006275 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006276 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006277 return ICEDiag(2, E->getLocStart());
6278
Douglas Gregoree8aff02011-01-04 17:33:58 +00006279 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006280 case Expr::GNUNullExprClass:
6281 // GCC considers the GNU __null value to be an integral constant expression.
6282 return NoDiag();
6283
John McCall91a57552011-07-15 05:09:51 +00006284 case Expr::SubstNonTypeTemplateParmExprClass:
6285 return
6286 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6287
John McCalld905f5a2010-05-07 05:32:02 +00006288 case Expr::ParenExprClass:
6289 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006290 case Expr::GenericSelectionExprClass:
6291 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006292 case Expr::IntegerLiteralClass:
6293 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006294 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006295 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006296 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006297 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006298 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006299 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006300 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006301 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006302 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006303 return NoDiag();
6304 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006305 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006306 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6307 // constant expressions, but they can never be ICEs because an ICE cannot
6308 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006309 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006310 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006311 return CheckEvalInICE(E, Ctx);
6312 return ICEDiag(2, E->getLocStart());
6313 }
Richard Smith359c89d2012-02-24 22:12:32 +00006314 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006315 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6316 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006317 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006318 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006319 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006320 // Parameter variables are never constants. Without this check,
6321 // getAnyInitializer() can find a default argument, which leads
6322 // to chaos.
6323 if (isa<ParmVarDecl>(D))
6324 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6325
6326 // C++ 7.1.5.1p2
6327 // A variable of non-volatile const-qualified integral or enumeration
6328 // type initialized by an ICE can be used in ICEs.
6329 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006330 if (!Dcl->getType()->isIntegralOrEnumerationType())
6331 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6332
Richard Smith099e7f62011-12-19 06:19:21 +00006333 const VarDecl *VD;
6334 // Look for a declaration of this variable that has an initializer, and
6335 // check whether it is an ICE.
6336 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6337 return NoDiag();
6338 else
6339 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006340 }
6341 }
6342 return ICEDiag(2, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006343 }
John McCalld905f5a2010-05-07 05:32:02 +00006344 case Expr::UnaryOperatorClass: {
6345 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6346 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006347 case UO_PostInc:
6348 case UO_PostDec:
6349 case UO_PreInc:
6350 case UO_PreDec:
6351 case UO_AddrOf:
6352 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006353 // C99 6.6/3 allows increment and decrement within unevaluated
6354 // subexpressions of constant expressions, but they can never be ICEs
6355 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006356 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006357 case UO_Extension:
6358 case UO_LNot:
6359 case UO_Plus:
6360 case UO_Minus:
6361 case UO_Not:
6362 case UO_Real:
6363 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006364 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006365 }
6366
6367 // OffsetOf falls through here.
6368 }
6369 case Expr::OffsetOfExprClass: {
6370 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006371 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006372 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006373 // compliance: we should warn earlier for offsetof expressions with
6374 // array subscripts that aren't ICEs, and if the array subscripts
6375 // are ICEs, the value of the offsetof must be an integer constant.
6376 return CheckEvalInICE(E, Ctx);
6377 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006378 case Expr::UnaryExprOrTypeTraitExprClass: {
6379 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6380 if ((Exp->getKind() == UETT_SizeOf) &&
6381 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006382 return ICEDiag(2, E->getLocStart());
6383 return NoDiag();
6384 }
6385 case Expr::BinaryOperatorClass: {
6386 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6387 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006388 case BO_PtrMemD:
6389 case BO_PtrMemI:
6390 case BO_Assign:
6391 case BO_MulAssign:
6392 case BO_DivAssign:
6393 case BO_RemAssign:
6394 case BO_AddAssign:
6395 case BO_SubAssign:
6396 case BO_ShlAssign:
6397 case BO_ShrAssign:
6398 case BO_AndAssign:
6399 case BO_XorAssign:
6400 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006401 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6402 // constant expressions, but they can never be ICEs because an ICE cannot
6403 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006404 return ICEDiag(2, E->getLocStart());
6405
John McCall2de56d12010-08-25 11:45:40 +00006406 case BO_Mul:
6407 case BO_Div:
6408 case BO_Rem:
6409 case BO_Add:
6410 case BO_Sub:
6411 case BO_Shl:
6412 case BO_Shr:
6413 case BO_LT:
6414 case BO_GT:
6415 case BO_LE:
6416 case BO_GE:
6417 case BO_EQ:
6418 case BO_NE:
6419 case BO_And:
6420 case BO_Xor:
6421 case BO_Or:
6422 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006423 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6424 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006425 if (Exp->getOpcode() == BO_Div ||
6426 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006427 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006428 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006429 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006430 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006431 if (REval == 0)
6432 return ICEDiag(1, E->getLocStart());
6433 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006434 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006435 if (LEval.isMinSignedValue())
6436 return ICEDiag(1, E->getLocStart());
6437 }
6438 }
6439 }
John McCall2de56d12010-08-25 11:45:40 +00006440 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006441 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006442 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6443 // if it isn't evaluated.
6444 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6445 return ICEDiag(1, E->getLocStart());
6446 } else {
6447 // In both C89 and C++, commas in ICEs are illegal.
6448 return ICEDiag(2, E->getLocStart());
6449 }
6450 }
6451 if (LHSResult.Val >= RHSResult.Val)
6452 return LHSResult;
6453 return RHSResult;
6454 }
John McCall2de56d12010-08-25 11:45:40 +00006455 case BO_LAnd:
6456 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006457 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6458 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6459 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6460 // Rare case where the RHS has a comma "side-effect"; we need
6461 // to actually check the condition to see whether the side
6462 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006463 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006464 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006465 return RHSResult;
6466 return NoDiag();
6467 }
6468
6469 if (LHSResult.Val >= RHSResult.Val)
6470 return LHSResult;
6471 return RHSResult;
6472 }
6473 }
6474 }
6475 case Expr::ImplicitCastExprClass:
6476 case Expr::CStyleCastExprClass:
6477 case Expr::CXXFunctionalCastExprClass:
6478 case Expr::CXXStaticCastExprClass:
6479 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006480 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006481 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006482 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006483 if (isa<ExplicitCastExpr>(E)) {
6484 if (const FloatingLiteral *FL
6485 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6486 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6487 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6488 APSInt IgnoredVal(DestWidth, !DestSigned);
6489 bool Ignored;
6490 // If the value does not fit in the destination type, the behavior is
6491 // undefined, so we are not required to treat it as a constant
6492 // expression.
6493 if (FL->getValue().convertToInteger(IgnoredVal,
6494 llvm::APFloat::rmTowardZero,
6495 &Ignored) & APFloat::opInvalidOp)
6496 return ICEDiag(2, E->getLocStart());
6497 return NoDiag();
6498 }
6499 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006500 switch (cast<CastExpr>(E)->getCastKind()) {
6501 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006502 case CK_AtomicToNonAtomic:
6503 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006504 case CK_NoOp:
6505 case CK_IntegralToBoolean:
6506 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006507 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006508 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006509 return ICEDiag(2, E->getLocStart());
6510 }
John McCalld905f5a2010-05-07 05:32:02 +00006511 }
John McCall56ca35d2011-02-17 10:25:35 +00006512 case Expr::BinaryConditionalOperatorClass: {
6513 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6514 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6515 if (CommonResult.Val == 2) return CommonResult;
6516 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6517 if (FalseResult.Val == 2) return FalseResult;
6518 if (CommonResult.Val == 1) return CommonResult;
6519 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006520 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006521 return FalseResult;
6522 }
John McCalld905f5a2010-05-07 05:32:02 +00006523 case Expr::ConditionalOperatorClass: {
6524 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6525 // If the condition (ignoring parens) is a __builtin_constant_p call,
6526 // then only the true side is actually considered in an integer constant
6527 // expression, and it is fully evaluated. This is an important GNU
6528 // extension. See GCC PR38377 for discussion.
6529 if (const CallExpr *CallCE
6530 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006531 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6532 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006533 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006534 if (CondResult.Val == 2)
6535 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006536
Richard Smithf48fdb02011-12-09 22:58:01 +00006537 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6538 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006539
John McCalld905f5a2010-05-07 05:32:02 +00006540 if (TrueResult.Val == 2)
6541 return TrueResult;
6542 if (FalseResult.Val == 2)
6543 return FalseResult;
6544 if (CondResult.Val == 1)
6545 return CondResult;
6546 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6547 return NoDiag();
6548 // Rare case where the diagnostics depend on which side is evaluated
6549 // Note that if we get here, CondResult is 0, and at least one of
6550 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006551 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006552 return FalseResult;
6553 }
6554 return TrueResult;
6555 }
6556 case Expr::CXXDefaultArgExprClass:
6557 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6558 case Expr::ChooseExprClass: {
6559 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6560 }
6561 }
6562
David Blaikie30263482012-01-20 21:50:17 +00006563 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006564}
6565
Richard Smithf48fdb02011-12-09 22:58:01 +00006566/// Evaluate an expression as a C++11 integral constant expression.
6567static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6568 const Expr *E,
6569 llvm::APSInt *Value,
6570 SourceLocation *Loc) {
6571 if (!E->getType()->isIntegralOrEnumerationType()) {
6572 if (Loc) *Loc = E->getExprLoc();
6573 return false;
6574 }
6575
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006576 APValue Result;
6577 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006578 return false;
6579
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006580 assert(Result.isInt() && "pointer cast to int is not an ICE");
6581 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006582 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006583}
6584
Richard Smithdd1f29b2011-12-12 09:28:41 +00006585bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006586 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006587 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6588
John McCalld905f5a2010-05-07 05:32:02 +00006589 ICEDiag d = CheckICE(this, Ctx);
6590 if (d.Val != 0) {
6591 if (Loc) *Loc = d.Loc;
6592 return false;
6593 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006594 return true;
6595}
6596
6597bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6598 SourceLocation *Loc, bool isEvaluated) const {
David Blaikie4e4d0842012-03-11 07:00:24 +00006599 if (Ctx.getLangOpts().CPlusPlus0x)
Richard Smithf48fdb02011-12-09 22:58:01 +00006600 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6601
6602 if (!isIntegerConstantExpr(Ctx, Loc))
6603 return false;
6604 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006605 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006606 return true;
6607}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006608
Richard Smith70488e22012-02-14 21:38:30 +00006609bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6610 return CheckICE(this, Ctx).Val == 0;
6611}
6612
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006613bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6614 SourceLocation *Loc) const {
6615 // We support this checking in C++98 mode in order to diagnose compatibility
6616 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006617 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006618
Richard Smith70488e22012-02-14 21:38:30 +00006619 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006620 Expr::EvalStatus Status;
6621 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6622 Status.Diag = &Diags;
6623 EvalInfo Info(Ctx, Status);
6624
6625 APValue Scratch;
6626 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6627
6628 if (!Diags.empty()) {
6629 IsConstExpr = false;
6630 if (Loc) *Loc = Diags[0].first;
6631 } else if (!IsConstExpr) {
6632 // FIXME: This shouldn't happen.
6633 if (Loc) *Loc = getExprLoc();
6634 }
6635
6636 return IsConstExpr;
6637}
Richard Smith745f5142012-01-27 01:14:48 +00006638
6639bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6640 llvm::SmallVectorImpl<
6641 PartialDiagnosticAt> &Diags) {
6642 // FIXME: It would be useful to check constexpr function templates, but at the
6643 // moment the constant expression evaluator cannot cope with the non-rigorous
6644 // ASTs which we build for dependent expressions.
6645 if (FD->isDependentContext())
6646 return true;
6647
6648 Expr::EvalStatus Status;
6649 Status.Diag = &Diags;
6650
6651 EvalInfo Info(FD->getASTContext(), Status);
6652 Info.CheckingPotentialConstantExpression = true;
6653
6654 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6655 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6656
6657 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6658 // is a temporary being used as the 'this' pointer.
6659 LValue This;
6660 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006661 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006662
Richard Smith745f5142012-01-27 01:14:48 +00006663 ArrayRef<const Expr*> Args;
6664
6665 SourceLocation Loc = FD->getLocation();
6666
Richard Smith1aa0be82012-03-03 22:46:17 +00006667 APValue Scratch;
6668 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006669 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006670 else
Richard Smith745f5142012-01-27 01:14:48 +00006671 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6672 Args, FD->getBody(), Info, Scratch);
6673
6674 return Diags.empty();
6675}