blob: 4ae5ab42ff79d0a043cd77e9341b28a8b4a01a60 [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 Smith47a1eed2011-10-29 20:57:55 +0000267 /// A core constant value. This can be the value of any constant expression,
268 /// or a pointer or reference to a non-static object or function parameter.
Richard Smithe24f5fc2011-11-17 22:56:20 +0000269 ///
270 /// For an LValue, the base and offset are stored in the APValue subobject,
271 /// but the other information is stored in the SubobjectDesignator. For all
272 /// other value kinds, the value is stored directly in the APValue subobject.
Richard Smith47a1eed2011-10-29 20:57:55 +0000273 class CCValue : public APValue {
274 typedef llvm::APSInt APSInt;
275 typedef llvm::APFloat APFloat;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000276 /// If the value is a reference or pointer, this is a description of how the
277 /// subobject was specified.
278 SubobjectDesignator Designator;
Richard Smith47a1eed2011-10-29 20:57:55 +0000279 public:
Richard Smith177dce72011-11-01 16:57:24 +0000280 struct GlobalValue {};
281
Richard Smith47a1eed2011-10-29 20:57:55 +0000282 CCValue() {}
283 explicit CCValue(const APSInt &I) : APValue(I) {}
284 explicit CCValue(const APFloat &F) : APValue(F) {}
285 CCValue(const APValue *E, unsigned N) : APValue(E, N) {}
286 CCValue(const APSInt &R, const APSInt &I) : APValue(R, I) {}
287 CCValue(const APFloat &R, const APFloat &I) : APValue(R, I) {}
Richard Smith83587db2012-02-15 02:18:13 +0000288 CCValue(const CCValue &V) : APValue(V), Designator(V.Designator) {}
289 CCValue(LValueBase B, const CharUnits &O, unsigned I,
Richard Smith0a3bdb62011-11-04 02:25:55 +0000290 const SubobjectDesignator &D) :
Richard Smith83587db2012-02-15 02:18:13 +0000291 APValue(B, O, APValue::NoLValuePath(), I), Designator(D) {}
Richard Smithb4e85ed2012-01-06 16:39:00 +0000292 CCValue(ASTContext &Ctx, const APValue &V, GlobalValue) :
Richard Smith83587db2012-02-15 02:18:13 +0000293 APValue(V), Designator(Ctx, V) {
294 }
Richard Smithe24f5fc2011-11-17 22:56:20 +0000295 CCValue(const ValueDecl *D, bool IsDerivedMember,
296 ArrayRef<const CXXRecordDecl*> Path) :
297 APValue(D, IsDerivedMember, Path) {}
Eli Friedman65639282012-01-04 23:13:47 +0000298 CCValue(const AddrLabelExpr* LHSExpr, const AddrLabelExpr* RHSExpr) :
299 APValue(LHSExpr, RHSExpr) {}
Richard Smith47a1eed2011-10-29 20:57:55 +0000300
Richard Smith0a3bdb62011-11-04 02:25:55 +0000301 SubobjectDesignator &getLValueDesignator() {
302 assert(getKind() == LValue);
303 return Designator;
304 }
305 const SubobjectDesignator &getLValueDesignator() const {
306 return const_cast<CCValue*>(this)->getLValueDesignator();
307 }
Richard Smith83587db2012-02-15 02:18:13 +0000308 APValue toAPValue() const {
309 if (!isLValue())
310 return *this;
311
312 if (Designator.Invalid) {
313 // This is not a core constant expression. An appropriate diagnostic
314 // will have already been produced.
315 return APValue(getLValueBase(), getLValueOffset(),
316 APValue::NoLValuePath(), getLValueCallIndex());
317 }
318
319 return APValue(getLValueBase(), getLValueOffset(),
320 Designator.Entries, Designator.IsOnePastTheEnd,
321 getLValueCallIndex());
322 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000323 };
324
Richard Smithd0dccea2011-10-28 22:34:42 +0000325 /// A stack frame in the constexpr call stack.
326 struct CallStackFrame {
327 EvalInfo &Info;
328
329 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000330 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000331
Richard Smith08d6e032011-12-16 19:06:07 +0000332 /// CallLoc - The location of the call expression for this call.
333 SourceLocation CallLoc;
334
335 /// Callee - The function which was called.
336 const FunctionDecl *Callee;
337
Richard Smith83587db2012-02-15 02:18:13 +0000338 /// Index - The call index of this call.
339 unsigned Index;
340
Richard Smith180f4792011-11-10 06:34:14 +0000341 /// This - The binding for the this pointer in this call, if any.
342 const LValue *This;
343
Richard Smithd0dccea2011-10-28 22:34:42 +0000344 /// ParmBindings - Parameter bindings for this function call, indexed by
345 /// parameters' function scope indices.
Richard Smith47a1eed2011-10-29 20:57:55 +0000346 const CCValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000347
Richard Smithbd552ef2011-10-31 05:52:43 +0000348 typedef llvm::DenseMap<const Expr*, CCValue> MapTy;
349 typedef MapTy::const_iterator temp_iterator;
350 /// Temporaries - Temporary lvalues materialized within this stack frame.
351 MapTy Temporaries;
352
Richard Smith08d6e032011-12-16 19:06:07 +0000353 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
354 const FunctionDecl *Callee, const LValue *This,
Richard Smith180f4792011-11-10 06:34:14 +0000355 const CCValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000356 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000357 };
358
Richard Smithdd1f29b2011-12-12 09:28:41 +0000359 /// A partial diagnostic which we might know in advance that we are not going
360 /// to emit.
361 class OptionalDiagnostic {
362 PartialDiagnostic *Diag;
363
364 public:
365 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
366
367 template<typename T>
368 OptionalDiagnostic &operator<<(const T &v) {
369 if (Diag)
370 *Diag << v;
371 return *this;
372 }
Richard Smith789f9b62012-01-31 04:08:20 +0000373
374 OptionalDiagnostic &operator<<(const APSInt &I) {
375 if (Diag) {
376 llvm::SmallVector<char, 32> Buffer;
377 I.toString(Buffer);
378 *Diag << StringRef(Buffer.data(), Buffer.size());
379 }
380 return *this;
381 }
382
383 OptionalDiagnostic &operator<<(const APFloat &F) {
384 if (Diag) {
385 llvm::SmallVector<char, 32> Buffer;
386 F.toString(Buffer);
387 *Diag << StringRef(Buffer.data(), Buffer.size());
388 }
389 return *this;
390 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000391 };
392
Richard Smith83587db2012-02-15 02:18:13 +0000393 /// EvalInfo - This is a private struct used by the evaluator to capture
394 /// information about a subexpression as it is folded. It retains information
395 /// about the AST context, but also maintains information about the folded
396 /// expression.
397 ///
398 /// If an expression could be evaluated, it is still possible it is not a C
399 /// "integer constant expression" or constant expression. If not, this struct
400 /// captures information about how and why not.
401 ///
402 /// One bit of information passed *into* the request for constant folding
403 /// indicates whether the subexpression is "evaluated" or not according to C
404 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
405 /// evaluate the expression regardless of what the RHS is, but C only allows
406 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000407 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000408 ASTContext &Ctx;
Richard Smithbd552ef2011-10-31 05:52:43 +0000409
410 /// EvalStatus - Contains information about the evaluation.
411 Expr::EvalStatus &EvalStatus;
412
413 /// CurrentCall - The top of the constexpr call stack.
414 CallStackFrame *CurrentCall;
415
Richard Smithbd552ef2011-10-31 05:52:43 +0000416 /// CallStackDepth - The number of calls in the call stack right now.
417 unsigned CallStackDepth;
418
Richard Smith83587db2012-02-15 02:18:13 +0000419 /// NextCallIndex - The next call index to assign.
420 unsigned NextCallIndex;
421
Richard Smithbd552ef2011-10-31 05:52:43 +0000422 typedef llvm::DenseMap<const OpaqueValueExpr*, CCValue> MapTy;
423 /// OpaqueValues - Values used as the common expression in a
424 /// BinaryConditionalOperator.
425 MapTy OpaqueValues;
426
427 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000428 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000429 CallStackFrame BottomFrame;
430
Richard Smith180f4792011-11-10 06:34:14 +0000431 /// EvaluatingDecl - This is the declaration whose initializer is being
432 /// evaluated, if any.
433 const VarDecl *EvaluatingDecl;
434
435 /// EvaluatingDeclValue - This is the value being constructed for the
436 /// declaration whose initializer is being evaluated, if any.
437 APValue *EvaluatingDeclValue;
438
Richard Smithc1c5f272011-12-13 06:39:58 +0000439 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
440 /// notes attached to it will also be stored, otherwise they will not be.
441 bool HasActiveDiagnostic;
442
Richard Smith745f5142012-01-27 01:14:48 +0000443 /// CheckingPotentialConstantExpression - Are we checking whether the
444 /// expression is a potential constant expression? If so, some diagnostics
445 /// are suppressed.
446 bool CheckingPotentialConstantExpression;
447
Richard Smithbd552ef2011-10-31 05:52:43 +0000448
449 EvalInfo(const ASTContext &C, Expr::EvalStatus &S)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000450 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000451 CallStackDepth(0), NextCallIndex(1),
452 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000453 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
454 CheckingPotentialConstantExpression(false) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000455
Richard Smithbd552ef2011-10-31 05:52:43 +0000456 const CCValue *getOpaqueValue(const OpaqueValueExpr *e) const {
457 MapTy::const_iterator i = OpaqueValues.find(e);
458 if (i == OpaqueValues.end()) return 0;
459 return &i->second;
460 }
461
Richard Smith180f4792011-11-10 06:34:14 +0000462 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
463 EvaluatingDecl = VD;
464 EvaluatingDeclValue = &Value;
465 }
466
Richard Smithc18c4232011-11-21 19:36:32 +0000467 const LangOptions &getLangOpts() const { return Ctx.getLangOptions(); }
468
Richard Smithc1c5f272011-12-13 06:39:58 +0000469 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000470 // Don't perform any constexpr calls (other than the call we're checking)
471 // when checking a potential constant expression.
472 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
473 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000474 if (NextCallIndex == 0) {
475 // NextCallIndex has wrapped around.
476 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
477 return false;
478 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000479 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
480 return true;
481 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
482 << getLangOpts().ConstexprCallDepth;
483 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000484 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000485
Richard Smith83587db2012-02-15 02:18:13 +0000486 CallStackFrame *getCallFrame(unsigned CallIndex) {
487 assert(CallIndex && "no call index in getCallFrame");
488 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
489 // be null in this loop.
490 CallStackFrame *Frame = CurrentCall;
491 while (Frame->Index > CallIndex)
492 Frame = Frame->Caller;
493 return (Frame->Index == CallIndex) ? Frame : 0;
494 }
495
Richard Smithc1c5f272011-12-13 06:39:58 +0000496 private:
497 /// Add a diagnostic to the diagnostics list.
498 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
499 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
500 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
501 return EvalStatus.Diag->back().second;
502 }
503
Richard Smith08d6e032011-12-16 19:06:07 +0000504 /// Add notes containing a call stack to the current point of evaluation.
505 void addCallStack(unsigned Limit);
506
Richard Smithc1c5f272011-12-13 06:39:58 +0000507 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000508 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000509 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
510 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000511 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000512 // If we have a prior diagnostic, it will be noting that the expression
513 // isn't a constant expression. This diagnostic is more important.
514 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000515 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000516 unsigned CallStackNotes = CallStackDepth - 1;
517 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
518 if (Limit)
519 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000520 if (CheckingPotentialConstantExpression)
521 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000522
Richard Smithc1c5f272011-12-13 06:39:58 +0000523 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000524 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000525 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
526 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000527 if (!CheckingPotentialConstantExpression)
528 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000529 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000530 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000531 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000532 return OptionalDiagnostic();
533 }
534
535 /// Diagnose that the evaluation does not produce a C++11 core constant
536 /// expression.
Richard Smith7098cbd2011-12-21 05:04:46 +0000537 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
538 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000539 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000540 // Don't override a previous diagnostic.
541 if (!EvalStatus.Diag || !EvalStatus.Diag->empty())
542 return OptionalDiagnostic();
Richard Smithc1c5f272011-12-13 06:39:58 +0000543 return Diag(Loc, DiagId, ExtraNotes);
544 }
545
546 /// Add a note to a prior diagnostic.
547 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
548 if (!HasActiveDiagnostic)
549 return OptionalDiagnostic();
550 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000551 }
Richard Smith099e7f62011-12-19 06:19:21 +0000552
553 /// Add a stack of notes to a prior diagnostic.
554 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
555 if (HasActiveDiagnostic) {
556 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
557 Diags.begin(), Diags.end());
558 }
559 }
Richard Smith745f5142012-01-27 01:14:48 +0000560
561 /// Should we continue evaluation as much as possible after encountering a
562 /// construct which can't be folded?
563 bool keepEvaluatingAfterFailure() {
Richard Smith74e1ad92012-02-16 02:46:34 +0000564 return CheckingPotentialConstantExpression &&
565 EvalStatus.Diag && EvalStatus.Diag->empty();
Richard Smith745f5142012-01-27 01:14:48 +0000566 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000567 };
Richard Smithf15fda02012-02-02 01:16:57 +0000568
569 /// Object used to treat all foldable expressions as constant expressions.
570 struct FoldConstant {
571 bool Enabled;
572
573 explicit FoldConstant(EvalInfo &Info)
574 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
575 !Info.EvalStatus.HasSideEffects) {
576 }
577 // Treat the value we've computed since this object was created as constant.
578 void Fold(EvalInfo &Info) {
579 if (Enabled && !Info.EvalStatus.Diag->empty() &&
580 !Info.EvalStatus.HasSideEffects)
581 Info.EvalStatus.Diag->clear();
582 }
583 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000584
585 /// RAII object used to suppress diagnostics and side-effects from a
586 /// speculative evaluation.
587 class SpeculativeEvaluationRAII {
588 EvalInfo &Info;
589 Expr::EvalStatus Old;
590
591 public:
592 SpeculativeEvaluationRAII(EvalInfo &Info,
593 llvm::SmallVectorImpl<PartialDiagnosticAt>
594 *NewDiag = 0)
595 : Info(Info), Old(Info.EvalStatus) {
596 Info.EvalStatus.Diag = NewDiag;
597 }
598 ~SpeculativeEvaluationRAII() {
599 Info.EvalStatus = Old;
600 }
601 };
Richard Smith08d6e032011-12-16 19:06:07 +0000602}
Richard Smithbd552ef2011-10-31 05:52:43 +0000603
Richard Smithb4e85ed2012-01-06 16:39:00 +0000604bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
605 CheckSubobjectKind CSK) {
606 if (Invalid)
607 return false;
608 if (isOnePastTheEnd()) {
609 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_past_end_subobject)
610 << CSK;
611 setInvalid();
612 return false;
613 }
614 return true;
615}
616
617void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
618 const Expr *E, uint64_t N) {
619 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
620 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
621 << static_cast<int>(N) << /*array*/ 0
622 << static_cast<unsigned>(MostDerivedArraySize);
623 else
624 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_array_index)
625 << static_cast<int>(N) << /*non-array*/ 1;
626 setInvalid();
627}
628
Richard Smith08d6e032011-12-16 19:06:07 +0000629CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
630 const FunctionDecl *Callee, const LValue *This,
631 const CCValue *Arguments)
632 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000633 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000634 Info.CurrentCall = this;
635 ++Info.CallStackDepth;
636}
637
638CallStackFrame::~CallStackFrame() {
639 assert(Info.CurrentCall == this && "calls retired out of order");
640 --Info.CallStackDepth;
641 Info.CurrentCall = Caller;
642}
643
644/// Produce a string describing the given constexpr call.
645static void describeCall(CallStackFrame *Frame, llvm::raw_ostream &Out) {
646 unsigned ArgIndex = 0;
647 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000648 !isa<CXXConstructorDecl>(Frame->Callee) &&
649 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000650
651 if (!IsMemberCall)
652 Out << *Frame->Callee << '(';
653
654 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
655 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000656 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000657 Out << ", ";
658
659 const ParmVarDecl *Param = *I;
660 const CCValue &Arg = Frame->Arguments[ArgIndex];
661 if (!Arg.isLValue() || Arg.getLValueDesignator().Invalid)
662 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
663 else {
Richard Smith83587db2012-02-15 02:18:13 +0000664 // Convert the CCValue to an APValue without checking for constantness.
Richard Smith08d6e032011-12-16 19:06:07 +0000665 APValue Value(Arg.getLValueBase(), Arg.getLValueOffset(),
666 Arg.getLValueDesignator().Entries,
Richard Smith83587db2012-02-15 02:18:13 +0000667 Arg.getLValueDesignator().IsOnePastTheEnd,
668 Arg.getLValueCallIndex());
Richard Smith08d6e032011-12-16 19:06:07 +0000669 Value.printPretty(Out, Frame->Info.Ctx, Param->getType());
670 }
671
672 if (ArgIndex == 0 && IsMemberCall)
673 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000674 }
675
Richard Smith08d6e032011-12-16 19:06:07 +0000676 Out << ')';
677}
678
679void EvalInfo::addCallStack(unsigned Limit) {
680 // Determine which calls to skip, if any.
681 unsigned ActiveCalls = CallStackDepth - 1;
682 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
683 if (Limit && Limit < ActiveCalls) {
684 SkipStart = Limit / 2 + Limit % 2;
685 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000686 }
687
Richard Smith08d6e032011-12-16 19:06:07 +0000688 // Walk the call stack and add the diagnostics.
689 unsigned CallIdx = 0;
690 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
691 Frame = Frame->Caller, ++CallIdx) {
692 // Skip this call?
693 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
694 if (CallIdx == SkipStart) {
695 // Note that we're skipping calls.
696 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
697 << unsigned(ActiveCalls - Limit);
698 }
699 continue;
700 }
701
702 llvm::SmallVector<char, 128> Buffer;
703 llvm::raw_svector_ostream Out(Buffer);
704 describeCall(Frame, Out);
705 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
706 }
707}
708
709namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000710 struct ComplexValue {
711 private:
712 bool IsInt;
713
714 public:
715 APSInt IntReal, IntImag;
716 APFloat FloatReal, FloatImag;
717
718 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
719
720 void makeComplexFloat() { IsInt = false; }
721 bool isComplexFloat() const { return !IsInt; }
722 APFloat &getComplexFloatReal() { return FloatReal; }
723 APFloat &getComplexFloatImag() { return FloatImag; }
724
725 void makeComplexInt() { IsInt = true; }
726 bool isComplexInt() const { return IsInt; }
727 APSInt &getComplexIntReal() { return IntReal; }
728 APSInt &getComplexIntImag() { return IntImag; }
729
Richard Smith47a1eed2011-10-29 20:57:55 +0000730 void moveInto(CCValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000731 if (isComplexFloat())
Richard Smith47a1eed2011-10-29 20:57:55 +0000732 v = CCValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000733 else
Richard Smith47a1eed2011-10-29 20:57:55 +0000734 v = CCValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000735 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000736 void setFrom(const CCValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000737 assert(v.isComplexFloat() || v.isComplexInt());
738 if (v.isComplexFloat()) {
739 makeComplexFloat();
740 FloatReal = v.getComplexFloatReal();
741 FloatImag = v.getComplexFloatImag();
742 } else {
743 makeComplexInt();
744 IntReal = v.getComplexIntReal();
745 IntImag = v.getComplexIntImag();
746 }
747 }
John McCallf4cf1a12010-05-07 17:22:02 +0000748 };
John McCallefdb83e2010-05-07 21:00:08 +0000749
750 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000751 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000752 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000753 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000754 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000755
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000756 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000757 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000758 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000759 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000760 SubobjectDesignator &getLValueDesignator() { return Designator; }
761 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000762
Richard Smith47a1eed2011-10-29 20:57:55 +0000763 void moveInto(CCValue &V) const {
Richard Smith83587db2012-02-15 02:18:13 +0000764 V = CCValue(Base, Offset, CallIndex, Designator);
John McCallefdb83e2010-05-07 21:00:08 +0000765 }
Richard Smith47a1eed2011-10-29 20:57:55 +0000766 void setFrom(const CCValue &V) {
767 assert(V.isLValue());
768 Base = V.getLValueBase();
769 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000770 CallIndex = V.getLValueCallIndex();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000771 Designator = V.getLValueDesignator();
772 }
773
Richard Smith83587db2012-02-15 02:18:13 +0000774 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000775 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000776 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000777 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000778 Designator = SubobjectDesignator(getType(B));
779 }
780
781 // Check that this LValue is not based on a null pointer. If it is, produce
782 // a diagnostic and mark the designator as invalid.
783 bool checkNullPointer(EvalInfo &Info, const Expr *E,
784 CheckSubobjectKind CSK) {
785 if (Designator.Invalid)
786 return false;
787 if (!Base) {
788 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_null_subobject)
789 << CSK;
790 Designator.setInvalid();
791 return false;
792 }
793 return true;
794 }
795
796 // Check this LValue refers to an object. If not, set the designator to be
797 // invalid and emit a diagnostic.
798 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
799 return checkNullPointer(Info, E, CSK) &&
800 Designator.checkSubobject(Info, E, CSK);
801 }
802
803 void addDecl(EvalInfo &Info, const Expr *E,
804 const Decl *D, bool Virtual = false) {
805 checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base);
806 Designator.addDeclUnchecked(D, Virtual);
807 }
808 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
809 checkSubobject(Info, E, CSK_ArrayToPointer);
810 Designator.addArrayUnchecked(CAT);
811 }
Richard Smith86024012012-02-18 22:04:06 +0000812 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
813 checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real);
814 Designator.addComplexUnchecked(EltTy, Imag);
815 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000816 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
817 if (!checkNullPointer(Info, E, CSK_ArrayIndex))
818 return;
819 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000820 }
John McCallefdb83e2010-05-07 21:00:08 +0000821 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000822
823 struct MemberPtr {
824 MemberPtr() {}
825 explicit MemberPtr(const ValueDecl *Decl) :
826 DeclAndIsDerivedMember(Decl, false), Path() {}
827
828 /// The member or (direct or indirect) field referred to by this member
829 /// pointer, or 0 if this is a null member pointer.
830 const ValueDecl *getDecl() const {
831 return DeclAndIsDerivedMember.getPointer();
832 }
833 /// Is this actually a member of some type derived from the relevant class?
834 bool isDerivedMember() const {
835 return DeclAndIsDerivedMember.getInt();
836 }
837 /// Get the class which the declaration actually lives in.
838 const CXXRecordDecl *getContainingRecord() const {
839 return cast<CXXRecordDecl>(
840 DeclAndIsDerivedMember.getPointer()->getDeclContext());
841 }
842
843 void moveInto(CCValue &V) const {
844 V = CCValue(getDecl(), isDerivedMember(), Path);
845 }
846 void setFrom(const CCValue &V) {
847 assert(V.isMemberPointer());
848 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
849 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
850 Path.clear();
851 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
852 Path.insert(Path.end(), P.begin(), P.end());
853 }
854
855 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
856 /// whether the member is a member of some class derived from the class type
857 /// of the member pointer.
858 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
859 /// Path - The path of base/derived classes from the member declaration's
860 /// class (exclusive) to the class type of the member pointer (inclusive).
861 SmallVector<const CXXRecordDecl*, 4> Path;
862
863 /// Perform a cast towards the class of the Decl (either up or down the
864 /// hierarchy).
865 bool castBack(const CXXRecordDecl *Class) {
866 assert(!Path.empty());
867 const CXXRecordDecl *Expected;
868 if (Path.size() >= 2)
869 Expected = Path[Path.size() - 2];
870 else
871 Expected = getContainingRecord();
872 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
873 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
874 // if B does not contain the original member and is not a base or
875 // derived class of the class containing the original member, the result
876 // of the cast is undefined.
877 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
878 // (D::*). We consider that to be a language defect.
879 return false;
880 }
881 Path.pop_back();
882 return true;
883 }
884 /// Perform a base-to-derived member pointer cast.
885 bool castToDerived(const CXXRecordDecl *Derived) {
886 if (!getDecl())
887 return true;
888 if (!isDerivedMember()) {
889 Path.push_back(Derived);
890 return true;
891 }
892 if (!castBack(Derived))
893 return false;
894 if (Path.empty())
895 DeclAndIsDerivedMember.setInt(false);
896 return true;
897 }
898 /// Perform a derived-to-base member pointer cast.
899 bool castToBase(const CXXRecordDecl *Base) {
900 if (!getDecl())
901 return true;
902 if (Path.empty())
903 DeclAndIsDerivedMember.setInt(true);
904 if (isDerivedMember()) {
905 Path.push_back(Base);
906 return true;
907 }
908 return castBack(Base);
909 }
910 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000911
Richard Smithb02e4622012-02-01 01:42:44 +0000912 /// Compare two member pointers, which are assumed to be of the same type.
913 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
914 if (!LHS.getDecl() || !RHS.getDecl())
915 return !LHS.getDecl() && !RHS.getDecl();
916 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
917 return false;
918 return LHS.Path == RHS.Path;
919 }
920
Richard Smithc1c5f272011-12-13 06:39:58 +0000921 /// Kinds of constant expression checking, for diagnostics.
922 enum CheckConstantExpressionKind {
923 CCEK_Constant, ///< A normal constant.
924 CCEK_ReturnValue, ///< A constexpr function return value.
925 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
926 };
John McCallf4cf1a12010-05-07 17:22:02 +0000927}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000928
Richard Smith47a1eed2011-10-29 20:57:55 +0000929static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000930static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
931 const LValue &This, const Expr *E,
932 CheckConstantExpressionKind CCEK = CCEK_Constant,
933 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000934static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
935static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000936static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
937 EvalInfo &Info);
938static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000939static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith47a1eed2011-10-29 20:57:55 +0000940static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000941 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000942static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000943static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000944
945//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000946// Misc utilities
947//===----------------------------------------------------------------------===//
948
Richard Smith180f4792011-11-10 06:34:14 +0000949/// Should this call expression be treated as a string literal?
950static bool IsStringLiteralCall(const CallExpr *E) {
951 unsigned Builtin = E->isBuiltinCall();
952 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
953 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
954}
955
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000956static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000957 // C++11 [expr.const]p3 An address constant expression is a prvalue core
958 // constant expression of pointer type that evaluates to...
959
960 // ... a null pointer value, or a prvalue core constant expression of type
961 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000962 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000963
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000964 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
965 // ... the address of an object with static storage duration,
966 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
967 return VD->hasGlobalStorage();
968 // ... the address of a function,
969 return isa<FunctionDecl>(D);
970 }
971
972 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000973 switch (E->getStmtClass()) {
974 default:
975 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000976 case Expr::CompoundLiteralExprClass: {
977 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
978 return CLE->isFileScope() && CLE->isLValue();
979 }
Richard Smith180f4792011-11-10 06:34:14 +0000980 // A string literal has static storage duration.
981 case Expr::StringLiteralClass:
982 case Expr::PredefinedExprClass:
983 case Expr::ObjCStringLiteralClass:
984 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000985 case Expr::CXXTypeidExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000986 return true;
987 case Expr::CallExprClass:
988 return IsStringLiteralCall(cast<CallExpr>(E));
989 // For GCC compatibility, &&label has static storage duration.
990 case Expr::AddrLabelExprClass:
991 return true;
992 // A Block literal expression may be used as the initialization value for
993 // Block variables at global or local static scope.
994 case Expr::BlockExprClass:
995 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000996 case Expr::ImplicitValueInitExprClass:
997 // FIXME:
998 // We can never form an lvalue with an implicit value initialization as its
999 // base through expression evaluation, so these only appear in one case: the
1000 // implicit variable declaration we invent when checking whether a constexpr
1001 // constructor can produce a constant expression. We must assume that such
1002 // an expression might be a global lvalue.
1003 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001004 }
John McCall42c8f872010-05-10 23:27:23 +00001005}
1006
Richard Smith83587db2012-02-15 02:18:13 +00001007static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1008 assert(Base && "no location for a null lvalue");
1009 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1010 if (VD)
1011 Info.Note(VD->getLocation(), diag::note_declared_at);
1012 else
1013 Info.Note(Base.dyn_cast<const Expr*>()->getExprLoc(),
1014 diag::note_constexpr_temporary_here);
1015}
1016
Richard Smith9a17a682011-11-07 05:07:52 +00001017/// Check that this reference or pointer core constant expression is a valid
Richard Smithb4e85ed2012-01-06 16:39:00 +00001018/// value for an address or reference constant expression. Type T should be
Richard Smith61e61622012-01-12 06:08:57 +00001019/// either LValue or CCValue. Return true if we can fold this expression,
1020/// whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00001021static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1022 QualType Type, const LValue &LVal) {
1023 bool IsReferenceType = Type->isReferenceType();
1024
Richard Smithc1c5f272011-12-13 06:39:58 +00001025 APValue::LValueBase Base = LVal.getLValueBase();
1026 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1027
Richard Smithb78ae972012-02-18 04:58:18 +00001028 // Check that the object is a global. Note that the fake 'this' object we
1029 // manufacture when checking potential constant expressions is conservatively
1030 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +00001031 if (!IsGlobalLValue(Base)) {
1032 if (Info.getLangOpts().CPlusPlus0x) {
1033 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001034 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1035 << IsReferenceType << !Designator.Entries.empty()
1036 << !!VD << VD;
1037 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001038 } else {
Richard Smith83587db2012-02-15 02:18:13 +00001039 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +00001040 }
Richard Smith61e61622012-01-12 06:08:57 +00001041 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +00001042 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001043 }
Richard Smith83587db2012-02-15 02:18:13 +00001044 assert((Info.CheckingPotentialConstantExpression ||
1045 LVal.getLValueCallIndex() == 0) &&
1046 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +00001047
1048 // Allow address constant expressions to be past-the-end pointers. This is
1049 // an extension: the standard requires them to point to an object.
1050 if (!IsReferenceType)
1051 return true;
1052
1053 // A reference constant expression must refer to an object.
1054 if (!Base) {
1055 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001056 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001057 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001058 }
1059
Richard Smithc1c5f272011-12-13 06:39:58 +00001060 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001061 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001062 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001063 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001064 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001065 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001066 }
1067
Richard Smith9a17a682011-11-07 05:07:52 +00001068 return true;
1069}
1070
Richard Smith51201882011-12-30 21:15:51 +00001071/// Check that this core constant expression is of literal type, and if not,
1072/// produce an appropriate diagnostic.
1073static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1074 if (!E->isRValue() || E->getType()->isLiteralType())
1075 return true;
1076
1077 // Prvalue constant expressions must be of literal types.
1078 if (Info.getLangOpts().CPlusPlus0x)
1079 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral)
1080 << E->getType();
1081 else
1082 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1083 return false;
1084}
1085
Richard Smith47a1eed2011-10-29 20:57:55 +00001086/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001087/// constant expression. If not, report an appropriate diagnostic. Does not
1088/// check that the expression is of literal type.
1089static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1090 QualType Type, const APValue &Value) {
1091 // Core issue 1454: For a literal constant expression of array or class type,
1092 // each subobject of its value shall have been initialized by a constant
1093 // expression.
1094 if (Value.isArray()) {
1095 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1096 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1097 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1098 Value.getArrayInitializedElt(I)))
1099 return false;
1100 }
1101 if (!Value.hasArrayFiller())
1102 return true;
1103 return CheckConstantExpression(Info, DiagLoc, EltTy,
1104 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001105 }
Richard Smith83587db2012-02-15 02:18:13 +00001106 if (Value.isUnion() && Value.getUnionField()) {
1107 return CheckConstantExpression(Info, DiagLoc,
1108 Value.getUnionField()->getType(),
1109 Value.getUnionValue());
1110 }
1111 if (Value.isStruct()) {
1112 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1113 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1114 unsigned BaseIndex = 0;
1115 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1116 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1117 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1118 Value.getStructBase(BaseIndex)))
1119 return false;
1120 }
1121 }
1122 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1123 I != E; ++I) {
1124 if (!CheckConstantExpression(Info, DiagLoc, (*I)->getType(),
1125 Value.getStructField((*I)->getFieldIndex())))
1126 return false;
1127 }
1128 }
1129
1130 if (Value.isLValue()) {
1131 CCValue Val(Info.Ctx, Value, CCValue::GlobalValue());
1132 LValue LVal;
1133 LVal.setFrom(Val);
1134 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1135 }
1136
1137 // Everything else is fine.
1138 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001139}
1140
Richard Smith9e36b532011-10-31 05:11:32 +00001141const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001142 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001143}
1144
1145static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001146 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001147}
1148
Richard Smith65ac5982011-11-01 21:06:14 +00001149static bool IsWeakLValue(const LValue &Value) {
1150 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001151 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001152}
1153
Richard Smithe24f5fc2011-11-17 22:56:20 +00001154static bool EvalPointerValueAsBool(const CCValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001155 // A null base expression indicates a null pointer. These are always
1156 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001157 if (!Value.getLValueBase()) {
1158 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001159 return true;
1160 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001161
Richard Smithe24f5fc2011-11-17 22:56:20 +00001162 // We have a non-null base. These are generally known to be true, but if it's
1163 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001164 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001165 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001166 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001167}
1168
Richard Smith47a1eed2011-10-29 20:57:55 +00001169static bool HandleConversionToBool(const CCValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001170 switch (Val.getKind()) {
1171 case APValue::Uninitialized:
1172 return false;
1173 case APValue::Int:
1174 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001175 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001176 case APValue::Float:
1177 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001178 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001179 case APValue::ComplexInt:
1180 Result = Val.getComplexIntReal().getBoolValue() ||
1181 Val.getComplexIntImag().getBoolValue();
1182 return true;
1183 case APValue::ComplexFloat:
1184 Result = !Val.getComplexFloatReal().isZero() ||
1185 !Val.getComplexFloatImag().isZero();
1186 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001187 case APValue::LValue:
1188 return EvalPointerValueAsBool(Val, Result);
1189 case APValue::MemberPointer:
1190 Result = Val.getMemberPointerDecl();
1191 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001192 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001193 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001194 case APValue::Struct:
1195 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001196 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001197 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001198 }
1199
Richard Smithc49bd112011-10-28 17:51:58 +00001200 llvm_unreachable("unknown APValue kind");
1201}
1202
1203static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1204 EvalInfo &Info) {
1205 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith47a1eed2011-10-29 20:57:55 +00001206 CCValue Val;
Richard Smithc49bd112011-10-28 17:51:58 +00001207 if (!Evaluate(Val, Info, E))
1208 return false;
1209 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001210}
1211
Richard Smithc1c5f272011-12-13 06:39:58 +00001212template<typename T>
1213static bool HandleOverflow(EvalInfo &Info, const Expr *E,
1214 const T &SrcValue, QualType DestType) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001215 Info.Diag(E->getExprLoc(), diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001216 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001217 return false;
1218}
1219
1220static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1221 QualType SrcType, const APFloat &Value,
1222 QualType DestType, APSInt &Result) {
1223 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001224 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001225 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001226
Richard Smithc1c5f272011-12-13 06:39:58 +00001227 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001228 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001229 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1230 & APFloat::opInvalidOp)
1231 return HandleOverflow(Info, E, Value, DestType);
1232 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001233}
1234
Richard Smithc1c5f272011-12-13 06:39:58 +00001235static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1236 QualType SrcType, QualType DestType,
1237 APFloat &Result) {
1238 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001239 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001240 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1241 APFloat::rmNearestTiesToEven, &ignored)
1242 & APFloat::opOverflow)
1243 return HandleOverflow(Info, E, Value, DestType);
1244 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001245}
1246
Richard Smithf72fccf2012-01-30 22:27:01 +00001247static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1248 QualType DestType, QualType SrcType,
1249 APSInt &Value) {
1250 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001251 APSInt Result = Value;
1252 // Figure out if this is a truncate, extend or noop cast.
1253 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001254 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001255 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001256 return Result;
1257}
1258
Richard Smithc1c5f272011-12-13 06:39:58 +00001259static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1260 QualType SrcType, const APSInt &Value,
1261 QualType DestType, APFloat &Result) {
1262 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1263 if (Result.convertFromAPInt(Value, Value.isSigned(),
1264 APFloat::rmNearestTiesToEven)
1265 & APFloat::opOverflow)
1266 return HandleOverflow(Info, E, Value, DestType);
1267 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001268}
1269
Eli Friedmane6a24e82011-12-22 03:51:45 +00001270static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1271 llvm::APInt &Res) {
1272 CCValue SVal;
1273 if (!Evaluate(SVal, Info, E))
1274 return false;
1275 if (SVal.isInt()) {
1276 Res = SVal.getInt();
1277 return true;
1278 }
1279 if (SVal.isFloat()) {
1280 Res = SVal.getFloat().bitcastToAPInt();
1281 return true;
1282 }
1283 if (SVal.isVector()) {
1284 QualType VecTy = E->getType();
1285 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1286 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1287 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1288 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1289 Res = llvm::APInt::getNullValue(VecSize);
1290 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1291 APValue &Elt = SVal.getVectorElt(i);
1292 llvm::APInt EltAsInt;
1293 if (Elt.isInt()) {
1294 EltAsInt = Elt.getInt();
1295 } else if (Elt.isFloat()) {
1296 EltAsInt = Elt.getFloat().bitcastToAPInt();
1297 } else {
1298 // Don't try to handle vectors of anything other than int or float
1299 // (not sure if it's possible to hit this case).
1300 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1301 return false;
1302 }
1303 unsigned BaseEltSize = EltAsInt.getBitWidth();
1304 if (BigEndian)
1305 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1306 else
1307 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1308 }
1309 return true;
1310 }
1311 // Give up if the input isn't an int, float, or vector. For example, we
1312 // reject "(v4i16)(intptr_t)&a".
1313 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1314 return false;
1315}
1316
Richard Smithb4e85ed2012-01-06 16:39:00 +00001317/// Cast an lvalue referring to a base subobject to a derived class, by
1318/// truncating the lvalue's path to the given length.
1319static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1320 const RecordDecl *TruncatedType,
1321 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001322 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001323
1324 // Check we actually point to a derived class object.
1325 if (TruncatedElements == D.Entries.size())
1326 return true;
1327 assert(TruncatedElements >= D.MostDerivedPathLength &&
1328 "not casting to a derived class");
1329 if (!Result.checkSubobject(Info, E, CSK_Derived))
1330 return false;
1331
1332 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001333 const RecordDecl *RD = TruncatedType;
1334 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
Richard Smith180f4792011-11-10 06:34:14 +00001335 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1336 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001337 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001338 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001339 else
Richard Smith180f4792011-11-10 06:34:14 +00001340 Result.Offset -= Layout.getBaseClassOffset(Base);
1341 RD = Base;
1342 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001343 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001344 return true;
1345}
1346
Richard Smithb4e85ed2012-01-06 16:39:00 +00001347static void HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001348 const CXXRecordDecl *Derived,
1349 const CXXRecordDecl *Base,
1350 const ASTRecordLayout *RL = 0) {
1351 if (!RL) RL = &Info.Ctx.getASTRecordLayout(Derived);
1352 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001353 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
Richard Smith180f4792011-11-10 06:34:14 +00001354}
1355
Richard Smithb4e85ed2012-01-06 16:39:00 +00001356static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001357 const CXXRecordDecl *DerivedDecl,
1358 const CXXBaseSpecifier *Base) {
1359 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1360
1361 if (!Base->isVirtual()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001362 HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001363 return true;
1364 }
1365
Richard Smithb4e85ed2012-01-06 16:39:00 +00001366 SubobjectDesignator &D = Obj.Designator;
1367 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001368 return false;
1369
Richard Smithb4e85ed2012-01-06 16:39:00 +00001370 // Extract most-derived object and corresponding type.
1371 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1372 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1373 return false;
1374
1375 // Find the virtual base class.
Richard Smith180f4792011-11-10 06:34:14 +00001376 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1377 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001378 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001379 return true;
1380}
1381
1382/// Update LVal to refer to the given field, which must be a member of the type
1383/// currently described by LVal.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001384static void HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001385 const FieldDecl *FD,
1386 const ASTRecordLayout *RL = 0) {
1387 if (!RL)
1388 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
1389
1390 unsigned I = FD->getFieldIndex();
1391 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001392 LVal.addDecl(Info, E, FD);
Richard Smith180f4792011-11-10 06:34:14 +00001393}
1394
Richard Smithd9b02e72012-01-25 22:15:11 +00001395/// Update LVal to refer to the given indirect field.
1396static void HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
1397 LValue &LVal,
1398 const IndirectFieldDecl *IFD) {
1399 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1400 CE = IFD->chain_end(); C != CE; ++C)
1401 HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C));
1402}
1403
Richard Smith180f4792011-11-10 06:34:14 +00001404/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001405static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1406 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001407 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1408 // extension.
1409 if (Type->isVoidType() || Type->isFunctionType()) {
1410 Size = CharUnits::One();
1411 return true;
1412 }
1413
1414 if (!Type->isConstantSizeType()) {
1415 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001416 // FIXME: Better diagnostic.
1417 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001418 return false;
1419 }
1420
1421 Size = Info.Ctx.getTypeSizeInChars(Type);
1422 return true;
1423}
1424
1425/// Update a pointer value to model pointer arithmetic.
1426/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001427/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001428/// \param LVal - The pointer value to be updated.
1429/// \param EltTy - The pointee type represented by LVal.
1430/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001431static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1432 LValue &LVal, QualType EltTy,
1433 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001434 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001435 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001436 return false;
1437
1438 // Compute the new offset in the appropriate width.
1439 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001440 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001441 return true;
1442}
1443
Richard Smith86024012012-02-18 22:04:06 +00001444/// Update an lvalue to refer to a component of a complex number.
1445/// \param Info - Information about the ongoing evaluation.
1446/// \param LVal - The lvalue to be updated.
1447/// \param EltTy - The complex number's component type.
1448/// \param Imag - False for the real component, true for the imaginary.
1449static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1450 LValue &LVal, QualType EltTy,
1451 bool Imag) {
1452 if (Imag) {
1453 CharUnits SizeOfComponent;
1454 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1455 return false;
1456 LVal.Offset += SizeOfComponent;
1457 }
1458 LVal.addComplex(Info, E, EltTy, Imag);
1459 return true;
1460}
1461
Richard Smith03f96112011-10-24 17:54:18 +00001462/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001463static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1464 const VarDecl *VD,
Richard Smith177dce72011-11-01 16:57:24 +00001465 CallStackFrame *Frame, CCValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001466 // If this is a parameter to an active constexpr function call, perform
1467 // argument substitution.
1468 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001469 // Assume arguments of a potential constant expression are unknown
1470 // constant expressions.
1471 if (Info.CheckingPotentialConstantExpression)
1472 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001473 if (!Frame || !Frame->Arguments) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001474 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001475 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001476 }
Richard Smith177dce72011-11-01 16:57:24 +00001477 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1478 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001479 }
Richard Smith03f96112011-10-24 17:54:18 +00001480
Richard Smith099e7f62011-12-19 06:19:21 +00001481 // Dig out the initializer, and use the declaration which it's attached to.
1482 const Expr *Init = VD->getAnyInitializer(VD);
1483 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001484 // If we're checking a potential constant expression, the variable could be
1485 // initialized later.
1486 if (!Info.CheckingPotentialConstantExpression)
1487 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001488 return false;
1489 }
1490
Richard Smith180f4792011-11-10 06:34:14 +00001491 // If we're currently evaluating the initializer of this declaration, use that
1492 // in-flight value.
1493 if (Info.EvaluatingDecl == VD) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001494 Result = CCValue(Info.Ctx, *Info.EvaluatingDeclValue,
1495 CCValue::GlobalValue());
Richard Smith180f4792011-11-10 06:34:14 +00001496 return !Result.isUninit();
1497 }
1498
Richard Smith65ac5982011-11-01 21:06:14 +00001499 // Never evaluate the initializer of a weak variable. We can't be sure that
1500 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001501 if (VD->isWeak()) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001502 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001503 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001504 }
Richard Smith65ac5982011-11-01 21:06:14 +00001505
Richard Smith099e7f62011-12-19 06:19:21 +00001506 // Check that we can fold the initializer. In C++, we will have already done
1507 // this in the cases where it matters for conformance.
1508 llvm::SmallVector<PartialDiagnosticAt, 8> Notes;
1509 if (!VD->evaluateValue(Notes)) {
1510 Info.Diag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1511 Notes.size() + 1) << VD;
1512 Info.Note(VD->getLocation(), diag::note_declared_at);
1513 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001514 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001515 } else if (!VD->checkInitIsICE()) {
1516 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_var_init_non_constant,
1517 Notes.size() + 1) << VD;
1518 Info.Note(VD->getLocation(), diag::note_declared_at);
1519 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001520 }
Richard Smith03f96112011-10-24 17:54:18 +00001521
Richard Smithb4e85ed2012-01-06 16:39:00 +00001522 Result = CCValue(Info.Ctx, *VD->getEvaluatedValue(), CCValue::GlobalValue());
Richard Smith47a1eed2011-10-29 20:57:55 +00001523 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001524}
1525
Richard Smithc49bd112011-10-28 17:51:58 +00001526static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001527 Qualifiers Quals = T.getQualifiers();
1528 return Quals.hasConst() && !Quals.hasVolatile();
1529}
1530
Richard Smith59efe262011-11-11 04:05:33 +00001531/// Get the base index of the given base class within an APValue representing
1532/// the given derived class.
1533static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1534 const CXXRecordDecl *Base) {
1535 Base = Base->getCanonicalDecl();
1536 unsigned Index = 0;
1537 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1538 E = Derived->bases_end(); I != E; ++I, ++Index) {
1539 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1540 return Index;
1541 }
1542
1543 llvm_unreachable("base class missing from derived class's bases list");
1544}
1545
Richard Smithf3908f22012-02-17 03:35:37 +00001546/// Extract the value of a character from a string literal.
1547static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
1548 uint64_t Index) {
1549 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1550 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1551 assert(S && "unexpected string literal expression kind");
1552
1553 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
1554 Lit->getType()->getArrayElementTypeNoTypeQual()->isUnsignedIntegerType());
1555 if (Index < S->getLength())
1556 Value = S->getCodeUnit(Index);
1557 return Value;
1558}
1559
Richard Smithcc5d4f62011-11-07 09:22:26 +00001560/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001561static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
1562 CCValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001563 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001564 if (Sub.Invalid)
1565 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001566 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001567 if (Sub.isOnePastTheEnd()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001568 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001569 (unsigned)diag::note_constexpr_read_past_end :
1570 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001571 return false;
1572 }
Richard Smithf64699e2011-11-11 08:28:03 +00001573 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001574 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001575 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1576 // This object might be initialized later.
1577 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001578
Richard Smithcc5d4f62011-11-07 09:22:26 +00001579 const APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001580 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001581 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001582 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001583 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001584 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001585 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001586 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001587 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001588 // Note, it should not be possible to form a pointer with a valid
1589 // designator which points more than one past the end of the array.
1590 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001591 (unsigned)diag::note_constexpr_read_past_end :
1592 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001593 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001594 }
Richard Smithf3908f22012-02-17 03:35:37 +00001595 // An array object is represented as either an Array APValue or as an
1596 // LValue which refers to a string literal.
1597 if (O->isLValue()) {
1598 assert(I == N - 1 && "extracting subobject of character?");
1599 assert(!O->hasLValuePath() || O->getLValuePath().empty());
1600 Obj = CCValue(ExtractStringLiteralCharacter(
1601 Info, O->getLValueBase().get<const Expr*>(), Index));
1602 return true;
1603 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001604 O = &O->getArrayInitializedElt(Index);
1605 else
1606 O = &O->getArrayFiller();
1607 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001608 } else if (ObjType->isAnyComplexType()) {
1609 // Next subobject is a complex number.
1610 uint64_t Index = Sub.Entries[I].ArrayIndex;
1611 if (Index > 1) {
1612 Info.Diag(E->getExprLoc(), Info.getLangOpts().CPlusPlus0x ?
1613 (unsigned)diag::note_constexpr_read_past_end :
1614 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1615 return false;
1616 }
1617 assert(I == N - 1 && "extracting subobject of scalar?");
1618 if (O->isComplexInt()) {
1619 Obj = CCValue(Index ? O->getComplexIntImag()
1620 : O->getComplexIntReal());
1621 } else {
1622 assert(O->isComplexFloat());
1623 Obj = CCValue(Index ? O->getComplexFloatImag()
1624 : O->getComplexFloatReal());
1625 }
1626 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001627 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001628 if (Field->isMutable()) {
1629 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_mutable, 1)
1630 << Field;
1631 Info.Note(Field->getLocation(), diag::note_declared_at);
1632 return false;
1633 }
1634
Richard Smith180f4792011-11-10 06:34:14 +00001635 // Next subobject is a class, struct or union field.
1636 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1637 if (RD->isUnion()) {
1638 const FieldDecl *UnionField = O->getUnionField();
1639 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001640 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001641 Info.Diag(E->getExprLoc(),
1642 diag::note_constexpr_read_inactive_union_member)
1643 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001644 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001645 }
Richard Smith180f4792011-11-10 06:34:14 +00001646 O = &O->getUnionValue();
1647 } else
1648 O = &O->getStructField(Field->getFieldIndex());
1649 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001650
1651 if (ObjType.isVolatileQualified()) {
1652 if (Info.getLangOpts().CPlusPlus) {
1653 // FIXME: Include a description of the path to the volatile subobject.
1654 Info.Diag(E->getExprLoc(), diag::note_constexpr_ltor_volatile_obj, 1)
1655 << 2 << Field;
1656 Info.Note(Field->getLocation(), diag::note_declared_at);
1657 } else {
1658 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1659 }
1660 return false;
1661 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001662 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001663 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001664 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1665 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1666 O = &O->getStructBase(getBaseIndex(Derived, Base));
1667 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001668 }
Richard Smith180f4792011-11-10 06:34:14 +00001669
Richard Smithf48fdb02011-12-09 22:58:01 +00001670 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001671 if (!Info.CheckingPotentialConstantExpression)
1672 Info.Diag(E->getExprLoc(), diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001673 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001674 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001675 }
1676
Richard Smithb4e85ed2012-01-06 16:39:00 +00001677 Obj = CCValue(Info.Ctx, *O, CCValue::GlobalValue());
Richard Smithcc5d4f62011-11-07 09:22:26 +00001678 return true;
1679}
1680
Richard Smithf15fda02012-02-02 01:16:57 +00001681/// Find the position where two subobject designators diverge, or equivalently
1682/// the length of the common initial subsequence.
1683static unsigned FindDesignatorMismatch(QualType ObjType,
1684 const SubobjectDesignator &A,
1685 const SubobjectDesignator &B,
1686 bool &WasArrayIndex) {
1687 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1688 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001689 if (!ObjType.isNull() &&
1690 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001691 // Next subobject is an array element.
1692 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1693 WasArrayIndex = true;
1694 return I;
1695 }
Richard Smith86024012012-02-18 22:04:06 +00001696 if (ObjType->isAnyComplexType())
1697 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1698 else
1699 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001700 } else {
1701 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1702 WasArrayIndex = false;
1703 return I;
1704 }
1705 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1706 // Next subobject is a field.
1707 ObjType = FD->getType();
1708 else
1709 // Next subobject is a base class.
1710 ObjType = QualType();
1711 }
1712 }
1713 WasArrayIndex = false;
1714 return I;
1715}
1716
1717/// Determine whether the given subobject designators refer to elements of the
1718/// same array object.
1719static bool AreElementsOfSameArray(QualType ObjType,
1720 const SubobjectDesignator &A,
1721 const SubobjectDesignator &B) {
1722 if (A.Entries.size() != B.Entries.size())
1723 return false;
1724
1725 bool IsArray = A.MostDerivedArraySize != 0;
1726 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1727 // A is a subobject of the array element.
1728 return false;
1729
1730 // If A (and B) designates an array element, the last entry will be the array
1731 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1732 // of length 1' case, and the entire path must match.
1733 bool WasArrayIndex;
1734 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1735 return CommonLength >= A.Entries.size() - IsArray;
1736}
1737
Richard Smith180f4792011-11-10 06:34:14 +00001738/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1739/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1740/// for looking up the glvalue referred to by an entity of reference type.
1741///
1742/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001743/// \param Conv - The expression for which we are performing the conversion.
1744/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001745/// \param Type - The type we expect this conversion to produce, before
1746/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001747/// \param LVal - The glvalue on which we are attempting to perform this action.
1748/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001749static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1750 QualType Type,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001751 const LValue &LVal, CCValue &RVal) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001752 // In C, an lvalue-to-rvalue conversion is never a constant expression.
1753 if (!Info.getLangOpts().CPlusPlus)
1754 Info.CCEDiag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
1755
Richard Smithb4e85ed2012-01-06 16:39:00 +00001756 if (LVal.Designator.Invalid)
1757 // A diagnostic will have already been produced.
1758 return false;
1759
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001760 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith7098cbd2011-12-21 05:04:46 +00001761 SourceLocation Loc = Conv->getExprLoc();
Richard Smithc49bd112011-10-28 17:51:58 +00001762
Richard Smithf48fdb02011-12-09 22:58:01 +00001763 if (!LVal.Base) {
1764 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith7098cbd2011-12-21 05:04:46 +00001765 Info.Diag(Loc, diag::note_invalid_subexpr_in_const_expr);
1766 return false;
1767 }
1768
Richard Smith83587db2012-02-15 02:18:13 +00001769 CallStackFrame *Frame = 0;
1770 if (LVal.CallIndex) {
1771 Frame = Info.getCallFrame(LVal.CallIndex);
1772 if (!Frame) {
1773 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1774 NoteLValueLocation(Info, LVal.Base);
1775 return false;
1776 }
1777 }
1778
Richard Smith7098cbd2011-12-21 05:04:46 +00001779 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1780 // is not a constant expression (even if the object is non-volatile). We also
1781 // apply this rule to C++98, in order to conform to the expected 'volatile'
1782 // semantics.
1783 if (Type.isVolatileQualified()) {
1784 if (Info.getLangOpts().CPlusPlus)
1785 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_type) << Type;
1786 else
1787 Info.Diag(Loc);
Richard Smithc49bd112011-10-28 17:51:58 +00001788 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001789 }
Richard Smithc49bd112011-10-28 17:51:58 +00001790
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001791 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001792 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1793 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001794 // expressions are constant expressions too. Inside constexpr functions,
1795 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001796 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001797 const VarDecl *VD = dyn_cast<VarDecl>(D);
Richard Smithf15fda02012-02-02 01:16:57 +00001798 if (const VarDecl *VDef = VD->getDefinition())
1799 VD = VDef;
Richard Smithf48fdb02011-12-09 22:58:01 +00001800 if (!VD || VD->isInvalidDecl()) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001801 Info.Diag(Loc);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001802 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001803 }
1804
Richard Smith7098cbd2011-12-21 05:04:46 +00001805 // DR1313: If the object is volatile-qualified but the glvalue was not,
1806 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001807 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001808 if (VT.isVolatileQualified()) {
1809 if (Info.getLangOpts().CPlusPlus) {
1810 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
1811 Info.Note(VD->getLocation(), diag::note_declared_at);
1812 } else {
1813 Info.Diag(Loc);
Richard Smithf48fdb02011-12-09 22:58:01 +00001814 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001815 return false;
1816 }
1817
1818 if (!isa<ParmVarDecl>(VD)) {
1819 if (VD->isConstexpr()) {
1820 // OK, we can read this variable.
1821 } else if (VT->isIntegralOrEnumerationType()) {
1822 if (!VT.isConstQualified()) {
1823 if (Info.getLangOpts().CPlusPlus) {
1824 Info.Diag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
1825 Info.Note(VD->getLocation(), diag::note_declared_at);
1826 } else {
1827 Info.Diag(Loc);
1828 }
1829 return false;
1830 }
1831 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1832 // We support folding of const floating-point types, in order to make
1833 // static const data members of such types (supported as an extension)
1834 // more useful.
1835 if (Info.getLangOpts().CPlusPlus0x) {
1836 Info.CCEDiag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1837 Info.Note(VD->getLocation(), diag::note_declared_at);
1838 } else {
1839 Info.CCEDiag(Loc);
1840 }
1841 } else {
1842 // FIXME: Allow folding of values of any literal type in all languages.
1843 if (Info.getLangOpts().CPlusPlus0x) {
1844 Info.Diag(Loc, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
1845 Info.Note(VD->getLocation(), diag::note_declared_at);
1846 } else {
1847 Info.Diag(Loc);
1848 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001849 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001850 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001851 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001852
Richard Smithf48fdb02011-12-09 22:58:01 +00001853 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001854 return false;
1855
Richard Smith47a1eed2011-10-29 20:57:55 +00001856 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001857 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001858
1859 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1860 // conversion. This happens when the declaration and the lvalue should be
1861 // considered synonymous, for instance when initializing an array of char
1862 // from a string literal. Continue as if the initializer lvalue was the
1863 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001864 assert(RVal.getLValueOffset().isZero() &&
1865 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001866 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001867
1868 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1869 Frame = Info.getCallFrame(CallIndex);
1870 if (!Frame) {
1871 Info.Diag(Loc, diag::note_constexpr_lifetime_ended, 1) << !Base;
1872 NoteLValueLocation(Info, RVal.getLValueBase());
1873 return false;
1874 }
1875 } else {
1876 Frame = 0;
1877 }
Richard Smithc49bd112011-10-28 17:51:58 +00001878 }
1879
Richard Smith7098cbd2011-12-21 05:04:46 +00001880 // Volatile temporary objects cannot be read in constant expressions.
1881 if (Base->getType().isVolatileQualified()) {
1882 if (Info.getLangOpts().CPlusPlus) {
1883 Info.Diag(Loc, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
1884 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1885 } else {
1886 Info.Diag(Loc);
1887 }
1888 return false;
1889 }
1890
Richard Smithcc5d4f62011-11-07 09:22:26 +00001891 if (Frame) {
1892 // If this is a temporary expression with a nontrivial initializer, grab the
1893 // value from the relevant stack frame.
1894 RVal = Frame->Temporaries[Base];
1895 } else if (const CompoundLiteralExpr *CLE
1896 = dyn_cast<CompoundLiteralExpr>(Base)) {
1897 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1898 // initializer until now for such expressions. Such an expression can't be
1899 // an ICE in C, so this only matters for fold.
1900 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1901 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1902 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001903 } else if (isa<StringLiteral>(Base)) {
1904 // We represent a string literal array as an lvalue pointing at the
1905 // corresponding expression, rather than building an array of chars.
1906 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1907 RVal = CCValue(Info.Ctx,
1908 APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0),
1909 CCValue::GlobalValue());
Richard Smithf48fdb02011-12-09 22:58:01 +00001910 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00001911 Info.Diag(Conv->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001912 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001913 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001914
Richard Smithf48fdb02011-12-09 22:58:01 +00001915 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1916 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001917}
1918
Richard Smith59efe262011-11-11 04:05:33 +00001919/// Build an lvalue for the object argument of a member function call.
1920static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1921 LValue &This) {
1922 if (Object->getType()->isPointerType())
1923 return EvaluatePointer(Object, This, Info);
1924
1925 if (Object->isGLValue())
1926 return EvaluateLValue(Object, This, Info);
1927
Richard Smithe24f5fc2011-11-17 22:56:20 +00001928 if (Object->getType()->isLiteralType())
1929 return EvaluateTemporary(Object, This, Info);
1930
1931 return false;
1932}
1933
1934/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1935/// lvalue referring to the result.
1936///
1937/// \param Info - Information about the ongoing evaluation.
1938/// \param BO - The member pointer access operation.
1939/// \param LV - Filled in with a reference to the resulting object.
1940/// \param IncludeMember - Specifies whether the member itself is included in
1941/// the resulting LValue subobject designator. This is not possible when
1942/// creating a bound member function.
1943/// \return The field or method declaration to which the member pointer refers,
1944/// or 0 if evaluation fails.
1945static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1946 const BinaryOperator *BO,
1947 LValue &LV,
1948 bool IncludeMember = true) {
1949 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1950
Richard Smith745f5142012-01-27 01:14:48 +00001951 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1952 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001953 return 0;
1954
1955 MemberPtr MemPtr;
1956 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1957 return 0;
1958
1959 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1960 // member value, the behavior is undefined.
1961 if (!MemPtr.getDecl())
1962 return 0;
1963
Richard Smith745f5142012-01-27 01:14:48 +00001964 if (!EvalObjOK)
1965 return 0;
1966
Richard Smithe24f5fc2011-11-17 22:56:20 +00001967 if (MemPtr.isDerivedMember()) {
1968 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001969 // The end of the derived-to-base path for the base object must match the
1970 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001971 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001972 LV.Designator.Entries.size())
1973 return 0;
1974 unsigned PathLengthToMember =
1975 LV.Designator.Entries.size() - MemPtr.Path.size();
1976 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1977 const CXXRecordDecl *LVDecl = getAsBaseClass(
1978 LV.Designator.Entries[PathLengthToMember + I]);
1979 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1980 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1981 return 0;
1982 }
1983
1984 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001985 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1986 PathLengthToMember))
1987 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001988 } else if (!MemPtr.Path.empty()) {
1989 // Extend the LValue path with the member pointer's path.
1990 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1991 MemPtr.Path.size() + IncludeMember);
1992
1993 // Walk down to the appropriate base class.
1994 QualType LVType = BO->getLHS()->getType();
1995 if (const PointerType *PT = LVType->getAs<PointerType>())
1996 LVType = PT->getPointeeType();
1997 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1998 assert(RD && "member pointer access on non-class-type expression");
1999 // The first class in the path is that of the lvalue.
2000 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
2001 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smithb4e85ed2012-01-06 16:39:00 +00002002 HandleLValueDirectBase(Info, BO, LV, RD, Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002003 RD = Base;
2004 }
2005 // Finally cast to the class containing the member.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002006 HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord());
Richard Smithe24f5fc2011-11-17 22:56:20 +00002007 }
2008
2009 // Add the member. Note that we cannot build bound member functions here.
2010 if (IncludeMember) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002011 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl()))
2012 HandleLValueMember(Info, BO, LV, FD);
2013 else if (const IndirectFieldDecl *IFD =
2014 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl()))
2015 HandleLValueIndirectMember(Info, BO, LV, IFD);
2016 else
2017 llvm_unreachable("can't construct reference to bound member function");
Richard Smithe24f5fc2011-11-17 22:56:20 +00002018 }
2019
2020 return MemPtr.getDecl();
2021}
2022
2023/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2024/// the provided lvalue, which currently refers to the base object.
2025static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2026 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002027 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002028 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002029 return false;
2030
Richard Smithb4e85ed2012-01-06 16:39:00 +00002031 QualType TargetQT = E->getType();
2032 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2033 TargetQT = PT->getPointeeType();
2034
2035 // Check this cast lands within the final derived-to-base subobject path.
2036 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
2037 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
2038 << D.MostDerivedType << TargetQT;
2039 return false;
2040 }
2041
Richard Smithe24f5fc2011-11-17 22:56:20 +00002042 // Check the type of the final cast. We don't need to check the path,
2043 // since a cast can only be formed if the path is unique.
2044 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002045 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2046 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002047 if (NewEntriesSize == D.MostDerivedPathLength)
2048 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2049 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002050 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002051 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
2052 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_downcast)
2053 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002054 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002055 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002056
2057 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002058 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002059}
2060
Mike Stumpc4c90452009-10-27 22:09:17 +00002061namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002062enum EvalStmtResult {
2063 /// Evaluation failed.
2064 ESR_Failed,
2065 /// Hit a 'return' statement.
2066 ESR_Returned,
2067 /// Evaluation succeeded.
2068 ESR_Succeeded
2069};
2070}
2071
2072// Evaluate a statement.
Richard Smith83587db2012-02-15 02:18:13 +00002073static EvalStmtResult EvaluateStmt(CCValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002074 const Stmt *S) {
2075 switch (S->getStmtClass()) {
2076 default:
2077 return ESR_Failed;
2078
2079 case Stmt::NullStmtClass:
2080 case Stmt::DeclStmtClass:
2081 return ESR_Succeeded;
2082
Richard Smithc1c5f272011-12-13 06:39:58 +00002083 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002084 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002085 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002086 return ESR_Failed;
2087 return ESR_Returned;
2088 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002089
2090 case Stmt::CompoundStmtClass: {
2091 const CompoundStmt *CS = cast<CompoundStmt>(S);
2092 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2093 BE = CS->body_end(); BI != BE; ++BI) {
2094 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2095 if (ESR != ESR_Succeeded)
2096 return ESR;
2097 }
2098 return ESR_Succeeded;
2099 }
2100 }
2101}
2102
Richard Smith61802452011-12-22 02:22:31 +00002103/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2104/// default constructor. If so, we'll fold it whether or not it's marked as
2105/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2106/// so we need special handling.
2107static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002108 const CXXConstructorDecl *CD,
2109 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002110 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2111 return false;
2112
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002113 // Value-initialization does not call a trivial default constructor, so such a
2114 // call is a core constant expression whether or not the constructor is
2115 // constexpr.
2116 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002117 if (Info.getLangOpts().CPlusPlus0x) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002118 // FIXME: If DiagDecl is an implicitly-declared special member function,
2119 // we should be much more explicit about why it's not constexpr.
2120 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2121 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2122 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002123 } else {
2124 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2125 }
2126 }
2127 return true;
2128}
2129
Richard Smithc1c5f272011-12-13 06:39:58 +00002130/// CheckConstexprFunction - Check that a function can be called in a constant
2131/// expression.
2132static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2133 const FunctionDecl *Declaration,
2134 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002135 // Potential constant expressions can contain calls to declared, but not yet
2136 // defined, constexpr functions.
2137 if (Info.CheckingPotentialConstantExpression && !Definition &&
2138 Declaration->isConstexpr())
2139 return false;
2140
Richard Smithc1c5f272011-12-13 06:39:58 +00002141 // Can we evaluate this function call?
2142 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2143 return true;
2144
2145 if (Info.getLangOpts().CPlusPlus0x) {
2146 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002147 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2148 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002149 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2150 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2151 << DiagDecl;
2152 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2153 } else {
2154 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2155 }
2156 return false;
2157}
2158
Richard Smith180f4792011-11-10 06:34:14 +00002159namespace {
Richard Smithcd99b072011-11-11 05:48:57 +00002160typedef SmallVector<CCValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002161}
2162
2163/// EvaluateArgs - Evaluate the arguments to a function call.
2164static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2165 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002166 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002167 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002168 I != E; ++I) {
2169 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2170 // If we're checking for a potential constant expression, evaluate all
2171 // initializers even if some of them fail.
2172 if (!Info.keepEvaluatingAfterFailure())
2173 return false;
2174 Success = false;
2175 }
2176 }
2177 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002178}
2179
Richard Smithd0dccea2011-10-28 22:34:42 +00002180/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002181static bool HandleFunctionCall(SourceLocation CallLoc,
2182 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002183 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith83587db2012-02-15 02:18:13 +00002184 EvalInfo &Info, CCValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002185 ArgVector ArgValues(Args.size());
2186 if (!EvaluateArgs(Args, ArgValues, Info))
2187 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002188
Richard Smith745f5142012-01-27 01:14:48 +00002189 if (!Info.CheckCallLimit(CallLoc))
2190 return false;
2191
2192 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002193 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2194}
2195
Richard Smith180f4792011-11-10 06:34:14 +00002196/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002197static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002198 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002199 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002200 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002201 ArgVector ArgValues(Args.size());
2202 if (!EvaluateArgs(Args, ArgValues, Info))
2203 return false;
2204
Richard Smith745f5142012-01-27 01:14:48 +00002205 if (!Info.CheckCallLimit(CallLoc))
2206 return false;
2207
Richard Smith86c3ae42012-02-13 03:54:03 +00002208 const CXXRecordDecl *RD = Definition->getParent();
2209 if (RD->getNumVBases()) {
2210 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2211 return false;
2212 }
2213
Richard Smith745f5142012-01-27 01:14:48 +00002214 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002215
2216 // If it's a delegating constructor, just delegate.
2217 if (Definition->isDelegatingConstructor()) {
2218 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002219 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002220 }
2221
Richard Smith610a60c2012-01-10 04:32:03 +00002222 // For a trivial copy or move constructor, perform an APValue copy. This is
2223 // essential for unions, where the operations performed by the constructor
2224 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002225 if (Definition->isDefaulted() &&
2226 ((Definition->isCopyConstructor() && RD->hasTrivialCopyConstructor()) ||
2227 (Definition->isMoveConstructor() && RD->hasTrivialMoveConstructor()))) {
2228 LValue RHS;
2229 RHS.setFrom(ArgValues[0]);
2230 CCValue Value;
Richard Smith745f5142012-01-27 01:14:48 +00002231 if (!HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2232 RHS, Value))
2233 return false;
2234 assert((Value.isStruct() || Value.isUnion()) &&
2235 "trivial copy/move from non-class type?");
2236 // Any CCValue of class type must already be a constant expression.
2237 Result = Value;
2238 return true;
Richard Smith610a60c2012-01-10 04:32:03 +00002239 }
2240
2241 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002242 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002243 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2244 std::distance(RD->field_begin(), RD->field_end()));
2245
2246 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2247
Richard Smith745f5142012-01-27 01:14:48 +00002248 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002249 unsigned BasesSeen = 0;
2250#ifndef NDEBUG
2251 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2252#endif
2253 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2254 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002255 LValue Subobject = This;
2256 APValue *Value = &Result;
2257
2258 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002259 if ((*I)->isBaseInitializer()) {
2260 QualType BaseType((*I)->getBaseClass(), 0);
2261#ifndef NDEBUG
2262 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002263 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002264 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2265 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2266 "base class initializers not in expected order");
2267 ++BaseIt;
2268#endif
Richard Smithb4e85ed2012-01-06 16:39:00 +00002269 HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
Richard Smith180f4792011-11-10 06:34:14 +00002270 BaseType->getAsCXXRecordDecl(), &Layout);
Richard Smith745f5142012-01-27 01:14:48 +00002271 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002272 } else if (FieldDecl *FD = (*I)->getMember()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002273 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout);
Richard Smith180f4792011-11-10 06:34:14 +00002274 if (RD->isUnion()) {
2275 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002276 Value = &Result.getUnionValue();
2277 } else {
2278 Value = &Result.getStructField(FD->getFieldIndex());
2279 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002280 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002281 // Walk the indirect field decl's chain to find the object to initialize,
2282 // and make sure we've initialized every step along it.
2283 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2284 CE = IFD->chain_end();
2285 C != CE; ++C) {
2286 FieldDecl *FD = cast<FieldDecl>(*C);
2287 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2288 // Switch the union field if it differs. This happens if we had
2289 // preceding zero-initialization, and we're now initializing a union
2290 // subobject other than the first.
2291 // FIXME: In this case, the values of the other subobjects are
2292 // specified, since zero-initialization sets all padding bits to zero.
2293 if (Value->isUninit() ||
2294 (Value->isUnion() && Value->getUnionField() != FD)) {
2295 if (CD->isUnion())
2296 *Value = APValue(FD);
2297 else
2298 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2299 std::distance(CD->field_begin(), CD->field_end()));
2300 }
Richard Smith745f5142012-01-27 01:14:48 +00002301 HandleLValueMember(Info, (*I)->getInit(), Subobject, FD);
Richard Smithd9b02e72012-01-25 22:15:11 +00002302 if (CD->isUnion())
2303 Value = &Value->getUnionValue();
2304 else
2305 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002306 }
Richard Smith180f4792011-11-10 06:34:14 +00002307 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002308 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002309 }
Richard Smith745f5142012-01-27 01:14:48 +00002310
Richard Smith83587db2012-02-15 02:18:13 +00002311 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2312 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002313 ? CCEK_Constant : CCEK_MemberInit)) {
2314 // If we're checking for a potential constant expression, evaluate all
2315 // initializers even if some of them fail.
2316 if (!Info.keepEvaluatingAfterFailure())
2317 return false;
2318 Success = false;
2319 }
Richard Smith180f4792011-11-10 06:34:14 +00002320 }
2321
Richard Smith745f5142012-01-27 01:14:48 +00002322 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002323}
2324
Richard Smithd0dccea2011-10-28 22:34:42 +00002325namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002326class HasSideEffect
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002327 : public ConstStmtVisitor<HasSideEffect, bool> {
Richard Smith1e12c592011-10-16 21:26:27 +00002328 const ASTContext &Ctx;
Mike Stumpc4c90452009-10-27 22:09:17 +00002329public:
2330
Richard Smith1e12c592011-10-16 21:26:27 +00002331 HasSideEffect(const ASTContext &C) : Ctx(C) {}
Mike Stumpc4c90452009-10-27 22:09:17 +00002332
2333 // Unhandled nodes conservatively default to having side effects.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002334 bool VisitStmt(const Stmt *S) {
Mike Stumpc4c90452009-10-27 22:09:17 +00002335 return true;
2336 }
2337
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002338 bool VisitParenExpr(const ParenExpr *E) { return Visit(E->getSubExpr()); }
2339 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E) {
Peter Collingbournef111d932011-04-15 00:35:48 +00002340 return Visit(E->getResultExpr());
2341 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002342 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002343 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002344 return true;
2345 return false;
2346 }
John McCallf85e1932011-06-15 23:02:42 +00002347 bool VisitObjCIvarRefExpr(const ObjCIvarRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002348 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002349 return true;
2350 return false;
2351 }
2352 bool VisitBlockDeclRefExpr (const BlockDeclRefExpr *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002353 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
John McCallf85e1932011-06-15 23:02:42 +00002354 return true;
2355 return false;
2356 }
2357
Mike Stumpc4c90452009-10-27 22:09:17 +00002358 // We don't want to evaluate BlockExprs multiple times, as they generate
2359 // a ton of code.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002360 bool VisitBlockExpr(const BlockExpr *E) { return true; }
2361 bool VisitPredefinedExpr(const PredefinedExpr *E) { return false; }
2362 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Mike Stumpc4c90452009-10-27 22:09:17 +00002363 { return Visit(E->getInitializer()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002364 bool VisitMemberExpr(const MemberExpr *E) { return Visit(E->getBase()); }
2365 bool VisitIntegerLiteral(const IntegerLiteral *E) { return false; }
2366 bool VisitFloatingLiteral(const FloatingLiteral *E) { return false; }
2367 bool VisitStringLiteral(const StringLiteral *E) { return false; }
2368 bool VisitCharacterLiteral(const CharacterLiteral *E) { return false; }
2369 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00002370 { return false; }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002371 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Mike Stump980ca222009-10-29 20:48:09 +00002372 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002373 bool VisitChooseExpr(const ChooseExpr *E)
Richard Smith1e12c592011-10-16 21:26:27 +00002374 { return Visit(E->getChosenSubExpr(Ctx)); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002375 bool VisitCastExpr(const CastExpr *E) { return Visit(E->getSubExpr()); }
2376 bool VisitBinAssign(const BinaryOperator *E) { return true; }
2377 bool VisitCompoundAssignOperator(const BinaryOperator *E) { return true; }
2378 bool VisitBinaryOperator(const BinaryOperator *E)
Mike Stump980ca222009-10-29 20:48:09 +00002379 { return Visit(E->getLHS()) || Visit(E->getRHS()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002380 bool VisitUnaryPreInc(const UnaryOperator *E) { return true; }
2381 bool VisitUnaryPostInc(const UnaryOperator *E) { return true; }
2382 bool VisitUnaryPreDec(const UnaryOperator *E) { return true; }
2383 bool VisitUnaryPostDec(const UnaryOperator *E) { return true; }
2384 bool VisitUnaryDeref(const UnaryOperator *E) {
Richard Smith1e12c592011-10-16 21:26:27 +00002385 if (Ctx.getCanonicalType(E->getType()).isVolatileQualified())
Mike Stumpc4c90452009-10-27 22:09:17 +00002386 return true;
Mike Stump980ca222009-10-29 20:48:09 +00002387 return Visit(E->getSubExpr());
Mike Stumpc4c90452009-10-27 22:09:17 +00002388 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002389 bool VisitUnaryOperator(const UnaryOperator *E) { return Visit(E->getSubExpr()); }
Chris Lattner363ff232010-04-13 17:34:23 +00002390
2391 // Has side effects if any element does.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002392 bool VisitInitListExpr(const InitListExpr *E) {
Chris Lattner363ff232010-04-13 17:34:23 +00002393 for (unsigned i = 0, e = E->getNumInits(); i != e; ++i)
2394 if (Visit(E->getInit(i))) return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002395 if (const Expr *filler = E->getArrayFiller())
Argyrios Kyrtzidis4423ac02011-04-21 00:27:41 +00002396 return Visit(filler);
Chris Lattner363ff232010-04-13 17:34:23 +00002397 return false;
2398 }
Douglas Gregoree8aff02011-01-04 17:33:58 +00002399
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002400 bool VisitSizeOfPackExpr(const SizeOfPackExpr *) { return false; }
Mike Stumpc4c90452009-10-27 22:09:17 +00002401};
2402
John McCall56ca35d2011-02-17 10:25:35 +00002403class OpaqueValueEvaluation {
2404 EvalInfo &info;
2405 OpaqueValueExpr *opaqueValue;
2406
2407public:
2408 OpaqueValueEvaluation(EvalInfo &info, OpaqueValueExpr *opaqueValue,
2409 Expr *value)
2410 : info(info), opaqueValue(opaqueValue) {
2411
2412 // If evaluation fails, fail immediately.
Richard Smith1e12c592011-10-16 21:26:27 +00002413 if (!Evaluate(info.OpaqueValues[opaqueValue], info, value)) {
John McCall56ca35d2011-02-17 10:25:35 +00002414 this->opaqueValue = 0;
2415 return;
2416 }
John McCall56ca35d2011-02-17 10:25:35 +00002417 }
2418
2419 bool hasError() const { return opaqueValue == 0; }
2420
2421 ~OpaqueValueEvaluation() {
Richard Smith74e1ad92012-02-16 02:46:34 +00002422 // FIXME: For a recursive constexpr call, an outer stack frame might have
2423 // been using this opaque value too, and will now have to re-evaluate the
2424 // source expression.
John McCall56ca35d2011-02-17 10:25:35 +00002425 if (opaqueValue) info.OpaqueValues.erase(opaqueValue);
2426 }
2427};
2428
Mike Stumpc4c90452009-10-27 22:09:17 +00002429} // end anonymous namespace
2430
Eli Friedman4efaa272008-11-12 09:44:48 +00002431//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002432// Generic Evaluation
2433//===----------------------------------------------------------------------===//
2434namespace {
2435
Richard Smithf48fdb02011-12-09 22:58:01 +00002436// FIXME: RetTy is always bool. Remove it.
2437template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002438class ExprEvaluatorBase
2439 : public ConstStmtVisitor<Derived, RetTy> {
2440private:
Richard Smith47a1eed2011-10-29 20:57:55 +00002441 RetTy DerivedSuccess(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002442 return static_cast<Derived*>(this)->Success(V, E);
2443 }
Richard Smith51201882011-12-30 21:15:51 +00002444 RetTy DerivedZeroInitialization(const Expr *E) {
2445 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002446 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002447
Richard Smith74e1ad92012-02-16 02:46:34 +00002448 // Check whether a conditional operator with a non-constant condition is a
2449 // potential constant expression. If neither arm is a potential constant
2450 // expression, then the conditional operator is not either.
2451 template<typename ConditionalOperator>
2452 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2453 assert(Info.CheckingPotentialConstantExpression);
2454
2455 // Speculatively evaluate both arms.
2456 {
2457 llvm::SmallVector<PartialDiagnosticAt, 8> Diag;
2458 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2459
2460 StmtVisitorTy::Visit(E->getFalseExpr());
2461 if (Diag.empty())
2462 return;
2463
2464 Diag.clear();
2465 StmtVisitorTy::Visit(E->getTrueExpr());
2466 if (Diag.empty())
2467 return;
2468 }
2469
2470 Error(E, diag::note_constexpr_conditional_never_const);
2471 }
2472
2473
2474 template<typename ConditionalOperator>
2475 bool HandleConditionalOperator(const ConditionalOperator *E) {
2476 bool BoolResult;
2477 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2478 if (Info.CheckingPotentialConstantExpression)
2479 CheckPotentialConstantConditional(E);
2480 return false;
2481 }
2482
2483 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2484 return StmtVisitorTy::Visit(EvalExpr);
2485 }
2486
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002487protected:
2488 EvalInfo &Info;
2489 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2490 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2491
Richard Smithdd1f29b2011-12-12 09:28:41 +00002492 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithd5093422011-12-12 09:41:58 +00002493 return Info.CCEDiag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002494 }
2495
2496 /// Report an evaluation error. This should only be called when an error is
2497 /// first discovered. When propagating an error, just return false.
2498 bool Error(const Expr *E, diag::kind D) {
Richard Smithdd1f29b2011-12-12 09:28:41 +00002499 Info.Diag(E->getExprLoc(), D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002500 return false;
2501 }
2502 bool Error(const Expr *E) {
2503 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2504 }
2505
Richard Smith51201882011-12-30 21:15:51 +00002506 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
Richard Smithf10d9172011-10-11 21:43:33 +00002507
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002508public:
2509 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2510
2511 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002512 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002513 }
2514 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002515 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002516 }
2517
2518 RetTy VisitParenExpr(const ParenExpr *E)
2519 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2520 RetTy VisitUnaryExtension(const UnaryOperator *E)
2521 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2522 RetTy VisitUnaryPlus(const UnaryOperator *E)
2523 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2524 RetTy VisitChooseExpr(const ChooseExpr *E)
2525 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2526 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2527 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002528 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2529 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002530 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2531 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002532 // We cannot create any objects for which cleanups are required, so there is
2533 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2534 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2535 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002536
Richard Smithc216a012011-12-12 12:46:16 +00002537 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2538 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2539 return static_cast<Derived*>(this)->VisitCastExpr(E);
2540 }
2541 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2542 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2543 return static_cast<Derived*>(this)->VisitCastExpr(E);
2544 }
2545
Richard Smithe24f5fc2011-11-17 22:56:20 +00002546 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2547 switch (E->getOpcode()) {
2548 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002549 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002550
2551 case BO_Comma:
2552 VisitIgnoredValue(E->getLHS());
2553 return StmtVisitorTy::Visit(E->getRHS());
2554
2555 case BO_PtrMemD:
2556 case BO_PtrMemI: {
2557 LValue Obj;
2558 if (!HandleMemberPointerAccess(Info, E, Obj))
2559 return false;
2560 CCValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002561 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002562 return false;
2563 return DerivedSuccess(Result, E);
2564 }
2565 }
2566 }
2567
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002568 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith74e1ad92012-02-16 02:46:34 +00002569 // Cache the value of the common expression.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002570 OpaqueValueEvaluation opaque(Info, E->getOpaqueValue(), E->getCommon());
2571 if (opaque.hasError())
Richard Smithf48fdb02011-12-09 22:58:01 +00002572 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002573
Richard Smith74e1ad92012-02-16 02:46:34 +00002574 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002575 }
2576
2577 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002578 bool IsBcpCall = false;
2579 // If the condition (ignoring parens) is a __builtin_constant_p call,
2580 // the result is a constant expression if it can be folded without
2581 // side-effects. This is an important GNU extension. See GCC PR38377
2582 // for discussion.
2583 if (const CallExpr *CallCE =
2584 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2585 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2586 IsBcpCall = true;
2587
2588 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2589 // constant expression; we can't check whether it's potentially foldable.
2590 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2591 return false;
2592
2593 FoldConstant Fold(Info);
2594
Richard Smith74e1ad92012-02-16 02:46:34 +00002595 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002596 return false;
2597
2598 if (IsBcpCall)
2599 Fold.Fold(Info);
2600
2601 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002602 }
2603
2604 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002605 const CCValue *Value = Info.getOpaqueValue(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002606 if (!Value) {
2607 const Expr *Source = E->getSourceExpr();
2608 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002609 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002610 if (Source == E) { // sanity checking.
2611 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002612 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002613 }
2614 return StmtVisitorTy::Visit(Source);
2615 }
Richard Smith47a1eed2011-10-29 20:57:55 +00002616 return DerivedSuccess(*Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002617 }
Richard Smithf10d9172011-10-11 21:43:33 +00002618
Richard Smithd0dccea2011-10-28 22:34:42 +00002619 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002620 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002621 QualType CalleeType = Callee->getType();
2622
Richard Smithd0dccea2011-10-28 22:34:42 +00002623 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002624 LValue *This = 0, ThisVal;
2625 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002626 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002627
Richard Smith59efe262011-11-11 04:05:33 +00002628 // Extract function decl and 'this' pointer from the callee.
2629 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002630 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002631 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2632 // Explicit bound member calls, such as x.f() or p->g();
2633 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002634 return false;
2635 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002636 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002637 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002638 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2639 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002640 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2641 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002642 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002643 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002644 return Error(Callee);
2645
2646 FD = dyn_cast<FunctionDecl>(Member);
2647 if (!FD)
2648 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002649 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002650 LValue Call;
2651 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002652 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002653
Richard Smithb4e85ed2012-01-06 16:39:00 +00002654 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002655 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002656 FD = dyn_cast_or_null<FunctionDecl>(
2657 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002658 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002659 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002660
2661 // Overloaded operator calls to member functions are represented as normal
2662 // calls with '*this' as the first argument.
2663 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2664 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002665 // FIXME: When selecting an implicit conversion for an overloaded
2666 // operator delete, we sometimes try to evaluate calls to conversion
2667 // operators without a 'this' parameter!
2668 if (Args.empty())
2669 return Error(E);
2670
Richard Smith59efe262011-11-11 04:05:33 +00002671 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2672 return false;
2673 This = &ThisVal;
2674 Args = Args.slice(1);
2675 }
2676
2677 // Don't call function pointers which have been cast to some other type.
2678 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002679 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002680 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002681 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002682
Richard Smithb04035a2012-02-01 02:39:43 +00002683 if (This && !This->checkSubobject(Info, E, CSK_This))
2684 return false;
2685
Richard Smith86c3ae42012-02-13 03:54:03 +00002686 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2687 // calls to such functions in constant expressions.
2688 if (This && !HasQualifier &&
2689 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2690 return Error(E, diag::note_constexpr_virtual_call);
2691
Richard Smithc1c5f272011-12-13 06:39:58 +00002692 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002693 Stmt *Body = FD->getBody(Definition);
Richard Smith83587db2012-02-15 02:18:13 +00002694 CCValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002695
Richard Smithc1c5f272011-12-13 06:39:58 +00002696 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002697 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2698 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002699 return false;
2700
Richard Smith83587db2012-02-15 02:18:13 +00002701 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002702 }
2703
Richard Smithc49bd112011-10-28 17:51:58 +00002704 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2705 return StmtVisitorTy::Visit(E->getInitializer());
2706 }
Richard Smithf10d9172011-10-11 21:43:33 +00002707 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002708 if (E->getNumInits() == 0)
2709 return DerivedZeroInitialization(E);
2710 if (E->getNumInits() == 1)
2711 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002712 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002713 }
2714 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002715 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002716 }
2717 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002718 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002719 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002720 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002721 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002722 }
Richard Smithf10d9172011-10-11 21:43:33 +00002723
Richard Smith180f4792011-11-10 06:34:14 +00002724 /// A member expression where the object is a prvalue is itself a prvalue.
2725 RetTy VisitMemberExpr(const MemberExpr *E) {
2726 assert(!E->isArrow() && "missing call to bound member function?");
2727
2728 CCValue Val;
2729 if (!Evaluate(Val, Info, E->getBase()))
2730 return false;
2731
2732 QualType BaseTy = E->getBase()->getType();
2733
2734 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002735 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002736 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
2737 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2738 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2739
Richard Smithb4e85ed2012-01-06 16:39:00 +00002740 SubobjectDesignator Designator(BaseTy);
2741 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002742
Richard Smithf48fdb02011-12-09 22:58:01 +00002743 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002744 DerivedSuccess(Val, E);
2745 }
2746
Richard Smithc49bd112011-10-28 17:51:58 +00002747 RetTy VisitCastExpr(const CastExpr *E) {
2748 switch (E->getCastKind()) {
2749 default:
2750 break;
2751
David Chisnall7a7ee302012-01-16 17:27:18 +00002752 case CK_AtomicToNonAtomic:
2753 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002754 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002755 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002756 return StmtVisitorTy::Visit(E->getSubExpr());
2757
2758 case CK_LValueToRValue: {
2759 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002760 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2761 return false;
2762 CCValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002763 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2764 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2765 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002766 return false;
2767 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002768 }
2769 }
2770
Richard Smithf48fdb02011-12-09 22:58:01 +00002771 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002772 }
2773
Richard Smith8327fad2011-10-24 18:44:57 +00002774 /// Visit a value which is evaluated, but whose value is ignored.
2775 void VisitIgnoredValue(const Expr *E) {
Richard Smith47a1eed2011-10-29 20:57:55 +00002776 CCValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002777 if (!Evaluate(Scratch, Info, E))
2778 Info.EvalStatus.HasSideEffects = true;
2779 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002780};
2781
2782}
2783
2784//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002785// Common base class for lvalue and temporary evaluation.
2786//===----------------------------------------------------------------------===//
2787namespace {
2788template<class Derived>
2789class LValueExprEvaluatorBase
2790 : public ExprEvaluatorBase<Derived, bool> {
2791protected:
2792 LValue &Result;
2793 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2794 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2795
2796 bool Success(APValue::LValueBase B) {
2797 Result.set(B);
2798 return true;
2799 }
2800
2801public:
2802 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2803 ExprEvaluatorBaseTy(Info), Result(Result) {}
2804
2805 bool Success(const CCValue &V, const Expr *E) {
2806 Result.setFrom(V);
2807 return true;
2808 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002809
Richard Smithe24f5fc2011-11-17 22:56:20 +00002810 bool VisitMemberExpr(const MemberExpr *E) {
2811 // Handle non-static data members.
2812 QualType BaseTy;
2813 if (E->isArrow()) {
2814 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2815 return false;
2816 BaseTy = E->getBase()->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002817 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002818 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002819 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2820 return false;
2821 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002822 } else {
2823 if (!this->Visit(E->getBase()))
2824 return false;
2825 BaseTy = E->getBase()->getType();
2826 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002827
Richard Smithd9b02e72012-01-25 22:15:11 +00002828 const ValueDecl *MD = E->getMemberDecl();
2829 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2830 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2831 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2832 (void)BaseTy;
2833 HandleLValueMember(this->Info, E, Result, FD);
2834 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
2835 HandleLValueIndirectMember(this->Info, E, Result, IFD);
2836 } else
2837 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002838
Richard Smithd9b02e72012-01-25 22:15:11 +00002839 if (MD->getType()->isReferenceType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002840 CCValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002841 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002842 RefValue))
2843 return false;
2844 return Success(RefValue, E);
2845 }
2846 return true;
2847 }
2848
2849 bool VisitBinaryOperator(const BinaryOperator *E) {
2850 switch (E->getOpcode()) {
2851 default:
2852 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2853
2854 case BO_PtrMemD:
2855 case BO_PtrMemI:
2856 return HandleMemberPointerAccess(this->Info, E, Result);
2857 }
2858 }
2859
2860 bool VisitCastExpr(const CastExpr *E) {
2861 switch (E->getCastKind()) {
2862 default:
2863 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2864
2865 case CK_DerivedToBase:
2866 case CK_UncheckedDerivedToBase: {
2867 if (!this->Visit(E->getSubExpr()))
2868 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002869
2870 // Now figure out the necessary offset to add to the base LV to get from
2871 // the derived class to the base class.
2872 QualType Type = E->getSubExpr()->getType();
2873
2874 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2875 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002876 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002877 *PathI))
2878 return false;
2879 Type = (*PathI)->getType();
2880 }
2881
2882 return true;
2883 }
2884 }
2885 }
2886};
2887}
2888
2889//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002890// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002891//
2892// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2893// function designators (in C), decl references to void objects (in C), and
2894// temporaries (if building with -Wno-address-of-temporary).
2895//
2896// LValue evaluation produces values comprising a base expression of one of the
2897// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002898// - Declarations
2899// * VarDecl
2900// * FunctionDecl
2901// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002902// * CompoundLiteralExpr in C
2903// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002904// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002905// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002906// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002907// * ObjCEncodeExpr
2908// * AddrLabelExpr
2909// * BlockExpr
2910// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002911// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002912// * Any Expr, with a CallIndex indicating the function in which the temporary
2913// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002914// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002915//===----------------------------------------------------------------------===//
2916namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002917class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002918 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002919public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002920 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2921 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002922
Richard Smithc49bd112011-10-28 17:51:58 +00002923 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2924
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002925 bool VisitDeclRefExpr(const DeclRefExpr *E);
2926 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002927 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002928 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2929 bool VisitMemberExpr(const MemberExpr *E);
2930 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2931 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002932 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002933 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2934 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002935 bool VisitUnaryReal(const UnaryOperator *E);
2936 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002937
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002938 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002939 switch (E->getCastKind()) {
2940 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002941 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002942
Eli Friedmandb924222011-10-11 00:13:24 +00002943 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002944 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002945 if (!Visit(E->getSubExpr()))
2946 return false;
2947 Result.Designator.setInvalid();
2948 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002949
Richard Smithe24f5fc2011-11-17 22:56:20 +00002950 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002951 if (!Visit(E->getSubExpr()))
2952 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002953 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002954 }
2955 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002956};
2957} // end anonymous namespace
2958
Richard Smithc49bd112011-10-28 17:51:58 +00002959/// Evaluate an expression as an lvalue. This can be legitimately called on
2960/// expressions which are not glvalues, in a few cases:
2961/// * function designators in C,
2962/// * "extern void" objects,
2963/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002964static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002965 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2966 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2967 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002968 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002969}
2970
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002971bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002972 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2973 return Success(FD);
2974 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002975 return VisitVarDecl(E, VD);
2976 return Error(E);
2977}
Richard Smith436c8892011-10-24 23:14:33 +00002978
Richard Smithc49bd112011-10-28 17:51:58 +00002979bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002980 if (!VD->getType()->isReferenceType()) {
2981 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002982 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002983 return true;
2984 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002985 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002986 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002987
Richard Smith47a1eed2011-10-29 20:57:55 +00002988 CCValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002989 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2990 return false;
2991 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002992}
2993
Richard Smithbd552ef2011-10-31 05:52:43 +00002994bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2995 const MaterializeTemporaryExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002996 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002997 if (E->getType()->isRecordType())
Richard Smithe24f5fc2011-11-17 22:56:20 +00002998 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2999
Richard Smith83587db2012-02-15 02:18:13 +00003000 Result.set(E, Info.CurrentCall->Index);
3001 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
3002 Result, E->GetTemporaryExpr());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003003 }
3004
3005 // Materialization of an lvalue temporary occurs when we need to force a copy
3006 // (for instance, if it's a bitfield).
3007 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
3008 if (!Visit(E->GetTemporaryExpr()))
3009 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003010 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003011 Info.CurrentCall->Temporaries[E]))
3012 return false;
Richard Smith83587db2012-02-15 02:18:13 +00003013 Result.set(E, Info.CurrentCall->Index);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003014 return true;
Richard Smithbd552ef2011-10-31 05:52:43 +00003015}
3016
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003017bool
3018LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003019 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
3020 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
3021 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00003022 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003023}
3024
Richard Smith47d21452011-12-27 12:18:28 +00003025bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
3026 if (E->isTypeOperand())
3027 return Success(E);
3028 CXXRecordDecl *RD = E->getExprOperand()->getType()->getAsCXXRecordDecl();
3029 if (RD && RD->isPolymorphic()) {
3030 Info.Diag(E->getExprLoc(), diag::note_constexpr_typeid_polymorphic)
3031 << E->getExprOperand()->getType()
3032 << E->getExprOperand()->getSourceRange();
3033 return false;
3034 }
3035 return Success(E);
3036}
3037
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003038bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003039 // Handle static data members.
3040 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
3041 VisitIgnoredValue(E->getBase());
3042 return VisitVarDecl(E, VD);
3043 }
3044
Richard Smithd0dccea2011-10-28 22:34:42 +00003045 // Handle static member functions.
3046 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
3047 if (MD->isStatic()) {
3048 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003049 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00003050 }
3051 }
3052
Richard Smith180f4792011-11-10 06:34:14 +00003053 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00003054 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003055}
3056
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003057bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00003058 // FIXME: Deal with vectors as array subscript bases.
3059 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00003060 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00003061
Anders Carlsson3068d112008-11-16 19:01:22 +00003062 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003063 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003064
Anders Carlsson3068d112008-11-16 19:01:22 +00003065 APSInt Index;
3066 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00003067 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003068 int64_t IndexValue
3069 = Index.isSigned() ? Index.getSExtValue()
3070 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00003071
Richard Smithb4e85ed2012-01-06 16:39:00 +00003072 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00003073}
Eli Friedman4efaa272008-11-12 09:44:48 +00003074
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003075bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00003076 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00003077}
3078
Richard Smith86024012012-02-18 22:04:06 +00003079bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
3080 if (!Visit(E->getSubExpr()))
3081 return false;
3082 // __real is a no-op on scalar lvalues.
3083 if (E->getSubExpr()->getType()->isAnyComplexType())
3084 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
3085 return true;
3086}
3087
3088bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
3089 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
3090 "lvalue __imag__ on scalar?");
3091 if (!Visit(E->getSubExpr()))
3092 return false;
3093 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
3094 return true;
3095}
3096
Eli Friedman4efaa272008-11-12 09:44:48 +00003097//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003098// Pointer Evaluation
3099//===----------------------------------------------------------------------===//
3100
Anders Carlssonc754aa62008-07-08 05:13:58 +00003101namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003102class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003103 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00003104 LValue &Result;
3105
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003106 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003107 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00003108 return true;
3109 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003110public:
Mike Stump1eb44332009-09-09 15:08:12 +00003111
John McCallefdb83e2010-05-07 21:00:08 +00003112 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003113 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003114
Richard Smith47a1eed2011-10-29 20:57:55 +00003115 bool Success(const CCValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003116 Result.setFrom(V);
3117 return true;
3118 }
Richard Smith51201882011-12-30 21:15:51 +00003119 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00003120 return Success((Expr*)0);
3121 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00003122
John McCallefdb83e2010-05-07 21:00:08 +00003123 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003124 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00003125 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003126 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00003127 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003128 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00003129 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003130 bool VisitCallExpr(const CallExpr *E);
3131 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00003132 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00003133 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00003134 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00003135 }
Richard Smith180f4792011-11-10 06:34:14 +00003136 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3137 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003138 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003139 Result = *Info.CurrentCall->This;
3140 return true;
3141 }
John McCall56ca35d2011-02-17 10:25:35 +00003142
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003143 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003144};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003145} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003146
John McCallefdb83e2010-05-07 21:00:08 +00003147static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003148 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003149 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003150}
3151
John McCallefdb83e2010-05-07 21:00:08 +00003152bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003153 if (E->getOpcode() != BO_Add &&
3154 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003155 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003156
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003157 const Expr *PExp = E->getLHS();
3158 const Expr *IExp = E->getRHS();
3159 if (IExp->getType()->isPointerType())
3160 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003161
Richard Smith745f5142012-01-27 01:14:48 +00003162 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3163 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003164 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003165
John McCallefdb83e2010-05-07 21:00:08 +00003166 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003167 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003168 return false;
3169 int64_t AdditionalOffset
3170 = Offset.isSigned() ? Offset.getSExtValue()
3171 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003172 if (E->getOpcode() == BO_Sub)
3173 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003174
Richard Smith180f4792011-11-10 06:34:14 +00003175 QualType Pointee = PExp->getType()->getAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003176 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3177 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003178}
Eli Friedman4efaa272008-11-12 09:44:48 +00003179
John McCallefdb83e2010-05-07 21:00:08 +00003180bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3181 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003182}
Mike Stump1eb44332009-09-09 15:08:12 +00003183
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003184bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3185 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003186
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003187 switch (E->getCastKind()) {
3188 default:
3189 break;
3190
John McCall2de56d12010-08-25 11:45:40 +00003191 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003192 case CK_CPointerToObjCPointerCast:
3193 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003194 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003195 if (!Visit(SubExpr))
3196 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003197 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3198 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3199 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003200 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003201 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003202 if (SubExpr->getType()->isVoidPointerType())
3203 CCEDiag(E, diag::note_constexpr_invalid_cast)
3204 << 3 << SubExpr->getType();
3205 else
3206 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3207 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003208 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003209
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003210 case CK_DerivedToBase:
3211 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003212 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003213 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003214 if (!Result.Base && Result.Offset.isZero())
3215 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003216
Richard Smith180f4792011-11-10 06:34:14 +00003217 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003218 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003219 QualType Type =
3220 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003221
Richard Smith180f4792011-11-10 06:34:14 +00003222 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003223 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003224 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3225 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003226 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003227 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003228 }
3229
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003230 return true;
3231 }
3232
Richard Smithe24f5fc2011-11-17 22:56:20 +00003233 case CK_BaseToDerived:
3234 if (!Visit(E->getSubExpr()))
3235 return false;
3236 if (!Result.Base && Result.Offset.isZero())
3237 return true;
3238 return HandleBaseToDerivedCast(Info, E, Result);
3239
Richard Smith47a1eed2011-10-29 20:57:55 +00003240 case CK_NullToPointer:
Richard Smith51201882011-12-30 21:15:51 +00003241 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003242
John McCall2de56d12010-08-25 11:45:40 +00003243 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003244 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3245
Richard Smith47a1eed2011-10-29 20:57:55 +00003246 CCValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003247 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003248 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003249
John McCallefdb83e2010-05-07 21:00:08 +00003250 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003251 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3252 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003253 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003254 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003255 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003256 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003257 return true;
3258 } else {
3259 // Cast is of an lvalue, no need to change value.
Richard Smith47a1eed2011-10-29 20:57:55 +00003260 Result.setFrom(Value);
John McCallefdb83e2010-05-07 21:00:08 +00003261 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003262 }
3263 }
John McCall2de56d12010-08-25 11:45:40 +00003264 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003265 if (SubExpr->isGLValue()) {
3266 if (!EvaluateLValue(SubExpr, Result, Info))
3267 return false;
3268 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003269 Result.set(SubExpr, Info.CurrentCall->Index);
3270 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3271 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003272 return false;
3273 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003274 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003275 if (const ConstantArrayType *CAT
3276 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3277 Result.addArray(Info, E, CAT);
3278 else
3279 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003280 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003281
John McCall2de56d12010-08-25 11:45:40 +00003282 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003283 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003284 }
3285
Richard Smithc49bd112011-10-28 17:51:58 +00003286 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003287}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003288
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003289bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003290 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003291 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003292
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003293 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003294}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003295
3296//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003297// Member Pointer Evaluation
3298//===----------------------------------------------------------------------===//
3299
3300namespace {
3301class MemberPointerExprEvaluator
3302 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3303 MemberPtr &Result;
3304
3305 bool Success(const ValueDecl *D) {
3306 Result = MemberPtr(D);
3307 return true;
3308 }
3309public:
3310
3311 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3312 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3313
3314 bool Success(const CCValue &V, const Expr *E) {
3315 Result.setFrom(V);
3316 return true;
3317 }
Richard Smith51201882011-12-30 21:15:51 +00003318 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003319 return Success((const ValueDecl*)0);
3320 }
3321
3322 bool VisitCastExpr(const CastExpr *E);
3323 bool VisitUnaryAddrOf(const UnaryOperator *E);
3324};
3325} // end anonymous namespace
3326
3327static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3328 EvalInfo &Info) {
3329 assert(E->isRValue() && E->getType()->isMemberPointerType());
3330 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3331}
3332
3333bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3334 switch (E->getCastKind()) {
3335 default:
3336 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3337
3338 case CK_NullToMemberPointer:
Richard Smith51201882011-12-30 21:15:51 +00003339 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003340
3341 case CK_BaseToDerivedMemberPointer: {
3342 if (!Visit(E->getSubExpr()))
3343 return false;
3344 if (E->path_empty())
3345 return true;
3346 // Base-to-derived member pointer casts store the path in derived-to-base
3347 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3348 // the wrong end of the derived->base arc, so stagger the path by one class.
3349 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3350 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3351 PathI != PathE; ++PathI) {
3352 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3353 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3354 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003355 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003356 }
3357 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3358 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003359 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003360 return true;
3361 }
3362
3363 case CK_DerivedToBaseMemberPointer:
3364 if (!Visit(E->getSubExpr()))
3365 return false;
3366 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3367 PathE = E->path_end(); PathI != PathE; ++PathI) {
3368 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3369 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3370 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003371 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003372 }
3373 return true;
3374 }
3375}
3376
3377bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3378 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3379 // member can be formed.
3380 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3381}
3382
3383//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003384// Record Evaluation
3385//===----------------------------------------------------------------------===//
3386
3387namespace {
3388 class RecordExprEvaluator
3389 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3390 const LValue &This;
3391 APValue &Result;
3392 public:
3393
3394 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3395 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3396
3397 bool Success(const CCValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003398 Result = V;
3399 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003400 }
Richard Smith51201882011-12-30 21:15:51 +00003401 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003402
Richard Smith59efe262011-11-11 04:05:33 +00003403 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003404 bool VisitInitListExpr(const InitListExpr *E);
3405 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3406 };
3407}
3408
Richard Smith51201882011-12-30 21:15:51 +00003409/// Perform zero-initialization on an object of non-union class type.
3410/// C++11 [dcl.init]p5:
3411/// To zero-initialize an object or reference of type T means:
3412/// [...]
3413/// -- if T is a (possibly cv-qualified) non-union class type,
3414/// each non-static data member and each base-class subobject is
3415/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003416static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3417 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003418 const LValue &This, APValue &Result) {
3419 assert(!RD->isUnion() && "Expected non-union class type");
3420 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3421 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3422 std::distance(RD->field_begin(), RD->field_end()));
3423
3424 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3425
3426 if (CD) {
3427 unsigned Index = 0;
3428 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003429 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003430 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3431 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003432 HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout);
3433 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003434 Result.getStructBase(Index)))
3435 return false;
3436 }
3437 }
3438
Richard Smithb4e85ed2012-01-06 16:39:00 +00003439 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3440 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003441 // -- if T is a reference type, no initialization is performed.
3442 if ((*I)->getType()->isReferenceType())
3443 continue;
3444
3445 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003446 HandleLValueMember(Info, E, Subobject, *I, &Layout);
Richard Smith51201882011-12-30 21:15:51 +00003447
3448 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003449 if (!EvaluateInPlace(
Richard Smith51201882011-12-30 21:15:51 +00003450 Result.getStructField((*I)->getFieldIndex()), Info, Subobject, &VIE))
3451 return false;
3452 }
3453
3454 return true;
3455}
3456
3457bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3458 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3459 if (RD->isUnion()) {
3460 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3461 // object's first non-static named data member is zero-initialized
3462 RecordDecl::field_iterator I = RD->field_begin();
3463 if (I == RD->field_end()) {
3464 Result = APValue((const FieldDecl*)0);
3465 return true;
3466 }
3467
3468 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003469 HandleLValueMember(Info, E, Subobject, *I);
Richard Smith51201882011-12-30 21:15:51 +00003470 Result = APValue(*I);
3471 ImplicitValueInitExpr VIE((*I)->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003472 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003473 }
3474
Richard Smithce582fe2012-02-17 00:44:16 +00003475 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
3476 Info.Diag(E->getExprLoc(), diag::note_constexpr_virtual_base) << RD;
3477 return false;
3478 }
3479
Richard Smithb4e85ed2012-01-06 16:39:00 +00003480 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003481}
3482
Richard Smith59efe262011-11-11 04:05:33 +00003483bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3484 switch (E->getCastKind()) {
3485 default:
3486 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3487
3488 case CK_ConstructorConversion:
3489 return Visit(E->getSubExpr());
3490
3491 case CK_DerivedToBase:
3492 case CK_UncheckedDerivedToBase: {
3493 CCValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003494 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003495 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003496 if (!DerivedObject.isStruct())
3497 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003498
3499 // Derived-to-base rvalue conversion: just slice off the derived part.
3500 APValue *Value = &DerivedObject;
3501 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3502 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3503 PathE = E->path_end(); PathI != PathE; ++PathI) {
3504 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3505 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3506 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3507 RD = Base;
3508 }
3509 Result = *Value;
3510 return true;
3511 }
3512 }
3513}
3514
Richard Smith180f4792011-11-10 06:34:14 +00003515bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003516 // Cannot constant-evaluate std::initializer_list inits.
3517 if (E->initializesStdInitializerList())
3518 return false;
3519
Richard Smith180f4792011-11-10 06:34:14 +00003520 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
3521 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3522
3523 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003524 const FieldDecl *Field = E->getInitializedFieldInUnion();
3525 Result = APValue(Field);
3526 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003527 return true;
Richard Smithec789162012-01-12 18:54:33 +00003528
3529 // If the initializer list for a union does not contain any elements, the
3530 // first element of the union is value-initialized.
3531 ImplicitValueInitExpr VIE(Field->getType());
3532 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3533
Richard Smith180f4792011-11-10 06:34:14 +00003534 LValue Subobject = This;
Richard Smithec789162012-01-12 18:54:33 +00003535 HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout);
Richard Smith83587db2012-02-15 02:18:13 +00003536 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003537 }
3538
3539 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3540 "initializer list for class with base classes");
3541 Result = APValue(APValue::UninitStruct(), 0,
3542 std::distance(RD->field_begin(), RD->field_end()));
3543 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003544 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003545 for (RecordDecl::field_iterator Field = RD->field_begin(),
3546 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3547 // Anonymous bit-fields are not considered members of the class for
3548 // purposes of aggregate initialization.
3549 if (Field->isUnnamedBitfield())
3550 continue;
3551
3552 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003553
Richard Smith745f5142012-01-27 01:14:48 +00003554 bool HaveInit = ElementNo < E->getNumInits();
3555
3556 // FIXME: Diagnostics here should point to the end of the initializer
3557 // list, not the start.
3558 HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E, Subobject,
3559 *Field, &Layout);
3560
3561 // Perform an implicit value-initialization for members beyond the end of
3562 // the initializer list.
3563 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3564
Richard Smith83587db2012-02-15 02:18:13 +00003565 if (!EvaluateInPlace(
Richard Smith745f5142012-01-27 01:14:48 +00003566 Result.getStructField((*Field)->getFieldIndex()),
3567 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3568 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003569 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003570 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003571 }
3572 }
3573
Richard Smith745f5142012-01-27 01:14:48 +00003574 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003575}
3576
3577bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3578 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith51201882011-12-30 21:15:51 +00003579 bool ZeroInit = E->requiresZeroInitialization();
3580 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003581 // If we've already performed zero-initialization, we're already done.
3582 if (!Result.isUninit())
3583 return true;
3584
Richard Smith51201882011-12-30 21:15:51 +00003585 if (ZeroInit)
3586 return ZeroInitialization(E);
3587
Richard Smith61802452011-12-22 02:22:31 +00003588 const CXXRecordDecl *RD = FD->getParent();
3589 if (RD->isUnion())
3590 Result = APValue((FieldDecl*)0);
3591 else
3592 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3593 std::distance(RD->field_begin(), RD->field_end()));
3594 return true;
3595 }
3596
Richard Smith180f4792011-11-10 06:34:14 +00003597 const FunctionDecl *Definition = 0;
3598 FD->getBody(Definition);
3599
Richard Smithc1c5f272011-12-13 06:39:58 +00003600 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3601 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003602
Richard Smith610a60c2012-01-10 04:32:03 +00003603 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003604 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003605 if (const MaterializeTemporaryExpr *ME
3606 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3607 return Visit(ME->GetTemporaryExpr());
3608
Richard Smith51201882011-12-30 21:15:51 +00003609 if (ZeroInit && !ZeroInitialization(E))
3610 return false;
3611
Richard Smith180f4792011-11-10 06:34:14 +00003612 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003613 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003614 cast<CXXConstructorDecl>(Definition), Info,
3615 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003616}
3617
3618static bool EvaluateRecord(const Expr *E, const LValue &This,
3619 APValue &Result, EvalInfo &Info) {
3620 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003621 "can't evaluate expression as a record rvalue");
3622 return RecordExprEvaluator(Info, This, Result).Visit(E);
3623}
3624
3625//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003626// Temporary Evaluation
3627//
3628// Temporaries are represented in the AST as rvalues, but generally behave like
3629// lvalues. The full-object of which the temporary is a subobject is implicitly
3630// materialized so that a reference can bind to it.
3631//===----------------------------------------------------------------------===//
3632namespace {
3633class TemporaryExprEvaluator
3634 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3635public:
3636 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3637 LValueExprEvaluatorBaseTy(Info, Result) {}
3638
3639 /// Visit an expression which constructs the value of this temporary.
3640 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003641 Result.set(E, Info.CurrentCall->Index);
3642 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003643 }
3644
3645 bool VisitCastExpr(const CastExpr *E) {
3646 switch (E->getCastKind()) {
3647 default:
3648 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3649
3650 case CK_ConstructorConversion:
3651 return VisitConstructExpr(E->getSubExpr());
3652 }
3653 }
3654 bool VisitInitListExpr(const InitListExpr *E) {
3655 return VisitConstructExpr(E);
3656 }
3657 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3658 return VisitConstructExpr(E);
3659 }
3660 bool VisitCallExpr(const CallExpr *E) {
3661 return VisitConstructExpr(E);
3662 }
3663};
3664} // end anonymous namespace
3665
3666/// Evaluate an expression of record type as a temporary.
3667static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003668 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003669 return TemporaryExprEvaluator(Info, Result).Visit(E);
3670}
3671
3672//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003673// Vector Evaluation
3674//===----------------------------------------------------------------------===//
3675
3676namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003677 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003678 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3679 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003680 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003681
Richard Smith07fc6572011-10-22 21:10:00 +00003682 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3683 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003684
Richard Smith07fc6572011-10-22 21:10:00 +00003685 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3686 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3687 // FIXME: remove this APValue copy.
3688 Result = APValue(V.data(), V.size());
3689 return true;
3690 }
Richard Smith69c2c502011-11-04 05:33:44 +00003691 bool Success(const CCValue &V, const Expr *E) {
3692 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003693 Result = V;
3694 return true;
3695 }
Richard Smith51201882011-12-30 21:15:51 +00003696 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003697
Richard Smith07fc6572011-10-22 21:10:00 +00003698 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003699 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003700 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003701 bool VisitInitListExpr(const InitListExpr *E);
3702 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003703 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003704 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003705 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003706 };
3707} // end anonymous namespace
3708
3709static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003710 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003711 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003712}
3713
Richard Smith07fc6572011-10-22 21:10:00 +00003714bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3715 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003716 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003717
Richard Smithd62ca372011-12-06 22:44:34 +00003718 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003719 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003720
Eli Friedman46a52322011-03-25 00:43:55 +00003721 switch (E->getCastKind()) {
3722 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003723 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003724 if (SETy->isIntegerType()) {
3725 APSInt IntResult;
3726 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003727 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003728 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003729 } else if (SETy->isRealFloatingType()) {
3730 APFloat F(0.0);
3731 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003732 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003733 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003734 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003735 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003736 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003737
3738 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003739 SmallVector<APValue, 4> Elts(NElts, Val);
3740 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003741 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003742 case CK_BitCast: {
3743 // Evaluate the operand into an APInt we can extract from.
3744 llvm::APInt SValInt;
3745 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3746 return false;
3747 // Extract the elements
3748 QualType EltTy = VTy->getElementType();
3749 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3750 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3751 SmallVector<APValue, 4> Elts;
3752 if (EltTy->isRealFloatingType()) {
3753 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
3754 bool isIEESem = &Sem != &APFloat::PPCDoubleDouble;
3755 unsigned FloatEltSize = EltSize;
3756 if (&Sem == &APFloat::x87DoubleExtended)
3757 FloatEltSize = 80;
3758 for (unsigned i = 0; i < NElts; i++) {
3759 llvm::APInt Elt;
3760 if (BigEndian)
3761 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3762 else
3763 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
3764 Elts.push_back(APValue(APFloat(Elt, isIEESem)));
3765 }
3766 } else if (EltTy->isIntegerType()) {
3767 for (unsigned i = 0; i < NElts; i++) {
3768 llvm::APInt Elt;
3769 if (BigEndian)
3770 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3771 else
3772 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3773 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3774 }
3775 } else {
3776 return Error(E);
3777 }
3778 return Success(Elts, E);
3779 }
Eli Friedman46a52322011-03-25 00:43:55 +00003780 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003781 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003782 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003783}
3784
Richard Smith07fc6572011-10-22 21:10:00 +00003785bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003786VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003787 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003788 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003789 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003790
Nate Begeman59b5da62009-01-18 03:20:47 +00003791 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003792 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003793
Eli Friedman3edd5a92012-01-03 23:24:20 +00003794 // The number of initializers can be less than the number of
3795 // vector elements. For OpenCL, this can be due to nested vector
3796 // initialization. For GCC compatibility, missing trailing elements
3797 // should be initialized with zeroes.
3798 unsigned CountInits = 0, CountElts = 0;
3799 while (CountElts < NumElements) {
3800 // Handle nested vector initialization.
3801 if (CountInits < NumInits
3802 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3803 APValue v;
3804 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3805 return Error(E);
3806 unsigned vlen = v.getVectorLength();
3807 for (unsigned j = 0; j < vlen; j++)
3808 Elements.push_back(v.getVectorElt(j));
3809 CountElts += vlen;
3810 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003811 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003812 if (CountInits < NumInits) {
3813 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
3814 return Error(E);
3815 } else // trailing integer zero.
3816 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3817 Elements.push_back(APValue(sInt));
3818 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003819 } else {
3820 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003821 if (CountInits < NumInits) {
3822 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
3823 return Error(E);
3824 } else // trailing float zero.
3825 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3826 Elements.push_back(APValue(f));
3827 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003828 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003829 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003830 }
Richard Smith07fc6572011-10-22 21:10:00 +00003831 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003832}
3833
Richard Smith07fc6572011-10-22 21:10:00 +00003834bool
Richard Smith51201882011-12-30 21:15:51 +00003835VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003836 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003837 QualType EltTy = VT->getElementType();
3838 APValue ZeroElement;
3839 if (EltTy->isIntegerType())
3840 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3841 else
3842 ZeroElement =
3843 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3844
Chris Lattner5f9e2722011-07-23 10:55:15 +00003845 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003846 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003847}
3848
Richard Smith07fc6572011-10-22 21:10:00 +00003849bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003850 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003851 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003852}
3853
Nate Begeman59b5da62009-01-18 03:20:47 +00003854//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003855// Array Evaluation
3856//===----------------------------------------------------------------------===//
3857
3858namespace {
3859 class ArrayExprEvaluator
3860 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003861 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003862 APValue &Result;
3863 public:
3864
Richard Smith180f4792011-11-10 06:34:14 +00003865 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3866 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003867
3868 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003869 assert((V.isArray() || V.isLValue()) &&
3870 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003871 Result = V;
3872 return true;
3873 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003874
Richard Smith51201882011-12-30 21:15:51 +00003875 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003876 const ConstantArrayType *CAT =
3877 Info.Ctx.getAsConstantArrayType(E->getType());
3878 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003879 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003880
3881 Result = APValue(APValue::UninitArray(), 0,
3882 CAT->getSize().getZExtValue());
3883 if (!Result.hasArrayFiller()) return true;
3884
Richard Smith51201882011-12-30 21:15:51 +00003885 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003886 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003887 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003888 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003889 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003890 }
3891
Richard Smithcc5d4f62011-11-07 09:22:26 +00003892 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003893 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003894 };
3895} // end anonymous namespace
3896
Richard Smith180f4792011-11-10 06:34:14 +00003897static bool EvaluateArray(const Expr *E, const LValue &This,
3898 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003899 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003900 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003901}
3902
3903bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3904 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3905 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003906 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003907
Richard Smith974c5f92011-12-22 01:07:19 +00003908 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3909 // an appropriately-typed string literal enclosed in braces.
Richard Smithec789162012-01-12 18:54:33 +00003910 if (E->getNumInits() == 1 && E->getInit(0)->isGLValue() &&
Richard Smith974c5f92011-12-22 01:07:19 +00003911 Info.Ctx.hasSameUnqualifiedType(E->getType(), E->getInit(0)->getType())) {
3912 LValue LV;
3913 if (!EvaluateLValue(E->getInit(0), LV, Info))
3914 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00003915 CCValue Val;
3916 LV.moveInto(Val);
3917 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003918 }
3919
Richard Smith745f5142012-01-27 01:14:48 +00003920 bool Success = true;
3921
Richard Smithcc5d4f62011-11-07 09:22:26 +00003922 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3923 CAT->getSize().getZExtValue());
Richard Smith180f4792011-11-10 06:34:14 +00003924 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003925 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003926 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003927 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003928 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003929 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3930 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003931 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3932 CAT->getElementType(), 1)) {
3933 if (!Info.keepEvaluatingAfterFailure())
3934 return false;
3935 Success = false;
3936 }
Richard Smith180f4792011-11-10 06:34:14 +00003937 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003938
Richard Smith745f5142012-01-27 01:14:48 +00003939 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003940 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003941 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3942 // but sometimes does:
3943 // struct S { constexpr S() : p(&p) {} void *p; };
3944 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003945 return EvaluateInPlace(Result.getArrayFiller(), Info,
3946 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003947}
3948
Richard Smithe24f5fc2011-11-17 22:56:20 +00003949bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3950 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3951 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003952 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003953
Richard Smithec789162012-01-12 18:54:33 +00003954 bool HadZeroInit = !Result.isUninit();
3955 if (!HadZeroInit)
3956 Result = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003957 if (!Result.hasArrayFiller())
3958 return true;
3959
3960 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003961
Richard Smith51201882011-12-30 21:15:51 +00003962 bool ZeroInit = E->requiresZeroInitialization();
3963 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003964 if (HadZeroInit)
3965 return true;
3966
Richard Smith51201882011-12-30 21:15:51 +00003967 if (ZeroInit) {
3968 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003969 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003970 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003971 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003972 }
3973
Richard Smith61802452011-12-22 02:22:31 +00003974 const CXXRecordDecl *RD = FD->getParent();
3975 if (RD->isUnion())
3976 Result.getArrayFiller() = APValue((FieldDecl*)0);
3977 else
3978 Result.getArrayFiller() =
3979 APValue(APValue::UninitStruct(), RD->getNumBases(),
3980 std::distance(RD->field_begin(), RD->field_end()));
3981 return true;
3982 }
3983
Richard Smithe24f5fc2011-11-17 22:56:20 +00003984 const FunctionDecl *Definition = 0;
3985 FD->getBody(Definition);
3986
Richard Smithc1c5f272011-12-13 06:39:58 +00003987 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3988 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003989
3990 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3991 // but sometimes does:
3992 // struct S { constexpr S() : p(&p) {} void *p; };
3993 // S s[10];
3994 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003995 Subobject.addArray(Info, E, CAT);
Richard Smith51201882011-12-30 21:15:51 +00003996
Richard Smithec789162012-01-12 18:54:33 +00003997 if (ZeroInit && !HadZeroInit) {
Richard Smith51201882011-12-30 21:15:51 +00003998 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003999 if (!EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00004000 return false;
4001 }
4002
Richard Smithe24f5fc2011-11-17 22:56:20 +00004003 llvm::ArrayRef<const Expr*> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00004004 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00004005 cast<CXXConstructorDecl>(Definition),
4006 Info, Result.getArrayFiller());
4007}
4008
Richard Smithcc5d4f62011-11-07 09:22:26 +00004009//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004010// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00004011//
4012// As a GNU extension, we support casting pointers to sufficiently-wide integer
4013// types and back in constant folding. Integer values are thus represented
4014// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004015//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004016
4017namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00004018class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004019 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith47a1eed2011-10-29 20:57:55 +00004020 CCValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00004021public:
Richard Smith47a1eed2011-10-29 20:57:55 +00004022 IntExprEvaluator(EvalInfo &info, CCValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004023 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004024
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004025 bool Success(const llvm::APSInt &SI, const Expr *E) {
4026 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004027 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004028 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004029 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004030 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004031 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00004032 Result = CCValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004033 return true;
4034 }
4035
Daniel Dunbar131eb432009-02-19 09:06:44 +00004036 bool Success(const llvm::APInt &I, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004037 assert(E->getType()->isIntegralOrEnumerationType() &&
4038 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004039 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004040 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00004041 Result = CCValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00004042 Result.getInt().setIsUnsigned(
4043 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00004044 return true;
4045 }
4046
4047 bool Success(uint64_t Value, const Expr *E) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004048 assert(E->getType()->isIntegralOrEnumerationType() &&
4049 "Invalid evaluation result.");
Richard Smith47a1eed2011-10-29 20:57:55 +00004050 Result = CCValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00004051 return true;
4052 }
4053
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004054 bool Success(CharUnits Size, const Expr *E) {
4055 return Success(Size.getQuantity(), E);
4056 }
4057
Richard Smith47a1eed2011-10-29 20:57:55 +00004058 bool Success(const CCValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00004059 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00004060 Result = V;
4061 return true;
4062 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004063 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00004064 }
Mike Stump1eb44332009-09-09 15:08:12 +00004065
Richard Smith51201882011-12-30 21:15:51 +00004066 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00004067
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004068 //===--------------------------------------------------------------------===//
4069 // Visitor Methods
4070 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00004071
Chris Lattner4c4867e2008-07-12 00:38:25 +00004072 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004073 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004074 }
4075 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004076 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00004077 }
Eli Friedman04309752009-11-24 05:28:59 +00004078
4079 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4080 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004081 if (CheckReferencedDecl(E, E->getDecl()))
4082 return true;
4083
4084 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004085 }
4086 bool VisitMemberExpr(const MemberExpr *E) {
4087 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00004088 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00004089 return true;
4090 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004091
4092 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00004093 }
4094
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004095 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004096 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00004097 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004098 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004099
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004100 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004101 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004102
Anders Carlsson3068d112008-11-16 19:01:22 +00004103 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004104 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004105 }
Mike Stump1eb44332009-09-09 15:08:12 +00004106
Richard Smithf10d9172011-10-11 21:43:33 +00004107 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004108 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004109 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004110 }
4111
Sebastian Redl64b45f72009-01-05 20:52:13 +00004112 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004113 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004114 }
4115
Francois Pichet6ad6f282010-12-07 00:08:36 +00004116 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4117 return Success(E->getValue(), E);
4118 }
4119
John Wiegley21ff2e52011-04-28 00:16:57 +00004120 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4121 return Success(E->getValue(), E);
4122 }
4123
John Wiegley55262202011-04-25 06:54:41 +00004124 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4125 return Success(E->getValue(), E);
4126 }
4127
Eli Friedman722c7172009-02-28 03:59:05 +00004128 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004129 bool VisitUnaryImag(const UnaryOperator *E);
4130
Sebastian Redl295995c2010-09-10 20:55:47 +00004131 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004132 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004133
Chris Lattnerfcee0012008-07-11 21:24:13 +00004134private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004135 CharUnits GetAlignOfExpr(const Expr *E);
4136 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004137 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004138 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004139 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004140};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004141} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004142
Richard Smithc49bd112011-10-28 17:51:58 +00004143/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4144/// produce either the integer value or a pointer.
4145///
4146/// GCC has a heinous extension which folds casts between pointer types and
4147/// pointer-sized integral types. We support this by allowing the evaluation of
4148/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4149/// Some simple arithmetic on such values is supported (they are treated much
4150/// like char*).
Richard Smithf48fdb02011-12-09 22:58:01 +00004151static bool EvaluateIntegerOrLValue(const Expr *E, CCValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004152 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004153 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004154 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004155}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004156
Richard Smithf48fdb02011-12-09 22:58:01 +00004157static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004158 CCValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004159 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004160 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004161 if (!Val.isInt()) {
4162 // FIXME: It would be better to produce the diagnostic for casting
4163 // a pointer to an integer.
Richard Smithdd1f29b2011-12-12 09:28:41 +00004164 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004165 return false;
4166 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004167 Result = Val.getInt();
4168 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004169}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004170
Richard Smithf48fdb02011-12-09 22:58:01 +00004171/// Check whether the given declaration can be directly converted to an integral
4172/// rvalue. If not, no diagnostic is produced; there are other things we can
4173/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004174bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004175 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004176 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004177 // Check for signedness/width mismatches between E type and ECD value.
4178 bool SameSign = (ECD->getInitVal().isSigned()
4179 == E->getType()->isSignedIntegerOrEnumerationType());
4180 bool SameWidth = (ECD->getInitVal().getBitWidth()
4181 == Info.Ctx.getIntWidth(E->getType()));
4182 if (SameSign && SameWidth)
4183 return Success(ECD->getInitVal(), E);
4184 else {
4185 // Get rid of mismatch (otherwise Success assertions will fail)
4186 // by computing a new value matching the type of E.
4187 llvm::APSInt Val = ECD->getInitVal();
4188 if (!SameSign)
4189 Val.setIsSigned(!ECD->getInitVal().isSigned());
4190 if (!SameWidth)
4191 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4192 return Success(Val, E);
4193 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004194 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004195 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004196}
4197
Chris Lattnera4d55d82008-10-06 06:40:35 +00004198/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4199/// as GCC.
4200static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4201 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004202 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004203 enum gcc_type_class {
4204 no_type_class = -1,
4205 void_type_class, integer_type_class, char_type_class,
4206 enumeral_type_class, boolean_type_class,
4207 pointer_type_class, reference_type_class, offset_type_class,
4208 real_type_class, complex_type_class,
4209 function_type_class, method_type_class,
4210 record_type_class, union_type_class,
4211 array_type_class, string_type_class,
4212 lang_type_class
4213 };
Mike Stump1eb44332009-09-09 15:08:12 +00004214
4215 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004216 // ideal, however it is what gcc does.
4217 if (E->getNumArgs() == 0)
4218 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004219
Chris Lattnera4d55d82008-10-06 06:40:35 +00004220 QualType ArgTy = E->getArg(0)->getType();
4221 if (ArgTy->isVoidType())
4222 return void_type_class;
4223 else if (ArgTy->isEnumeralType())
4224 return enumeral_type_class;
4225 else if (ArgTy->isBooleanType())
4226 return boolean_type_class;
4227 else if (ArgTy->isCharType())
4228 return string_type_class; // gcc doesn't appear to use char_type_class
4229 else if (ArgTy->isIntegerType())
4230 return integer_type_class;
4231 else if (ArgTy->isPointerType())
4232 return pointer_type_class;
4233 else if (ArgTy->isReferenceType())
4234 return reference_type_class;
4235 else if (ArgTy->isRealType())
4236 return real_type_class;
4237 else if (ArgTy->isComplexType())
4238 return complex_type_class;
4239 else if (ArgTy->isFunctionType())
4240 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004241 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004242 return record_type_class;
4243 else if (ArgTy->isUnionType())
4244 return union_type_class;
4245 else if (ArgTy->isArrayType())
4246 return array_type_class;
4247 else if (ArgTy->isUnionType())
4248 return union_type_class;
4249 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004250 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004251}
4252
Richard Smith80d4b552011-12-28 19:48:30 +00004253/// EvaluateBuiltinConstantPForLValue - Determine the result of
4254/// __builtin_constant_p when applied to the given lvalue.
4255///
4256/// An lvalue is only "constant" if it is a pointer or reference to the first
4257/// character of a string literal.
4258template<typename LValue>
4259static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
4260 const Expr *E = LV.getLValueBase().dyn_cast<const Expr*>();
4261 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4262}
4263
4264/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4265/// GCC as we can manage.
4266static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4267 QualType ArgType = Arg->getType();
4268
4269 // __builtin_constant_p always has one operand. The rules which gcc follows
4270 // are not precisely documented, but are as follows:
4271 //
4272 // - If the operand is of integral, floating, complex or enumeration type,
4273 // and can be folded to a known value of that type, it returns 1.
4274 // - If the operand and can be folded to a pointer to the first character
4275 // of a string literal (or such a pointer cast to an integral type), it
4276 // returns 1.
4277 //
4278 // Otherwise, it returns 0.
4279 //
4280 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4281 // its support for this does not currently work.
4282 if (ArgType->isIntegralOrEnumerationType()) {
4283 Expr::EvalResult Result;
4284 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4285 return false;
4286
4287 APValue &V = Result.Val;
4288 if (V.getKind() == APValue::Int)
4289 return true;
4290
4291 return EvaluateBuiltinConstantPForLValue(V);
4292 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4293 return Arg->isEvaluatable(Ctx);
4294 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4295 LValue LV;
4296 Expr::EvalStatus Status;
4297 EvalInfo Info(Ctx, Status);
4298 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4299 : EvaluatePointer(Arg, LV, Info)) &&
4300 !Status.HasSideEffects)
4301 return EvaluateBuiltinConstantPForLValue(LV);
4302 }
4303
4304 // Anything else isn't considered to be sufficiently constant.
4305 return false;
4306}
4307
John McCall42c8f872010-05-10 23:27:23 +00004308/// Retrieves the "underlying object type" of the given expression,
4309/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004310QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4311 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4312 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004313 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004314 } else if (const Expr *E = B.get<const Expr*>()) {
4315 if (isa<CompoundLiteralExpr>(E))
4316 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004317 }
4318
4319 return QualType();
4320}
4321
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004322bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004323 // TODO: Perhaps we should let LLVM lower this?
4324 LValue Base;
4325 if (!EvaluatePointer(E->getArg(0), Base, Info))
4326 return false;
4327
4328 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004329 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004330
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004331 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004332 if (T.isNull() ||
4333 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004334 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004335 T->isVariablyModifiedType() ||
4336 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004337 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004338
4339 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4340 CharUnits Offset = Base.getLValueOffset();
4341
4342 if (!Offset.isNegative() && Offset <= Size)
4343 Size -= Offset;
4344 else
4345 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004346 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004347}
4348
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004349bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00004350 switch (E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004351 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004352 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004353
4354 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004355 if (TryEvaluateBuiltinObjectSize(E))
4356 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004357
Eric Christopherb2aaf512010-01-19 22:58:35 +00004358 // If evaluating the argument has side-effects we can't determine
4359 // the size of the object and lower it to unknown now.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004360 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004361 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004362 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004363 return Success(0, E);
4364 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004365
Richard Smithf48fdb02011-12-09 22:58:01 +00004366 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004367 }
4368
Chris Lattner019f4e82008-10-06 05:28:25 +00004369 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004370 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004371
Richard Smith80d4b552011-12-28 19:48:30 +00004372 case Builtin::BI__builtin_constant_p:
4373 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004374
Chris Lattner21fb98e2009-09-23 06:06:36 +00004375 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004376 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004377 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004378 return Success(Operand, E);
4379 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004380
4381 case Builtin::BI__builtin_expect:
4382 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004383
Douglas Gregor5726d402010-09-10 06:27:15 +00004384 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004385 // A call to strlen is not a constant expression.
4386 if (Info.getLangOpts().CPlusPlus0x)
4387 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_invalid_function)
4388 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4389 else
4390 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
4391 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004392 case Builtin::BI__builtin_strlen:
4393 // As an extension, we support strlen() and __builtin_strlen() as constant
4394 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004395 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004396 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4397 // The string literal may have embedded null characters. Find the first
4398 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004399 StringRef Str = S->getString();
4400 StringRef::size_type Pos = Str.find(0);
4401 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004402 Str = Str.substr(0, Pos);
4403
4404 return Success(Str.size(), E);
4405 }
4406
Richard Smithf48fdb02011-12-09 22:58:01 +00004407 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004408
4409 case Builtin::BI__atomic_is_lock_free: {
4410 APSInt SizeVal;
4411 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4412 return false;
4413
4414 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4415 // of two less than the maximum inline atomic width, we know it is
4416 // lock-free. If the size isn't a power of two, or greater than the
4417 // maximum alignment where we promote atomics, we know it is not lock-free
4418 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4419 // the answer can only be determined at runtime; for example, 16-byte
4420 // atomics have lock-free implementations on some, but not all,
4421 // x86-64 processors.
4422
4423 // Check power-of-two.
4424 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
4425 if (!Size.isPowerOfTwo())
4426#if 0
4427 // FIXME: Suppress this folding until the ABI for the promotion width
4428 // settles.
4429 return Success(0, E);
4430#else
Richard Smithf48fdb02011-12-09 22:58:01 +00004431 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004432#endif
4433
4434#if 0
4435 // Check against promotion width.
4436 // FIXME: Suppress this folding until the ABI for the promotion width
4437 // settles.
4438 unsigned PromoteWidthBits =
4439 Info.Ctx.getTargetInfo().getMaxAtomicPromoteWidth();
4440 if (Size > Info.Ctx.toCharUnitsFromBits(PromoteWidthBits))
4441 return Success(0, E);
4442#endif
4443
4444 // Check against inlining width.
4445 unsigned InlineWidthBits =
4446 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4447 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits))
4448 return Success(1, E);
4449
Richard Smithf48fdb02011-12-09 22:58:01 +00004450 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004451 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004452 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004453}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004454
Richard Smith625b8072011-10-31 01:37:14 +00004455static bool HasSameBase(const LValue &A, const LValue &B) {
4456 if (!A.getLValueBase())
4457 return !B.getLValueBase();
4458 if (!B.getLValueBase())
4459 return false;
4460
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004461 if (A.getLValueBase().getOpaqueValue() !=
4462 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004463 const Decl *ADecl = GetLValueBaseDecl(A);
4464 if (!ADecl)
4465 return false;
4466 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004467 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004468 return false;
4469 }
4470
4471 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004472 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004473}
4474
Richard Smith7b48a292012-02-01 05:53:12 +00004475/// Perform the given integer operation, which is known to need at most BitWidth
4476/// bits, and check for overflow in the original type (if that type was not an
4477/// unsigned type).
4478template<typename Operation>
4479static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4480 const APSInt &LHS, const APSInt &RHS,
4481 unsigned BitWidth, Operation Op) {
4482 if (LHS.isUnsigned())
4483 return Op(LHS, RHS);
4484
4485 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4486 APSInt Result = Value.trunc(LHS.getBitWidth());
4487 if (Result.extend(BitWidth) != Value)
4488 HandleOverflow(Info, E, Value, E->getType());
4489 return Result;
4490}
4491
Chris Lattnerb542afe2008-07-11 19:10:17 +00004492bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00004493 if (E->isAssignmentOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004494 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00004495
John McCall2de56d12010-08-25 11:45:40 +00004496 if (E->getOpcode() == BO_Comma) {
Richard Smith8327fad2011-10-24 18:44:57 +00004497 VisitIgnoredValue(E->getLHS());
4498 return Visit(E->getRHS());
Eli Friedmana6afa762008-11-13 06:09:17 +00004499 }
4500
4501 if (E->isLogicalOp()) {
4502 // These need to be handled specially because the operands aren't
Richard Smith74e1ad92012-02-16 02:46:34 +00004503 // necessarily integral nor evaluated.
Anders Carlssonfcb4d092008-11-30 16:51:17 +00004504 bool lhsResult, rhsResult;
Mike Stump1eb44332009-09-09 15:08:12 +00004505
Richard Smithc49bd112011-10-28 17:51:58 +00004506 if (EvaluateAsBooleanCondition(E->getLHS(), lhsResult, Info)) {
Anders Carlsson51fe9962008-11-22 21:04:56 +00004507 // We were able to evaluate the LHS, see if we can get away with not
4508 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
John McCall2de56d12010-08-25 11:45:40 +00004509 if (lhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004510 return Success(lhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004511
Richard Smithc49bd112011-10-28 17:51:58 +00004512 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
John McCall2de56d12010-08-25 11:45:40 +00004513 if (E->getOpcode() == BO_LOr)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004514 return Success(lhsResult || rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004515 else
Daniel Dunbar131eb432009-02-19 09:06:44 +00004516 return Success(lhsResult && rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004517 }
4518 } else {
Richard Smith74e1ad92012-02-16 02:46:34 +00004519 // Since we weren't able to evaluate the left hand side, it
4520 // must have had side effects.
4521 Info.EvalStatus.HasSideEffects = true;
4522
4523 // Suppress diagnostics from this arm.
4524 SpeculativeEvaluationRAII Speculative(Info);
Richard Smithc49bd112011-10-28 17:51:58 +00004525 if (EvaluateAsBooleanCondition(E->getRHS(), rhsResult, Info)) {
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004526 // We can't evaluate the LHS; however, sometimes the result
4527 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
Richard Smith74e1ad92012-02-16 02:46:34 +00004528 if (rhsResult == (E->getOpcode() == BO_LOr))
Daniel Dunbar131eb432009-02-19 09:06:44 +00004529 return Success(rhsResult, E);
Anders Carlsson4bbc0e02008-11-24 04:21:33 +00004530 }
Anders Carlsson51fe9962008-11-22 21:04:56 +00004531 }
Eli Friedmana6afa762008-11-13 06:09:17 +00004532
Eli Friedmana6afa762008-11-13 06:09:17 +00004533 return false;
4534 }
4535
Anders Carlsson286f85e2008-11-16 07:17:21 +00004536 QualType LHSTy = E->getLHS()->getType();
4537 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004538
4539 if (LHSTy->isAnyComplexType()) {
4540 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004541 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004542
Richard Smith745f5142012-01-27 01:14:48 +00004543 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4544 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004545 return false;
4546
Richard Smith745f5142012-01-27 01:14:48 +00004547 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004548 return false;
4549
4550 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004551 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004552 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004553 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004554 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4555
John McCall2de56d12010-08-25 11:45:40 +00004556 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004557 return Success((CR_r == APFloat::cmpEqual &&
4558 CR_i == APFloat::cmpEqual), E);
4559 else {
John McCall2de56d12010-08-25 11:45:40 +00004560 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004561 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004562 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004563 CR_r == APFloat::cmpLessThan ||
4564 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004565 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004566 CR_i == APFloat::cmpLessThan ||
4567 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004568 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004569 } else {
John McCall2de56d12010-08-25 11:45:40 +00004570 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004571 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4572 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4573 else {
John McCall2de56d12010-08-25 11:45:40 +00004574 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004575 "Invalid compex comparison.");
4576 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4577 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4578 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004579 }
4580 }
Mike Stump1eb44332009-09-09 15:08:12 +00004581
Anders Carlsson286f85e2008-11-16 07:17:21 +00004582 if (LHSTy->isRealFloatingType() &&
4583 RHSTy->isRealFloatingType()) {
4584 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004585
Richard Smith745f5142012-01-27 01:14:48 +00004586 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4587 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004588 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004589
Richard Smith745f5142012-01-27 01:14:48 +00004590 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004591 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004592
Anders Carlsson286f85e2008-11-16 07:17:21 +00004593 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004594
Anders Carlsson286f85e2008-11-16 07:17:21 +00004595 switch (E->getOpcode()) {
4596 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004597 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004598 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004599 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004600 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004601 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004602 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004603 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004604 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004605 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004606 E);
John McCall2de56d12010-08-25 11:45:40 +00004607 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004608 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004609 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004610 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004611 || CR == APFloat::cmpLessThan
4612 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004613 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004614 }
Mike Stump1eb44332009-09-09 15:08:12 +00004615
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004616 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004617 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004618 LValue LHSValue, RHSValue;
4619
4620 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4621 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004622 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004623
Richard Smith745f5142012-01-27 01:14:48 +00004624 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004625 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004626
Richard Smith625b8072011-10-31 01:37:14 +00004627 // Reject differing bases from the normal codepath; we special-case
4628 // comparisons to null.
4629 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004630 if (E->getOpcode() == BO_Sub) {
4631 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004632 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4633 return false;
4634 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4635 const Expr *RHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
4636 if (!LHSExpr || !RHSExpr)
4637 return false;
4638 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4639 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4640 if (!LHSAddrExpr || !RHSAddrExpr)
4641 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004642 // Make sure both labels come from the same function.
4643 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4644 RHSAddrExpr->getLabel()->getDeclContext())
4645 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004646 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4647 return true;
4648 }
Richard Smith9e36b532011-10-31 05:11:32 +00004649 // Inequalities and subtractions between unrelated pointers have
4650 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004651 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004652 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004653 // A constant address may compare equal to the address of a symbol.
4654 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004655 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004656 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4657 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004658 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004659 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004660 // distinct addresses. In clang, the result of such a comparison is
4661 // unspecified, so it is not a constant expression. However, we do know
4662 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004663 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4664 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004665 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004666 // We can't tell whether weak symbols will end up pointing to the same
4667 // object.
4668 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004669 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004670 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004671 // (Note that clang defaults to -fmerge-all-constants, which can
4672 // lead to inconsistent results for comparisons involving the address
4673 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004674 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004675 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004676
Richard Smith15efc4d2012-02-01 08:10:20 +00004677 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4678 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4679
Richard Smithf15fda02012-02-02 01:16:57 +00004680 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4681 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4682
John McCall2de56d12010-08-25 11:45:40 +00004683 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004684 // C++11 [expr.add]p6:
4685 // Unless both pointers point to elements of the same array object, or
4686 // one past the last element of the array object, the behavior is
4687 // undefined.
4688 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4689 !AreElementsOfSameArray(getType(LHSValue.Base),
4690 LHSDesignator, RHSDesignator))
4691 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4692
Chris Lattner4992bdd2010-04-20 17:13:14 +00004693 QualType Type = E->getLHS()->getType();
4694 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004695
Richard Smith180f4792011-11-10 06:34:14 +00004696 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004697 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004698 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004699
Richard Smith15efc4d2012-02-01 08:10:20 +00004700 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4701 // and produce incorrect results when it overflows. Such behavior
4702 // appears to be non-conforming, but is common, so perhaps we should
4703 // assume the standard intended for such cases to be undefined behavior
4704 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004705
Richard Smith15efc4d2012-02-01 08:10:20 +00004706 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
4707 // overflow in the final conversion to ptrdiff_t.
4708 APSInt LHS(
4709 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
4710 APSInt RHS(
4711 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
4712 APSInt ElemSize(
4713 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
4714 APSInt TrueResult = (LHS - RHS) / ElemSize;
4715 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
4716
4717 if (Result.extend(65) != TrueResult)
4718 HandleOverflow(Info, E, TrueResult, E->getType());
4719 return Success(Result, E);
4720 }
Richard Smith82f28582012-01-31 06:41:30 +00004721
4722 // C++11 [expr.rel]p3:
4723 // Pointers to void (after pointer conversions) can be compared, with a
4724 // result defined as follows: If both pointers represent the same
4725 // address or are both the null pointer value, the result is true if the
4726 // operator is <= or >= and false otherwise; otherwise the result is
4727 // unspecified.
4728 // We interpret this as applying to pointers to *cv* void.
4729 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00004730 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00004731 CCEDiag(E, diag::note_constexpr_void_comparison);
4732
Richard Smithf15fda02012-02-02 01:16:57 +00004733 // C++11 [expr.rel]p2:
4734 // - If two pointers point to non-static data members of the same object,
4735 // or to subobjects or array elements fo such members, recursively, the
4736 // pointer to the later declared member compares greater provided the
4737 // two members have the same access control and provided their class is
4738 // not a union.
4739 // [...]
4740 // - Otherwise pointer comparisons are unspecified.
4741 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4742 E->isRelationalOp()) {
4743 bool WasArrayIndex;
4744 unsigned Mismatch =
4745 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
4746 RHSDesignator, WasArrayIndex);
4747 // At the point where the designators diverge, the comparison has a
4748 // specified value if:
4749 // - we are comparing array indices
4750 // - we are comparing fields of a union, or fields with the same access
4751 // Otherwise, the result is unspecified and thus the comparison is not a
4752 // constant expression.
4753 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
4754 Mismatch < RHSDesignator.Entries.size()) {
4755 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
4756 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
4757 if (!LF && !RF)
4758 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
4759 else if (!LF)
4760 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4761 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
4762 << RF->getParent() << RF;
4763 else if (!RF)
4764 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
4765 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
4766 << LF->getParent() << LF;
4767 else if (!LF->getParent()->isUnion() &&
4768 LF->getAccess() != RF->getAccess())
4769 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
4770 << LF << LF->getAccess() << RF << RF->getAccess()
4771 << LF->getParent();
4772 }
4773 }
4774
Richard Smith625b8072011-10-31 01:37:14 +00004775 switch (E->getOpcode()) {
4776 default: llvm_unreachable("missing comparison operator");
4777 case BO_LT: return Success(LHSOffset < RHSOffset, E);
4778 case BO_GT: return Success(LHSOffset > RHSOffset, E);
4779 case BO_LE: return Success(LHSOffset <= RHSOffset, E);
4780 case BO_GE: return Success(LHSOffset >= RHSOffset, E);
4781 case BO_EQ: return Success(LHSOffset == RHSOffset, E);
4782 case BO_NE: return Success(LHSOffset != RHSOffset, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004783 }
Anders Carlsson3068d112008-11-16 19:01:22 +00004784 }
4785 }
Richard Smithb02e4622012-02-01 01:42:44 +00004786
4787 if (LHSTy->isMemberPointerType()) {
4788 assert(E->isEqualityOp() && "unexpected member pointer operation");
4789 assert(RHSTy->isMemberPointerType() && "invalid comparison");
4790
4791 MemberPtr LHSValue, RHSValue;
4792
4793 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
4794 if (!LHSOK && Info.keepEvaluatingAfterFailure())
4795 return false;
4796
4797 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
4798 return false;
4799
4800 // C++11 [expr.eq]p2:
4801 // If both operands are null, they compare equal. Otherwise if only one is
4802 // null, they compare unequal.
4803 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
4804 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
4805 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4806 }
4807
4808 // Otherwise if either is a pointer to a virtual member function, the
4809 // result is unspecified.
4810 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
4811 if (MD->isVirtual())
4812 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4813 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
4814 if (MD->isVirtual())
4815 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
4816
4817 // Otherwise they compare equal if and only if they would refer to the
4818 // same member of the same most derived object or the same subobject if
4819 // they were dereferenced with a hypothetical object of the associated
4820 // class type.
4821 bool Equal = LHSValue == RHSValue;
4822 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
4823 }
4824
Richard Smith26f2cac2012-02-14 22:35:28 +00004825 if (LHSTy->isNullPtrType()) {
4826 assert(E->isComparisonOp() && "unexpected nullptr operation");
4827 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
4828 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
4829 // are compared, the result is true of the operator is <=, >= or ==, and
4830 // false otherwise.
4831 BinaryOperator::Opcode Opcode = E->getOpcode();
4832 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
4833 }
4834
Douglas Gregor2ade35e2010-06-16 00:17:44 +00004835 if (!LHSTy->isIntegralOrEnumerationType() ||
4836 !RHSTy->isIntegralOrEnumerationType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00004837 // We can't continue from here for non-integral types.
4838 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004839 }
4840
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004841 // The LHS of a constant expr is always evaluated and needed.
Richard Smith47a1eed2011-10-29 20:57:55 +00004842 CCValue LHSVal;
Richard Smith745f5142012-01-27 01:14:48 +00004843
4844 bool LHSOK = EvaluateIntegerOrLValue(E->getLHS(), LHSVal, Info);
4845 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Richard Smithf48fdb02011-12-09 22:58:01 +00004846 return false;
Eli Friedmand9f4bcd2008-07-27 05:46:18 +00004847
Richard Smith745f5142012-01-27 01:14:48 +00004848 if (!Visit(E->getRHS()) || !LHSOK)
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004849 return false;
Richard Smith745f5142012-01-27 01:14:48 +00004850
Richard Smith47a1eed2011-10-29 20:57:55 +00004851 CCValue &RHSVal = Result;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004852
4853 // Handle cases like (unsigned long)&a + 4.
Richard Smithc49bd112011-10-28 17:51:58 +00004854 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
Ken Dycka7305832010-01-15 12:37:54 +00004855 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4856 RHSVal.getInt().getZExtValue());
John McCall2de56d12010-08-25 11:45:40 +00004857 if (E->getOpcode() == BO_Add)
Richard Smith47a1eed2011-10-29 20:57:55 +00004858 LHSVal.getLValueOffset() += AdditionalOffset;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004859 else
Richard Smith47a1eed2011-10-29 20:57:55 +00004860 LHSVal.getLValueOffset() -= AdditionalOffset;
4861 Result = LHSVal;
Eli Friedman42edd0d2009-03-24 01:14:50 +00004862 return true;
4863 }
4864
4865 // Handle cases like 4 + (unsigned long)&a
John McCall2de56d12010-08-25 11:45:40 +00004866 if (E->getOpcode() == BO_Add &&
Richard Smithc49bd112011-10-28 17:51:58 +00004867 RHSVal.isLValue() && LHSVal.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00004868 RHSVal.getLValueOffset() += CharUnits::fromQuantity(
4869 LHSVal.getInt().getZExtValue());
4870 // Note that RHSVal is Result.
Eli Friedman42edd0d2009-03-24 01:14:50 +00004871 return true;
4872 }
4873
Eli Friedman65639282012-01-04 23:13:47 +00004874 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4875 // Handle (intptr_t)&&A - (intptr_t)&&B.
Eli Friedman65639282012-01-04 23:13:47 +00004876 if (!LHSVal.getLValueOffset().isZero() ||
4877 !RHSVal.getLValueOffset().isZero())
4878 return false;
4879 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4880 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4881 if (!LHSExpr || !RHSExpr)
4882 return false;
4883 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4884 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4885 if (!LHSAddrExpr || !RHSAddrExpr)
4886 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004887 // Make sure both labels come from the same function.
4888 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4889 RHSAddrExpr->getLabel()->getDeclContext())
4890 return false;
Eli Friedman65639282012-01-04 23:13:47 +00004891 Result = CCValue(LHSAddrExpr, RHSAddrExpr);
4892 return true;
4893 }
4894
Eli Friedman42edd0d2009-03-24 01:14:50 +00004895 // All the following cases expect both operands to be an integer
Richard Smithc49bd112011-10-28 17:51:58 +00004896 if (!LHSVal.isInt() || !RHSVal.isInt())
Richard Smithf48fdb02011-12-09 22:58:01 +00004897 return Error(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004898
Richard Smithc49bd112011-10-28 17:51:58 +00004899 APSInt &LHS = LHSVal.getInt();
4900 APSInt &RHS = RHSVal.getInt();
Eli Friedman42edd0d2009-03-24 01:14:50 +00004901
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004902 switch (E->getOpcode()) {
Chris Lattner32fea9d2008-11-12 07:43:42 +00004903 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00004904 return Error(E);
Richard Smith7b48a292012-02-01 05:53:12 +00004905 case BO_Mul:
4906 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4907 LHS.getBitWidth() * 2,
4908 std::multiplies<APSInt>()), E);
4909 case BO_Add:
4910 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4911 LHS.getBitWidth() + 1,
4912 std::plus<APSInt>()), E);
4913 case BO_Sub:
4914 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4915 LHS.getBitWidth() + 1,
4916 std::minus<APSInt>()), E);
Richard Smithc49bd112011-10-28 17:51:58 +00004917 case BO_And: return Success(LHS & RHS, E);
4918 case BO_Xor: return Success(LHS ^ RHS, E);
4919 case BO_Or: return Success(LHS | RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004920 case BO_Div:
John McCall2de56d12010-08-25 11:45:40 +00004921 case BO_Rem:
Chris Lattner54176fd2008-07-12 00:14:42 +00004922 if (RHS == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00004923 return Error(E, diag::note_expr_divide_by_zero);
Richard Smith3df61302012-01-31 23:24:19 +00004924 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is not
4925 // actually undefined behavior in C++11 due to a language defect.
4926 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4927 LHS.isSigned() && LHS.isMinSignedValue())
4928 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4929 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E);
John McCall2de56d12010-08-25 11:45:40 +00004930 case BO_Shl: {
Richard Smith789f9b62012-01-31 04:08:20 +00004931 // During constant-folding, a negative shift is an opposite shift. Such a
4932 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004933 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004934 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004935 RHS = -RHS;
4936 goto shift_right;
4937 }
4938
4939 shift_left:
Richard Smith789f9b62012-01-31 04:08:20 +00004940 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4941 // shifted type.
4942 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4943 if (SA != RHS) {
4944 CCEDiag(E, diag::note_constexpr_large_shift)
4945 << RHS << E->getType() << LHS.getBitWidth();
4946 } else if (LHS.isSigned()) {
4947 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
Richard Smith925d8e72012-02-08 06:14:53 +00004948 // operand, and must not overflow the corresponding unsigned type.
Richard Smith789f9b62012-01-31 04:08:20 +00004949 if (LHS.isNegative())
4950 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
Richard Smith925d8e72012-02-08 06:14:53 +00004951 else if (LHS.countLeadingZeros() < SA)
4952 CCEDiag(E, diag::note_constexpr_lshift_discards);
Richard Smith789f9b62012-01-31 04:08:20 +00004953 }
4954
Richard Smithc49bd112011-10-28 17:51:58 +00004955 return Success(LHS << SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004956 }
John McCall2de56d12010-08-25 11:45:40 +00004957 case BO_Shr: {
Richard Smith789f9b62012-01-31 04:08:20 +00004958 // During constant-folding, a negative shift is an opposite shift. Such a
4959 // shift is not a constant expression.
John McCall091f23f2010-11-09 22:22:12 +00004960 if (RHS.isSigned() && RHS.isNegative()) {
Richard Smith789f9b62012-01-31 04:08:20 +00004961 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
John McCall091f23f2010-11-09 22:22:12 +00004962 RHS = -RHS;
4963 goto shift_left;
4964 }
4965
4966 shift_right:
Richard Smith789f9b62012-01-31 04:08:20 +00004967 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4968 // shifted type.
4969 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4970 if (SA != RHS)
4971 CCEDiag(E, diag::note_constexpr_large_shift)
4972 << RHS << E->getType() << LHS.getBitWidth();
4973
Richard Smithc49bd112011-10-28 17:51:58 +00004974 return Success(LHS >> SA, E);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00004975 }
Mike Stump1eb44332009-09-09 15:08:12 +00004976
Richard Smithc49bd112011-10-28 17:51:58 +00004977 case BO_LT: return Success(LHS < RHS, E);
4978 case BO_GT: return Success(LHS > RHS, E);
4979 case BO_LE: return Success(LHS <= RHS, E);
4980 case BO_GE: return Success(LHS >= RHS, E);
4981 case BO_EQ: return Success(LHS == RHS, E);
4982 case BO_NE: return Success(LHS != RHS, E);
Eli Friedmanb11e7782008-11-13 02:13:11 +00004983 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004984}
4985
Ken Dyck8b752f12010-01-27 17:10:57 +00004986CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00004987 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
4988 // result shall be the alignment of the referenced type."
4989 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4990 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00004991
4992 // __alignof is defined to return the preferred alignment.
4993 return Info.Ctx.toCharUnitsFromBits(
4994 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00004995}
4996
Ken Dyck8b752f12010-01-27 17:10:57 +00004997CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00004998 E = E->IgnoreParens();
4999
5000 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005001 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005002 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005003 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5004 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005005
Chris Lattneraf707ab2009-01-24 21:53:27 +00005006 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005007 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5008 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005009
Chris Lattnere9feb472009-01-24 21:09:06 +00005010 return GetAlignOfType(E->getType());
5011}
5012
5013
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005014/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5015/// a result as the expression's type.
5016bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5017 const UnaryExprOrTypeTraitExpr *E) {
5018 switch(E->getKind()) {
5019 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005020 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005021 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005022 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005023 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005024 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005025
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005026 case UETT_VecStep: {
5027 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005028
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005029 if (Ty->isVectorType()) {
5030 unsigned n = Ty->getAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005031
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005032 // The vec_step built-in functions that take a 3-component
5033 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5034 if (n == 3)
5035 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005036
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005037 return Success(n, E);
5038 } else
5039 return Success(1, E);
5040 }
5041
5042 case UETT_SizeOf: {
5043 QualType SrcTy = E->getTypeOfArgument();
5044 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5045 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005046 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5047 SrcTy = Ref->getPointeeType();
5048
Richard Smith180f4792011-11-10 06:34:14 +00005049 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005050 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005051 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005052 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005053 }
5054 }
5055
5056 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005057}
5058
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005059bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005060 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005061 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005062 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005063 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005064 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005065 for (unsigned i = 0; i != n; ++i) {
5066 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5067 switch (ON.getKind()) {
5068 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005069 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005070 APSInt IdxResult;
5071 if (!EvaluateInteger(Idx, IdxResult, Info))
5072 return false;
5073 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5074 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005075 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005076 CurrentType = AT->getElementType();
5077 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5078 Result += IdxResult.getSExtValue() * ElementSize;
5079 break;
5080 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005081
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005082 case OffsetOfExpr::OffsetOfNode::Field: {
5083 FieldDecl *MemberDecl = ON.getField();
5084 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005085 if (!RT)
5086 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005087 RecordDecl *RD = RT->getDecl();
5088 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005089 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005090 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005091 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005092 CurrentType = MemberDecl->getType().getNonReferenceType();
5093 break;
5094 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005095
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005096 case OffsetOfExpr::OffsetOfNode::Identifier:
5097 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005098
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005099 case OffsetOfExpr::OffsetOfNode::Base: {
5100 CXXBaseSpecifier *BaseSpec = ON.getBase();
5101 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005102 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005103
5104 // Find the layout of the class whose base we are looking into.
5105 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005106 if (!RT)
5107 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005108 RecordDecl *RD = RT->getDecl();
5109 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5110
5111 // Find the base class itself.
5112 CurrentType = BaseSpec->getType();
5113 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5114 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005115 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005116
5117 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005118 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005119 break;
5120 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005121 }
5122 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005123 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005124}
5125
Chris Lattnerb542afe2008-07-11 19:10:17 +00005126bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005127 switch (E->getOpcode()) {
5128 default:
5129 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5130 // See C99 6.6p3.
5131 return Error(E);
5132 case UO_Extension:
5133 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5134 // If so, we could clear the diagnostic ID.
5135 return Visit(E->getSubExpr());
5136 case UO_Plus:
5137 // The result is just the value.
5138 return Visit(E->getSubExpr());
5139 case UO_Minus: {
5140 if (!Visit(E->getSubExpr()))
5141 return false;
5142 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005143 const APSInt &Value = Result.getInt();
5144 if (Value.isSigned() && Value.isMinSignedValue())
5145 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5146 E->getType());
5147 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005148 }
5149 case UO_Not: {
5150 if (!Visit(E->getSubExpr()))
5151 return false;
5152 if (!Result.isInt()) return Error(E);
5153 return Success(~Result.getInt(), E);
5154 }
5155 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005156 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005157 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005158 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005159 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005160 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005161 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005162}
Mike Stump1eb44332009-09-09 15:08:12 +00005163
Chris Lattner732b2232008-07-12 01:15:53 +00005164/// HandleCast - This is used to evaluate implicit or explicit casts where the
5165/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005166bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5167 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005168 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005169 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005170
Eli Friedman46a52322011-03-25 00:43:55 +00005171 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005172 case CK_BaseToDerived:
5173 case CK_DerivedToBase:
5174 case CK_UncheckedDerivedToBase:
5175 case CK_Dynamic:
5176 case CK_ToUnion:
5177 case CK_ArrayToPointerDecay:
5178 case CK_FunctionToPointerDecay:
5179 case CK_NullToPointer:
5180 case CK_NullToMemberPointer:
5181 case CK_BaseToDerivedMemberPointer:
5182 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005183 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005184 case CK_ConstructorConversion:
5185 case CK_IntegralToPointer:
5186 case CK_ToVoid:
5187 case CK_VectorSplat:
5188 case CK_IntegralToFloating:
5189 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005190 case CK_CPointerToObjCPointerCast:
5191 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005192 case CK_AnyPointerToBlockPointerCast:
5193 case CK_ObjCObjectLValueCast:
5194 case CK_FloatingRealToComplex:
5195 case CK_FloatingComplexToReal:
5196 case CK_FloatingComplexCast:
5197 case CK_FloatingComplexToIntegralComplex:
5198 case CK_IntegralRealToComplex:
5199 case CK_IntegralComplexCast:
5200 case CK_IntegralComplexToFloatingComplex:
5201 llvm_unreachable("invalid cast kind for integral value");
5202
Eli Friedmane50c2972011-03-25 19:07:11 +00005203 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005204 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005205 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005206 case CK_ARCProduceObject:
5207 case CK_ARCConsumeObject:
5208 case CK_ARCReclaimReturnedObject:
5209 case CK_ARCExtendBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005210 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005211
Richard Smith7d580a42012-01-17 21:17:26 +00005212 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005213 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005214 case CK_AtomicToNonAtomic:
5215 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005216 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005217 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005218
5219 case CK_MemberPointerToBoolean:
5220 case CK_PointerToBoolean:
5221 case CK_IntegralToBoolean:
5222 case CK_FloatingToBoolean:
5223 case CK_FloatingComplexToBoolean:
5224 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005225 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005226 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005227 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005228 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005229 }
5230
Eli Friedman46a52322011-03-25 00:43:55 +00005231 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005232 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005233 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005234
Eli Friedmanbe265702009-02-20 01:15:07 +00005235 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005236 // Allow casts of address-of-label differences if they are no-ops
5237 // or narrowing. (The narrowing case isn't actually guaranteed to
5238 // be constant-evaluatable except in some narrow cases which are hard
5239 // to detect here. We let it through on the assumption the user knows
5240 // what they are doing.)
5241 if (Result.isAddrLabelDiff())
5242 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005243 // Only allow casts of lvalues if they are lossless.
5244 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5245 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005246
Richard Smithf72fccf2012-01-30 22:27:01 +00005247 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5248 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005249 }
Mike Stump1eb44332009-09-09 15:08:12 +00005250
Eli Friedman46a52322011-03-25 00:43:55 +00005251 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005252 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5253
John McCallefdb83e2010-05-07 21:00:08 +00005254 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005255 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005256 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005257
Daniel Dunbardd211642009-02-19 22:24:01 +00005258 if (LV.getLValueBase()) {
5259 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005260 // FIXME: Allow a larger integer size than the pointer size, and allow
5261 // narrowing back down to pointer width in subsequent integral casts.
5262 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005263 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005264 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005265
Richard Smithb755a9d2011-11-16 07:18:12 +00005266 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005267 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005268 return true;
5269 }
5270
Ken Dycka7305832010-01-15 12:37:54 +00005271 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5272 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005273 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005274 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005275
Eli Friedman46a52322011-03-25 00:43:55 +00005276 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005277 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005278 if (!EvaluateComplex(SubExpr, C, Info))
5279 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005280 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005281 }
Eli Friedman2217c872009-02-22 11:46:18 +00005282
Eli Friedman46a52322011-03-25 00:43:55 +00005283 case CK_FloatingToIntegral: {
5284 APFloat F(0.0);
5285 if (!EvaluateFloat(SubExpr, F, Info))
5286 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005287
Richard Smithc1c5f272011-12-13 06:39:58 +00005288 APSInt Value;
5289 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5290 return false;
5291 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005292 }
5293 }
Mike Stump1eb44332009-09-09 15:08:12 +00005294
Eli Friedman46a52322011-03-25 00:43:55 +00005295 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005296}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005297
Eli Friedman722c7172009-02-28 03:59:05 +00005298bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5299 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005300 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005301 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5302 return false;
5303 if (!LV.isComplexInt())
5304 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005305 return Success(LV.getComplexIntReal(), E);
5306 }
5307
5308 return Visit(E->getSubExpr());
5309}
5310
Eli Friedman664a1042009-02-27 04:45:43 +00005311bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005312 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005313 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005314 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5315 return false;
5316 if (!LV.isComplexInt())
5317 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005318 return Success(LV.getComplexIntImag(), E);
5319 }
5320
Richard Smith8327fad2011-10-24 18:44:57 +00005321 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005322 return Success(0, E);
5323}
5324
Douglas Gregoree8aff02011-01-04 17:33:58 +00005325bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5326 return Success(E->getPackLength(), E);
5327}
5328
Sebastian Redl295995c2010-09-10 20:55:47 +00005329bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5330 return Success(E->getValue(), E);
5331}
5332
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005333//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005334// Float Evaluation
5335//===----------------------------------------------------------------------===//
5336
5337namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005338class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005339 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005340 APFloat &Result;
5341public:
5342 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005343 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005344
Richard Smith47a1eed2011-10-29 20:57:55 +00005345 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005346 Result = V.getFloat();
5347 return true;
5348 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005349
Richard Smith51201882011-12-30 21:15:51 +00005350 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005351 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5352 return true;
5353 }
5354
Chris Lattner019f4e82008-10-06 05:28:25 +00005355 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005356
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005357 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005358 bool VisitBinaryOperator(const BinaryOperator *E);
5359 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005360 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005361
John McCallabd3a852010-05-07 22:08:54 +00005362 bool VisitUnaryReal(const UnaryOperator *E);
5363 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005364
Richard Smith51201882011-12-30 21:15:51 +00005365 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005366};
5367} // end anonymous namespace
5368
5369static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005370 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005371 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005372}
5373
Jay Foad4ba2a172011-01-12 09:06:06 +00005374static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005375 QualType ResultTy,
5376 const Expr *Arg,
5377 bool SNaN,
5378 llvm::APFloat &Result) {
5379 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5380 if (!S) return false;
5381
5382 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5383
5384 llvm::APInt fill;
5385
5386 // Treat empty strings as if they were zero.
5387 if (S->getString().empty())
5388 fill = llvm::APInt(32, 0);
5389 else if (S->getString().getAsInteger(0, fill))
5390 return false;
5391
5392 if (SNaN)
5393 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5394 else
5395 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5396 return true;
5397}
5398
Chris Lattner019f4e82008-10-06 05:28:25 +00005399bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005400 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005401 default:
5402 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5403
Chris Lattner019f4e82008-10-06 05:28:25 +00005404 case Builtin::BI__builtin_huge_val:
5405 case Builtin::BI__builtin_huge_valf:
5406 case Builtin::BI__builtin_huge_vall:
5407 case Builtin::BI__builtin_inf:
5408 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005409 case Builtin::BI__builtin_infl: {
5410 const llvm::fltSemantics &Sem =
5411 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005412 Result = llvm::APFloat::getInf(Sem);
5413 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005414 }
Mike Stump1eb44332009-09-09 15:08:12 +00005415
John McCalldb7b72a2010-02-28 13:00:19 +00005416 case Builtin::BI__builtin_nans:
5417 case Builtin::BI__builtin_nansf:
5418 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005419 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5420 true, Result))
5421 return Error(E);
5422 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005423
Chris Lattner9e621712008-10-06 06:31:58 +00005424 case Builtin::BI__builtin_nan:
5425 case Builtin::BI__builtin_nanf:
5426 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005427 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005428 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005429 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5430 false, Result))
5431 return Error(E);
5432 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005433
5434 case Builtin::BI__builtin_fabs:
5435 case Builtin::BI__builtin_fabsf:
5436 case Builtin::BI__builtin_fabsl:
5437 if (!EvaluateFloat(E->getArg(0), Result, Info))
5438 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005439
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005440 if (Result.isNegative())
5441 Result.changeSign();
5442 return true;
5443
Mike Stump1eb44332009-09-09 15:08:12 +00005444 case Builtin::BI__builtin_copysign:
5445 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005446 case Builtin::BI__builtin_copysignl: {
5447 APFloat RHS(0.);
5448 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5449 !EvaluateFloat(E->getArg(1), RHS, Info))
5450 return false;
5451 Result.copySign(RHS);
5452 return true;
5453 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005454 }
5455}
5456
John McCallabd3a852010-05-07 22:08:54 +00005457bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005458 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5459 ComplexValue CV;
5460 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5461 return false;
5462 Result = CV.FloatReal;
5463 return true;
5464 }
5465
5466 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005467}
5468
5469bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005470 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5471 ComplexValue CV;
5472 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5473 return false;
5474 Result = CV.FloatImag;
5475 return true;
5476 }
5477
Richard Smith8327fad2011-10-24 18:44:57 +00005478 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005479 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5480 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005481 return true;
5482}
5483
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005484bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005485 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005486 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005487 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005488 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005489 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005490 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5491 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005492 Result.changeSign();
5493 return true;
5494 }
5495}
Chris Lattner019f4e82008-10-06 05:28:25 +00005496
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005497bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005498 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5499 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005500
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005501 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005502 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5503 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005504 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005505 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005506 return false;
5507
5508 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005509 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005510 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005511 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005512 break;
John McCall2de56d12010-08-25 11:45:40 +00005513 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005514 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005515 break;
John McCall2de56d12010-08-25 11:45:40 +00005516 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005517 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005518 break;
John McCall2de56d12010-08-25 11:45:40 +00005519 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005520 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005521 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005522 }
Richard Smith7b48a292012-02-01 05:53:12 +00005523
5524 if (Result.isInfinity() || Result.isNaN())
5525 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5526 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005527}
5528
5529bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5530 Result = E->getValue();
5531 return true;
5532}
5533
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005534bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5535 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005536
Eli Friedman2a523ee2011-03-25 00:54:52 +00005537 switch (E->getCastKind()) {
5538 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005539 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005540
5541 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005542 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005543 return EvaluateInteger(SubExpr, IntResult, Info) &&
5544 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5545 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005546 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005547
5548 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005549 if (!Visit(SubExpr))
5550 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005551 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5552 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005553 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005554
Eli Friedman2a523ee2011-03-25 00:54:52 +00005555 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005556 ComplexValue V;
5557 if (!EvaluateComplex(SubExpr, V, Info))
5558 return false;
5559 Result = V.getComplexFloatReal();
5560 return true;
5561 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005562 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005563}
5564
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005565//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005566// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005567//===----------------------------------------------------------------------===//
5568
5569namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005570class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005571 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005572 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005573
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005574public:
John McCallf4cf1a12010-05-07 17:22:02 +00005575 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005576 : ExprEvaluatorBaseTy(info), Result(Result) {}
5577
Richard Smith47a1eed2011-10-29 20:57:55 +00005578 bool Success(const CCValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005579 Result.setFrom(V);
5580 return true;
5581 }
Mike Stump1eb44332009-09-09 15:08:12 +00005582
Eli Friedman7ead5c72012-01-10 04:58:17 +00005583 bool ZeroInitialization(const Expr *E);
5584
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005585 //===--------------------------------------------------------------------===//
5586 // Visitor Methods
5587 //===--------------------------------------------------------------------===//
5588
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005589 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005590 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005591 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005592 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005593 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005594};
5595} // end anonymous namespace
5596
John McCallf4cf1a12010-05-07 17:22:02 +00005597static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5598 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005599 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005600 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005601}
5602
Eli Friedman7ead5c72012-01-10 04:58:17 +00005603bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Eli Friedmanf6c17a42012-01-13 23:34:56 +00005604 QualType ElemTy = E->getType()->getAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005605 if (ElemTy->isRealFloatingType()) {
5606 Result.makeComplexFloat();
5607 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5608 Result.FloatReal = Zero;
5609 Result.FloatImag = Zero;
5610 } else {
5611 Result.makeComplexInt();
5612 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5613 Result.IntReal = Zero;
5614 Result.IntImag = Zero;
5615 }
5616 return true;
5617}
5618
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005619bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5620 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005621
5622 if (SubExpr->getType()->isRealFloatingType()) {
5623 Result.makeComplexFloat();
5624 APFloat &Imag = Result.FloatImag;
5625 if (!EvaluateFloat(SubExpr, Imag, Info))
5626 return false;
5627
5628 Result.FloatReal = APFloat(Imag.getSemantics());
5629 return true;
5630 } else {
5631 assert(SubExpr->getType()->isIntegerType() &&
5632 "Unexpected imaginary literal.");
5633
5634 Result.makeComplexInt();
5635 APSInt &Imag = Result.IntImag;
5636 if (!EvaluateInteger(SubExpr, Imag, Info))
5637 return false;
5638
5639 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5640 return true;
5641 }
5642}
5643
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005644bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005645
John McCall8786da72010-12-14 17:51:41 +00005646 switch (E->getCastKind()) {
5647 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005648 case CK_BaseToDerived:
5649 case CK_DerivedToBase:
5650 case CK_UncheckedDerivedToBase:
5651 case CK_Dynamic:
5652 case CK_ToUnion:
5653 case CK_ArrayToPointerDecay:
5654 case CK_FunctionToPointerDecay:
5655 case CK_NullToPointer:
5656 case CK_NullToMemberPointer:
5657 case CK_BaseToDerivedMemberPointer:
5658 case CK_DerivedToBaseMemberPointer:
5659 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005660 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005661 case CK_ConstructorConversion:
5662 case CK_IntegralToPointer:
5663 case CK_PointerToIntegral:
5664 case CK_PointerToBoolean:
5665 case CK_ToVoid:
5666 case CK_VectorSplat:
5667 case CK_IntegralCast:
5668 case CK_IntegralToBoolean:
5669 case CK_IntegralToFloating:
5670 case CK_FloatingToIntegral:
5671 case CK_FloatingToBoolean:
5672 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005673 case CK_CPointerToObjCPointerCast:
5674 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005675 case CK_AnyPointerToBlockPointerCast:
5676 case CK_ObjCObjectLValueCast:
5677 case CK_FloatingComplexToReal:
5678 case CK_FloatingComplexToBoolean:
5679 case CK_IntegralComplexToReal:
5680 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005681 case CK_ARCProduceObject:
5682 case CK_ARCConsumeObject:
5683 case CK_ARCReclaimReturnedObject:
5684 case CK_ARCExtendBlockObject:
John McCall8786da72010-12-14 17:51:41 +00005685 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005686
John McCall8786da72010-12-14 17:51:41 +00005687 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005688 case CK_AtomicToNonAtomic:
5689 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005690 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005691 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005692
5693 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005694 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005695 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005696 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005697
5698 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005699 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005700 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005701 return false;
5702
John McCall8786da72010-12-14 17:51:41 +00005703 Result.makeComplexFloat();
5704 Result.FloatImag = APFloat(Real.getSemantics());
5705 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005706 }
5707
John McCall8786da72010-12-14 17:51:41 +00005708 case CK_FloatingComplexCast: {
5709 if (!Visit(E->getSubExpr()))
5710 return false;
5711
5712 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5713 QualType From
5714 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5715
Richard Smithc1c5f272011-12-13 06:39:58 +00005716 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5717 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005718 }
5719
5720 case CK_FloatingComplexToIntegralComplex: {
5721 if (!Visit(E->getSubExpr()))
5722 return false;
5723
5724 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5725 QualType From
5726 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5727 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005728 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5729 To, Result.IntReal) &&
5730 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5731 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005732 }
5733
5734 case CK_IntegralRealToComplex: {
5735 APSInt &Real = Result.IntReal;
5736 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5737 return false;
5738
5739 Result.makeComplexInt();
5740 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5741 return true;
5742 }
5743
5744 case CK_IntegralComplexCast: {
5745 if (!Visit(E->getSubExpr()))
5746 return false;
5747
5748 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5749 QualType From
5750 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5751
Richard Smithf72fccf2012-01-30 22:27:01 +00005752 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5753 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005754 return true;
5755 }
5756
5757 case CK_IntegralComplexToFloatingComplex: {
5758 if (!Visit(E->getSubExpr()))
5759 return false;
5760
5761 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5762 QualType From
5763 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5764 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005765 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5766 To, Result.FloatReal) &&
5767 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5768 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005769 }
5770 }
5771
5772 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005773}
5774
John McCallf4cf1a12010-05-07 17:22:02 +00005775bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005776 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005777 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5778
Richard Smith745f5142012-01-27 01:14:48 +00005779 bool LHSOK = Visit(E->getLHS());
5780 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005781 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005782
John McCallf4cf1a12010-05-07 17:22:02 +00005783 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005784 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005785 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005786
Daniel Dunbar3f279872009-01-29 01:32:56 +00005787 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5788 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005789 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005790 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005791 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005792 if (Result.isComplexFloat()) {
5793 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5794 APFloat::rmNearestTiesToEven);
5795 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5796 APFloat::rmNearestTiesToEven);
5797 } else {
5798 Result.getComplexIntReal() += RHS.getComplexIntReal();
5799 Result.getComplexIntImag() += RHS.getComplexIntImag();
5800 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005801 break;
John McCall2de56d12010-08-25 11:45:40 +00005802 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005803 if (Result.isComplexFloat()) {
5804 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5805 APFloat::rmNearestTiesToEven);
5806 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5807 APFloat::rmNearestTiesToEven);
5808 } else {
5809 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5810 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5811 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005812 break;
John McCall2de56d12010-08-25 11:45:40 +00005813 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005814 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005815 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005816 APFloat &LHS_r = LHS.getComplexFloatReal();
5817 APFloat &LHS_i = LHS.getComplexFloatImag();
5818 APFloat &RHS_r = RHS.getComplexFloatReal();
5819 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00005820
Daniel Dunbar3f279872009-01-29 01:32:56 +00005821 APFloat Tmp = LHS_r;
5822 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5823 Result.getComplexFloatReal() = Tmp;
5824 Tmp = LHS_i;
5825 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5826 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
5827
5828 Tmp = LHS_r;
5829 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5830 Result.getComplexFloatImag() = Tmp;
5831 Tmp = LHS_i;
5832 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5833 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
5834 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00005835 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005836 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005837 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
5838 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00005839 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00005840 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
5841 LHS.getComplexIntImag() * RHS.getComplexIntReal());
5842 }
5843 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005844 case BO_Div:
5845 if (Result.isComplexFloat()) {
5846 ComplexValue LHS = Result;
5847 APFloat &LHS_r = LHS.getComplexFloatReal();
5848 APFloat &LHS_i = LHS.getComplexFloatImag();
5849 APFloat &RHS_r = RHS.getComplexFloatReal();
5850 APFloat &RHS_i = RHS.getComplexFloatImag();
5851 APFloat &Res_r = Result.getComplexFloatReal();
5852 APFloat &Res_i = Result.getComplexFloatImag();
5853
5854 APFloat Den = RHS_r;
5855 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5856 APFloat Tmp = RHS_i;
5857 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5858 Den.add(Tmp, APFloat::rmNearestTiesToEven);
5859
5860 Res_r = LHS_r;
5861 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5862 Tmp = LHS_i;
5863 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5864 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
5865 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
5866
5867 Res_i = LHS_i;
5868 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
5869 Tmp = LHS_r;
5870 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
5871 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
5872 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
5873 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00005874 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
5875 return Error(E, diag::note_expr_divide_by_zero);
5876
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005877 ComplexValue LHS = Result;
5878 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
5879 RHS.getComplexIntImag() * RHS.getComplexIntImag();
5880 Result.getComplexIntReal() =
5881 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
5882 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
5883 Result.getComplexIntImag() =
5884 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
5885 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
5886 }
5887 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005888 }
5889
John McCallf4cf1a12010-05-07 17:22:02 +00005890 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005891}
5892
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005893bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
5894 // Get the operand value into 'Result'.
5895 if (!Visit(E->getSubExpr()))
5896 return false;
5897
5898 switch (E->getOpcode()) {
5899 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00005900 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005901 case UO_Extension:
5902 return true;
5903 case UO_Plus:
5904 // The result is always just the subexpr.
5905 return true;
5906 case UO_Minus:
5907 if (Result.isComplexFloat()) {
5908 Result.getComplexFloatReal().changeSign();
5909 Result.getComplexFloatImag().changeSign();
5910 }
5911 else {
5912 Result.getComplexIntReal() = -Result.getComplexIntReal();
5913 Result.getComplexIntImag() = -Result.getComplexIntImag();
5914 }
5915 return true;
5916 case UO_Not:
5917 if (Result.isComplexFloat())
5918 Result.getComplexFloatImag().changeSign();
5919 else
5920 Result.getComplexIntImag() = -Result.getComplexIntImag();
5921 return true;
5922 }
5923}
5924
Eli Friedman7ead5c72012-01-10 04:58:17 +00005925bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5926 if (E->getNumInits() == 2) {
5927 if (E->getType()->isComplexType()) {
5928 Result.makeComplexFloat();
5929 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
5930 return false;
5931 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
5932 return false;
5933 } else {
5934 Result.makeComplexInt();
5935 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
5936 return false;
5937 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
5938 return false;
5939 }
5940 return true;
5941 }
5942 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
5943}
5944
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005945//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00005946// Void expression evaluation, primarily for a cast to void on the LHS of a
5947// comma operator
5948//===----------------------------------------------------------------------===//
5949
5950namespace {
5951class VoidExprEvaluator
5952 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
5953public:
5954 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
5955
5956 bool Success(const CCValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00005957
5958 bool VisitCastExpr(const CastExpr *E) {
5959 switch (E->getCastKind()) {
5960 default:
5961 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5962 case CK_ToVoid:
5963 VisitIgnoredValue(E->getSubExpr());
5964 return true;
5965 }
5966 }
5967};
5968} // end anonymous namespace
5969
5970static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
5971 assert(E->isRValue() && E->getType()->isVoidType());
5972 return VoidExprEvaluator(Info).Visit(E);
5973}
5974
5975//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00005976// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005977//===----------------------------------------------------------------------===//
5978
Richard Smith47a1eed2011-10-29 20:57:55 +00005979static bool Evaluate(CCValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00005980 // In C, function designators are not lvalues, but we evaluate them as if they
5981 // are.
5982 if (E->isGLValue() || E->getType()->isFunctionType()) {
5983 LValue LV;
5984 if (!EvaluateLValue(E, LV, Info))
5985 return false;
5986 LV.moveInto(Result);
5987 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005988 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00005989 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00005990 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00005991 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005992 return false;
John McCallefdb83e2010-05-07 21:00:08 +00005993 } else if (E->getType()->hasPointerRepresentation()) {
5994 LValue LV;
5995 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00005996 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00005997 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00005998 } else if (E->getType()->isRealFloatingType()) {
5999 llvm::APFloat F(0.0);
6000 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006001 return false;
Richard Smith47a1eed2011-10-29 20:57:55 +00006002 Result = CCValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006003 } else if (E->getType()->isAnyComplexType()) {
6004 ComplexValue C;
6005 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006006 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006007 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006008 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006009 MemberPtr P;
6010 if (!EvaluateMemberPointer(E, P, Info))
6011 return false;
6012 P.moveInto(Result);
6013 return true;
Richard Smith51201882011-12-30 21:15:51 +00006014 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006015 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006016 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006017 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006018 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006019 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006020 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006021 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006022 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006023 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6024 return false;
6025 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006026 } else if (E->getType()->isVoidType()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00006027 if (Info.getLangOpts().CPlusPlus0x)
6028 Info.CCEDiag(E->getExprLoc(), diag::note_constexpr_nonliteral)
6029 << E->getType();
6030 else
6031 Info.CCEDiag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Richard Smithaa9c3502011-12-07 00:43:50 +00006032 if (!EvaluateVoid(E, Info))
6033 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00006034 } else if (Info.getLangOpts().CPlusPlus0x) {
6035 Info.Diag(E->getExprLoc(), diag::note_constexpr_nonliteral) << E->getType();
6036 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006037 } else {
Richard Smithdd1f29b2011-12-12 09:28:41 +00006038 Info.Diag(E->getExprLoc(), diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006039 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006040 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006041
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006042 return true;
6043}
6044
Richard Smith83587db2012-02-15 02:18:13 +00006045/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6046/// cases, the in-place evaluation is essential, since later initializers for
6047/// an object can indirectly refer to subobjects which were initialized earlier.
6048static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6049 const Expr *E, CheckConstantExpressionKind CCEK,
6050 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006051 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006052 return false;
6053
6054 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006055 // Evaluate arrays and record types in-place, so that later initializers can
6056 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006057 if (E->getType()->isArrayType())
6058 return EvaluateArray(E, This, Result, Info);
6059 else if (E->getType()->isRecordType())
6060 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006061 }
6062
6063 // For any other type, in-place evaluation is unimportant.
6064 CCValue CoreConstResult;
Richard Smith83587db2012-02-15 02:18:13 +00006065 if (!Evaluate(CoreConstResult, Info, E))
6066 return false;
6067 Result = CoreConstResult.toAPValue();
6068 return true;
Richard Smith69c2c502011-11-04 05:33:44 +00006069}
6070
Richard Smithf48fdb02011-12-09 22:58:01 +00006071/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6072/// lvalue-to-rvalue cast if it is an lvalue.
6073static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006074 if (!CheckLiteralType(Info, E))
6075 return false;
6076
Richard Smithf48fdb02011-12-09 22:58:01 +00006077 CCValue Value;
6078 if (!::Evaluate(Value, Info, E))
6079 return false;
6080
6081 if (E->isGLValue()) {
6082 LValue LV;
6083 LV.setFrom(Value);
6084 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Value))
6085 return false;
6086 }
6087
6088 // Check this core constant expression is a constant expression, and if so,
6089 // convert it to one.
Richard Smith83587db2012-02-15 02:18:13 +00006090 Result = Value.toAPValue();
6091 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006092}
Richard Smithc49bd112011-10-28 17:51:58 +00006093
Richard Smith51f47082011-10-29 00:50:52 +00006094/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006095/// any crazy technique (that has nothing to do with language standards) that
6096/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006097/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6098/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006099bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smithee19f432011-12-10 01:10:13 +00006100 // Fast-path evaluations of integer literals, since we sometimes see files
6101 // containing vast quantities of these.
6102 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(this)) {
6103 Result.Val = APValue(APSInt(L->getValue(),
6104 L->getType()->isUnsignedIntegerType()));
6105 return true;
6106 }
6107
Richard Smith2d6a5672012-01-14 04:30:29 +00006108 // FIXME: Evaluating values of large array and record types can cause
6109 // performance problems. Only do so in C++11 for now.
Richard Smithe24f5fc2011-11-17 22:56:20 +00006110 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6111 !Ctx.getLangOptions().CPlusPlus0x)
Richard Smith1445bba2011-11-10 03:30:42 +00006112 return false;
6113
Richard Smithf48fdb02011-12-09 22:58:01 +00006114 EvalInfo Info(Ctx, Result);
6115 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006116}
6117
Jay Foad4ba2a172011-01-12 09:06:06 +00006118bool Expr::EvaluateAsBooleanCondition(bool &Result,
6119 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006120 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006121 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smithb4e85ed2012-01-06 16:39:00 +00006122 HandleConversionToBool(CCValue(const_cast<ASTContext&>(Ctx),
6123 Scratch.Val, CCValue::GlobalValue()),
Richard Smith47a1eed2011-10-29 20:57:55 +00006124 Result);
John McCallcd7a4452010-01-05 23:42:56 +00006125}
6126
Richard Smith80d4b552011-12-28 19:48:30 +00006127bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6128 SideEffectsKind AllowSideEffects) const {
6129 if (!getType()->isIntegralOrEnumerationType())
6130 return false;
6131
Richard Smithc49bd112011-10-28 17:51:58 +00006132 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006133 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6134 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006135 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006136
Richard Smithc49bd112011-10-28 17:51:58 +00006137 Result = ExprResult.Val.getInt();
6138 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006139}
6140
Jay Foad4ba2a172011-01-12 09:06:06 +00006141bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006142 EvalInfo Info(Ctx, Result);
6143
John McCallefdb83e2010-05-07 21:00:08 +00006144 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006145 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6146 !CheckLValueConstantExpression(Info, getExprLoc(),
6147 Ctx.getLValueReferenceType(getType()), LV))
6148 return false;
6149
6150 CCValue Tmp;
6151 LV.moveInto(Tmp);
6152 Result.Val = Tmp.toAPValue();
6153 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006154}
6155
Richard Smith099e7f62011-12-19 06:19:21 +00006156bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6157 const VarDecl *VD,
6158 llvm::SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006159 // FIXME: Evaluating initializers for large array and record types can cause
6160 // performance problems. Only do so in C++11 for now.
6161 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
6162 !Ctx.getLangOptions().CPlusPlus0x)
6163 return false;
6164
Richard Smith099e7f62011-12-19 06:19:21 +00006165 Expr::EvalStatus EStatus;
6166 EStatus.Diag = &Notes;
6167
6168 EvalInfo InitInfo(Ctx, EStatus);
6169 InitInfo.setEvaluatingDecl(VD, Value);
6170
6171 LValue LVal;
6172 LVal.set(VD);
6173
Richard Smith51201882011-12-30 21:15:51 +00006174 // C++11 [basic.start.init]p2:
6175 // Variables with static storage duration or thread storage duration shall be
6176 // zero-initialized before any other initialization takes place.
6177 // This behavior is not present in C.
6178 if (Ctx.getLangOptions().CPlusPlus && !VD->hasLocalStorage() &&
6179 !VD->getType()->isReferenceType()) {
6180 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006181 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6182 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006183 return false;
6184 }
6185
Richard Smith83587db2012-02-15 02:18:13 +00006186 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6187 /*AllowNonLiteralTypes=*/true) ||
6188 EStatus.HasSideEffects)
6189 return false;
6190
6191 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6192 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006193}
6194
Richard Smith51f47082011-10-29 00:50:52 +00006195/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6196/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006197bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006198 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006199 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006200}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006201
Jay Foad4ba2a172011-01-12 09:06:06 +00006202bool Expr::HasSideEffects(const ASTContext &Ctx) const {
Richard Smith1e12c592011-10-16 21:26:27 +00006203 return HasSideEffect(Ctx).Visit(this);
Fariborz Jahanian393c2472009-11-05 18:03:03 +00006204}
6205
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006206APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006207 EvalResult EvalResult;
Richard Smith51f47082011-10-29 00:50:52 +00006208 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006209 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006210 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006211 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006212
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006213 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006214}
John McCalld905f5a2010-05-07 05:32:02 +00006215
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006216 bool Expr::EvalResult::isGlobalLValue() const {
6217 assert(Val.isLValue());
6218 return IsGlobalLValue(Val.getLValueBase());
6219 }
6220
6221
John McCalld905f5a2010-05-07 05:32:02 +00006222/// isIntegerConstantExpr - this recursive routine will test if an expression is
6223/// an integer constant expression.
6224
6225/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6226/// comma, etc
6227///
6228/// FIXME: Handle offsetof. Two things to do: Handle GCC's __builtin_offsetof
6229/// to support gcc 4.0+ and handle the idiom GCC recognizes with a null pointer
6230/// cast+dereference.
6231
6232// CheckICE - This function does the fundamental ICE checking: the returned
6233// ICEDiag contains a Val of 0, 1, or 2, and a possibly null SourceLocation.
6234// Note that to reduce code duplication, this helper does no evaluation
6235// itself; the caller checks whether the expression is evaluatable, and
6236// in the rare cases where CheckICE actually cares about the evaluated
6237// value, it calls into Evalute.
6238//
6239// Meanings of Val:
Richard Smith51f47082011-10-29 00:50:52 +00006240// 0: This expression is an ICE.
John McCalld905f5a2010-05-07 05:32:02 +00006241// 1: This expression is not an ICE, but if it isn't evaluated, it's
6242// a legal subexpression for an ICE. This return value is used to handle
6243// the comma operator in C99 mode.
6244// 2: This expression is not an ICE, and is not a legal subexpression for one.
6245
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006246namespace {
6247
John McCalld905f5a2010-05-07 05:32:02 +00006248struct ICEDiag {
6249 unsigned Val;
6250 SourceLocation Loc;
6251
6252 public:
6253 ICEDiag(unsigned v, SourceLocation l) : Val(v), Loc(l) {}
6254 ICEDiag() : Val(0) {}
6255};
6256
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006257}
6258
6259static ICEDiag NoDiag() { return ICEDiag(); }
John McCalld905f5a2010-05-07 05:32:02 +00006260
6261static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6262 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006263 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
John McCalld905f5a2010-05-07 05:32:02 +00006264 !EVResult.Val.isInt()) {
6265 return ICEDiag(2, E->getLocStart());
6266 }
6267 return NoDiag();
6268}
6269
6270static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6271 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Douglas Gregor2ade35e2010-06-16 00:17:44 +00006272 if (!E->getType()->isIntegralOrEnumerationType()) {
John McCalld905f5a2010-05-07 05:32:02 +00006273 return ICEDiag(2, E->getLocStart());
6274 }
6275
6276 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006277#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006278#define STMT(Node, Base) case Expr::Node##Class:
6279#define EXPR(Node, Base)
6280#include "clang/AST/StmtNodes.inc"
6281 case Expr::PredefinedExprClass:
6282 case Expr::FloatingLiteralClass:
6283 case Expr::ImaginaryLiteralClass:
6284 case Expr::StringLiteralClass:
6285 case Expr::ArraySubscriptExprClass:
6286 case Expr::MemberExprClass:
6287 case Expr::CompoundAssignOperatorClass:
6288 case Expr::CompoundLiteralExprClass:
6289 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006290 case Expr::DesignatedInitExprClass:
6291 case Expr::ImplicitValueInitExprClass:
6292 case Expr::ParenListExprClass:
6293 case Expr::VAArgExprClass:
6294 case Expr::AddrLabelExprClass:
6295 case Expr::StmtExprClass:
6296 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006297 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006298 case Expr::CXXDynamicCastExprClass:
6299 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006300 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006301 case Expr::CXXNullPtrLiteralExprClass:
6302 case Expr::CXXThisExprClass:
6303 case Expr::CXXThrowExprClass:
6304 case Expr::CXXNewExprClass:
6305 case Expr::CXXDeleteExprClass:
6306 case Expr::CXXPseudoDestructorExprClass:
6307 case Expr::UnresolvedLookupExprClass:
6308 case Expr::DependentScopeDeclRefExprClass:
6309 case Expr::CXXConstructExprClass:
6310 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006311 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006312 case Expr::CXXTemporaryObjectExprClass:
6313 case Expr::CXXUnresolvedConstructExprClass:
6314 case Expr::CXXDependentScopeMemberExprClass:
6315 case Expr::UnresolvedMemberExprClass:
6316 case Expr::ObjCStringLiteralClass:
6317 case Expr::ObjCEncodeExprClass:
6318 case Expr::ObjCMessageExprClass:
6319 case Expr::ObjCSelectorExprClass:
6320 case Expr::ObjCProtocolExprClass:
6321 case Expr::ObjCIvarRefExprClass:
6322 case Expr::ObjCPropertyRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006323 case Expr::ObjCIsaExprClass:
6324 case Expr::ShuffleVectorExprClass:
6325 case Expr::BlockExprClass:
6326 case Expr::BlockDeclRefExprClass:
6327 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006328 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006329 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006330 case Expr::SubstNonTypeTemplateParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006331 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006332 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006333 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006334 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006335 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006336 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006337 case Expr::LambdaExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006338 return ICEDiag(2, E->getLocStart());
6339
Douglas Gregoree8aff02011-01-04 17:33:58 +00006340 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006341 case Expr::GNUNullExprClass:
6342 // GCC considers the GNU __null value to be an integral constant expression.
6343 return NoDiag();
6344
John McCall91a57552011-07-15 05:09:51 +00006345 case Expr::SubstNonTypeTemplateParmExprClass:
6346 return
6347 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6348
John McCalld905f5a2010-05-07 05:32:02 +00006349 case Expr::ParenExprClass:
6350 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006351 case Expr::GenericSelectionExprClass:
6352 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006353 case Expr::IntegerLiteralClass:
6354 case Expr::CharacterLiteralClass:
6355 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006356 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006357 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006358 case Expr::BinaryTypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006359 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006360 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006361 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006362 return NoDiag();
6363 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006364 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006365 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6366 // constant expressions, but they can never be ICEs because an ICE cannot
6367 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006368 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006369 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006370 return CheckEvalInICE(E, Ctx);
6371 return ICEDiag(2, E->getLocStart());
6372 }
6373 case Expr::DeclRefExprClass:
6374 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6375 return NoDiag();
Richard Smith03f96112011-10-24 17:54:18 +00006376 if (Ctx.getLangOptions().CPlusPlus && IsConstNonVolatile(E->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006377 const NamedDecl *D = cast<DeclRefExpr>(E)->getDecl();
6378
6379 // Parameter variables are never constants. Without this check,
6380 // getAnyInitializer() can find a default argument, which leads
6381 // to chaos.
6382 if (isa<ParmVarDecl>(D))
6383 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6384
6385 // C++ 7.1.5.1p2
6386 // A variable of non-volatile const-qualified integral or enumeration
6387 // type initialized by an ICE can be used in ICEs.
6388 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006389 if (!Dcl->getType()->isIntegralOrEnumerationType())
6390 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
6391
Richard Smith099e7f62011-12-19 06:19:21 +00006392 const VarDecl *VD;
6393 // Look for a declaration of this variable that has an initializer, and
6394 // check whether it is an ICE.
6395 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6396 return NoDiag();
6397 else
6398 return ICEDiag(2, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006399 }
6400 }
6401 return ICEDiag(2, E->getLocStart());
6402 case Expr::UnaryOperatorClass: {
6403 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6404 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006405 case UO_PostInc:
6406 case UO_PostDec:
6407 case UO_PreInc:
6408 case UO_PreDec:
6409 case UO_AddrOf:
6410 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006411 // C99 6.6/3 allows increment and decrement within unevaluated
6412 // subexpressions of constant expressions, but they can never be ICEs
6413 // because an ICE cannot contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006414 return ICEDiag(2, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006415 case UO_Extension:
6416 case UO_LNot:
6417 case UO_Plus:
6418 case UO_Minus:
6419 case UO_Not:
6420 case UO_Real:
6421 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006422 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006423 }
6424
6425 // OffsetOf falls through here.
6426 }
6427 case Expr::OffsetOfExprClass: {
6428 // Note that per C99, offsetof must be an ICE. And AFAIK, using
Richard Smith51f47082011-10-29 00:50:52 +00006429 // EvaluateAsRValue matches the proposed gcc behavior for cases like
Richard Smith05830142011-10-24 22:35:48 +00006430 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
John McCalld905f5a2010-05-07 05:32:02 +00006431 // compliance: we should warn earlier for offsetof expressions with
6432 // array subscripts that aren't ICEs, and if the array subscripts
6433 // are ICEs, the value of the offsetof must be an integer constant.
6434 return CheckEvalInICE(E, Ctx);
6435 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006436 case Expr::UnaryExprOrTypeTraitExprClass: {
6437 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6438 if ((Exp->getKind() == UETT_SizeOf) &&
6439 Exp->getTypeOfArgument()->isVariableArrayType())
John McCalld905f5a2010-05-07 05:32:02 +00006440 return ICEDiag(2, E->getLocStart());
6441 return NoDiag();
6442 }
6443 case Expr::BinaryOperatorClass: {
6444 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6445 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006446 case BO_PtrMemD:
6447 case BO_PtrMemI:
6448 case BO_Assign:
6449 case BO_MulAssign:
6450 case BO_DivAssign:
6451 case BO_RemAssign:
6452 case BO_AddAssign:
6453 case BO_SubAssign:
6454 case BO_ShlAssign:
6455 case BO_ShrAssign:
6456 case BO_AndAssign:
6457 case BO_XorAssign:
6458 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006459 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6460 // constant expressions, but they can never be ICEs because an ICE cannot
6461 // contain an lvalue operand.
John McCalld905f5a2010-05-07 05:32:02 +00006462 return ICEDiag(2, E->getLocStart());
6463
John McCall2de56d12010-08-25 11:45:40 +00006464 case BO_Mul:
6465 case BO_Div:
6466 case BO_Rem:
6467 case BO_Add:
6468 case BO_Sub:
6469 case BO_Shl:
6470 case BO_Shr:
6471 case BO_LT:
6472 case BO_GT:
6473 case BO_LE:
6474 case BO_GE:
6475 case BO_EQ:
6476 case BO_NE:
6477 case BO_And:
6478 case BO_Xor:
6479 case BO_Or:
6480 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006481 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6482 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006483 if (Exp->getOpcode() == BO_Div ||
6484 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006485 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006486 // we don't evaluate one.
John McCall3b332ab2011-02-26 08:27:17 +00006487 if (LHSResult.Val == 0 && RHSResult.Val == 0) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006488 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006489 if (REval == 0)
6490 return ICEDiag(1, E->getLocStart());
6491 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006492 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006493 if (LEval.isMinSignedValue())
6494 return ICEDiag(1, E->getLocStart());
6495 }
6496 }
6497 }
John McCall2de56d12010-08-25 11:45:40 +00006498 if (Exp->getOpcode() == BO_Comma) {
John McCalld905f5a2010-05-07 05:32:02 +00006499 if (Ctx.getLangOptions().C99) {
6500 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6501 // if it isn't evaluated.
6502 if (LHSResult.Val == 0 && RHSResult.Val == 0)
6503 return ICEDiag(1, E->getLocStart());
6504 } else {
6505 // In both C89 and C++, commas in ICEs are illegal.
6506 return ICEDiag(2, E->getLocStart());
6507 }
6508 }
6509 if (LHSResult.Val >= RHSResult.Val)
6510 return LHSResult;
6511 return RHSResult;
6512 }
John McCall2de56d12010-08-25 11:45:40 +00006513 case BO_LAnd:
6514 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006515 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6516 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
6517 if (LHSResult.Val == 0 && RHSResult.Val == 1) {
6518 // Rare case where the RHS has a comma "side-effect"; we need
6519 // to actually check the condition to see whether the side
6520 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006521 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006522 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006523 return RHSResult;
6524 return NoDiag();
6525 }
6526
6527 if (LHSResult.Val >= RHSResult.Val)
6528 return LHSResult;
6529 return RHSResult;
6530 }
6531 }
6532 }
6533 case Expr::ImplicitCastExprClass:
6534 case Expr::CStyleCastExprClass:
6535 case Expr::CXXFunctionalCastExprClass:
6536 case Expr::CXXStaticCastExprClass:
6537 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006538 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006539 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006540 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006541 if (isa<ExplicitCastExpr>(E)) {
6542 if (const FloatingLiteral *FL
6543 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6544 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6545 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6546 APSInt IgnoredVal(DestWidth, !DestSigned);
6547 bool Ignored;
6548 // If the value does not fit in the destination type, the behavior is
6549 // undefined, so we are not required to treat it as a constant
6550 // expression.
6551 if (FL->getValue().convertToInteger(IgnoredVal,
6552 llvm::APFloat::rmTowardZero,
6553 &Ignored) & APFloat::opInvalidOp)
6554 return ICEDiag(2, E->getLocStart());
6555 return NoDiag();
6556 }
6557 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006558 switch (cast<CastExpr>(E)->getCastKind()) {
6559 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006560 case CK_AtomicToNonAtomic:
6561 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006562 case CK_NoOp:
6563 case CK_IntegralToBoolean:
6564 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006565 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006566 default:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006567 return ICEDiag(2, E->getLocStart());
6568 }
John McCalld905f5a2010-05-07 05:32:02 +00006569 }
John McCall56ca35d2011-02-17 10:25:35 +00006570 case Expr::BinaryConditionalOperatorClass: {
6571 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6572 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
6573 if (CommonResult.Val == 2) return CommonResult;
6574 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
6575 if (FalseResult.Val == 2) return FalseResult;
6576 if (CommonResult.Val == 1) return CommonResult;
6577 if (FalseResult.Val == 1 &&
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006578 Exp->getCommon()->EvaluateKnownConstInt(Ctx) == 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006579 return FalseResult;
6580 }
John McCalld905f5a2010-05-07 05:32:02 +00006581 case Expr::ConditionalOperatorClass: {
6582 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6583 // If the condition (ignoring parens) is a __builtin_constant_p call,
6584 // then only the true side is actually considered in an integer constant
6585 // expression, and it is fully evaluated. This is an important GNU
6586 // extension. See GCC PR38377 for discussion.
6587 if (const CallExpr *CallCE
6588 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006589 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6590 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006591 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006592 if (CondResult.Val == 2)
6593 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006594
Richard Smithf48fdb02011-12-09 22:58:01 +00006595 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6596 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006597
John McCalld905f5a2010-05-07 05:32:02 +00006598 if (TrueResult.Val == 2)
6599 return TrueResult;
6600 if (FalseResult.Val == 2)
6601 return FalseResult;
6602 if (CondResult.Val == 1)
6603 return CondResult;
6604 if (TrueResult.Val == 0 && FalseResult.Val == 0)
6605 return NoDiag();
6606 // Rare case where the diagnostics depend on which side is evaluated
6607 // Note that if we get here, CondResult is 0, and at least one of
6608 // TrueResult and FalseResult is non-zero.
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006609 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0) {
John McCalld905f5a2010-05-07 05:32:02 +00006610 return FalseResult;
6611 }
6612 return TrueResult;
6613 }
6614 case Expr::CXXDefaultArgExprClass:
6615 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6616 case Expr::ChooseExprClass: {
6617 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6618 }
6619 }
6620
David Blaikie30263482012-01-20 21:50:17 +00006621 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006622}
6623
Richard Smithf48fdb02011-12-09 22:58:01 +00006624/// Evaluate an expression as a C++11 integral constant expression.
6625static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6626 const Expr *E,
6627 llvm::APSInt *Value,
6628 SourceLocation *Loc) {
6629 if (!E->getType()->isIntegralOrEnumerationType()) {
6630 if (Loc) *Loc = E->getExprLoc();
6631 return false;
6632 }
6633
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006634 APValue Result;
6635 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006636 return false;
6637
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006638 assert(Result.isInt() && "pointer cast to int is not an ICE");
6639 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006640 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006641}
6642
Richard Smithdd1f29b2011-12-12 09:28:41 +00006643bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smithf48fdb02011-12-09 22:58:01 +00006644 if (Ctx.getLangOptions().CPlusPlus0x)
6645 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6646
John McCalld905f5a2010-05-07 05:32:02 +00006647 ICEDiag d = CheckICE(this, Ctx);
6648 if (d.Val != 0) {
6649 if (Loc) *Loc = d.Loc;
6650 return false;
6651 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006652 return true;
6653}
6654
6655bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6656 SourceLocation *Loc, bool isEvaluated) const {
6657 if (Ctx.getLangOptions().CPlusPlus0x)
6658 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6659
6660 if (!isIntegerConstantExpr(Ctx, Loc))
6661 return false;
6662 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006663 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006664 return true;
6665}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006666
Richard Smith70488e22012-02-14 21:38:30 +00006667bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
6668 return CheckICE(this, Ctx).Val == 0;
6669}
6670
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006671bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6672 SourceLocation *Loc) const {
6673 // We support this checking in C++98 mode in order to diagnose compatibility
6674 // issues.
6675 assert(Ctx.getLangOptions().CPlusPlus);
6676
Richard Smith70488e22012-02-14 21:38:30 +00006677 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006678 Expr::EvalStatus Status;
6679 llvm::SmallVector<PartialDiagnosticAt, 8> Diags;
6680 Status.Diag = &Diags;
6681 EvalInfo Info(Ctx, Status);
6682
6683 APValue Scratch;
6684 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6685
6686 if (!Diags.empty()) {
6687 IsConstExpr = false;
6688 if (Loc) *Loc = Diags[0].first;
6689 } else if (!IsConstExpr) {
6690 // FIXME: This shouldn't happen.
6691 if (Loc) *Loc = getExprLoc();
6692 }
6693
6694 return IsConstExpr;
6695}
Richard Smith745f5142012-01-27 01:14:48 +00006696
6697bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
6698 llvm::SmallVectorImpl<
6699 PartialDiagnosticAt> &Diags) {
6700 // FIXME: It would be useful to check constexpr function templates, but at the
6701 // moment the constant expression evaluator cannot cope with the non-rigorous
6702 // ASTs which we build for dependent expressions.
6703 if (FD->isDependentContext())
6704 return true;
6705
6706 Expr::EvalStatus Status;
6707 Status.Diag = &Diags;
6708
6709 EvalInfo Info(FD->getASTContext(), Status);
6710 Info.CheckingPotentialConstantExpression = true;
6711
6712 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6713 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6714
6715 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6716 // is a temporary being used as the 'this' pointer.
6717 LValue This;
6718 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006719 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006720
Richard Smith745f5142012-01-27 01:14:48 +00006721 ArrayRef<const Expr*> Args;
6722
6723 SourceLocation Loc = FD->getLocation();
6724
6725 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
Richard Smith83587db2012-02-15 02:18:13 +00006726 APValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006727 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006728 } else {
6729 CCValue Scratch;
Richard Smith745f5142012-01-27 01:14:48 +00006730 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6731 Args, FD->getBody(), Info, Scratch);
Richard Smith83587db2012-02-15 02:18:13 +00006732 }
Richard Smith745f5142012-01-27 01:14:48 +00006733
6734 return Diags.empty();
6735}