blob: d7abe3082e58052b77d06655cc17ef666cd6759c [file] [log] [blame]
Chris Lattnerb542afe2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlssonc44eec62008-07-03 04:20:39 +00002//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Expr constant evaluator.
11//
Richard Smith745f5142012-01-27 01:14:48 +000012// Constant expression evaluation produces four main results:
13//
14// * A success/failure flag indicating whether constant folding was successful.
15// This is the 'bool' return value used by most of the code in this file. A
16// 'false' return value indicates that constant folding has failed, and any
17// appropriate diagnostic has already been produced.
18//
19// * An evaluated result, valid only if constant folding has not failed.
20//
21// * A flag indicating if evaluation encountered (unevaluated) side-effects.
22// These arise in cases such as (sideEffect(), 0) and (sideEffect() || 1),
23// where it is possible to determine the evaluated result regardless.
24//
25// * A set of notes indicating why the evaluation was not a constant expression
26// (under the C++11 rules only, at the moment), or, if folding failed too,
27// why the expression could not be folded.
28//
29// If we are checking for a potential constant expression, failure to constant
30// fold a potential constant sub-expression will be indicated by a 'false'
31// return value (the expression could not be folded) and no diagnostic (the
32// expression is not necessarily non-constant).
33//
Anders Carlssonc44eec62008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck199c3d62010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson19cc4ab2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon0fe52e12008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor8ecdb652010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner1b63e4f2009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson06a36752008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stump7462b392009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Benjamin Kramera93d0f22012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump4572bab2009-05-30 03:56:50 +000048#include <cstring>
Richard Smith7b48a292012-02-01 05:53:12 +000049#include <functional>
Mike Stump4572bab2009-05-30 03:56:50 +000050
Anders Carlssonc44eec62008-07-03 04:20:39 +000051using namespace clang;
Chris Lattnerf5eeb052008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlssonc44eec62008-07-03 04:20:39 +000054
Richard Smith83587db2012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCallf4cf1a12010-05-07 17:22:02 +000057namespace {
Richard Smith180f4792011-11-10 06:34:14 +000058 struct LValue;
Richard Smithd0dccea2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smithbd552ef2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smithd0dccea2011-10-28 22:34:42 +000061
Richard Smith83587db2012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
65 return D->getType();
66 return B.get<const Expr*>()->getType();
67 }
68
Richard Smith180f4792011-11-10 06:34:14 +000069 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smithf15fda02012-02-02 01:16:57 +000070 /// field or base class.
Richard Smith83587db2012-02-15 02:18:13 +000071 static
Richard Smithf15fda02012-02-02 01:16:57 +000072 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smith180f4792011-11-10 06:34:14 +000073 APValue::BaseOrMemberType Value;
74 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smithf15fda02012-02-02 01:16:57 +000075 return Value;
76 }
77
78 /// Get an LValue path entry, which is known to not be an array index, as a
79 /// field declaration.
Richard Smith83587db2012-02-15 02:18:13 +000080 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000081 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000082 }
83 /// Get an LValue path entry, which is known to not be an array index, as a
84 /// base class declaration.
Richard Smith83587db2012-02-15 02:18:13 +000085 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000086 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smith180f4792011-11-10 06:34:14 +000087 }
88 /// Determine whether this LValue path entry for a base class names a virtual
89 /// base class.
Richard Smith83587db2012-02-15 02:18:13 +000090 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smithf15fda02012-02-02 01:16:57 +000091 return getAsBaseOrMember(E).getInt();
Richard Smith180f4792011-11-10 06:34:14 +000092 }
93
Richard Smithb4e85ed2012-01-06 16:39:00 +000094 /// Find the path length and type of the most-derived subobject in the given
95 /// path, and find the size of the containing array, if any.
96 static
97 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
98 ArrayRef<APValue::LValuePathEntry> Path,
99 uint64_t &ArraySize, QualType &Type) {
100 unsigned MostDerivedLength = 0;
101 Type = Base;
Richard Smith9a17a682011-11-07 05:07:52 +0000102 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000103 if (Type->isArrayType()) {
104 const ConstantArrayType *CAT =
105 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
106 Type = CAT->getElementType();
107 ArraySize = CAT->getSize().getZExtValue();
108 MostDerivedLength = I + 1;
Richard Smith86024012012-02-18 22:04:06 +0000109 } else if (Type->isAnyComplexType()) {
110 const ComplexType *CT = Type->castAs<ComplexType>();
111 Type = CT->getElementType();
112 ArraySize = 2;
113 MostDerivedLength = I + 1;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000114 } else if (const FieldDecl *FD = getAsField(Path[I])) {
115 Type = FD->getType();
116 ArraySize = 0;
117 MostDerivedLength = I + 1;
118 } else {
Richard Smith9a17a682011-11-07 05:07:52 +0000119 // Path[I] describes a base class.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000120 ArraySize = 0;
121 }
Richard Smith9a17a682011-11-07 05:07:52 +0000122 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000123 return MostDerivedLength;
Richard Smith9a17a682011-11-07 05:07:52 +0000124 }
125
Richard Smithb4e85ed2012-01-06 16:39:00 +0000126 // The order of this enum is important for diagnostics.
127 enum CheckSubobjectKind {
Richard Smithb04035a2012-02-01 02:39:43 +0000128 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith86024012012-02-18 22:04:06 +0000129 CSK_This, CSK_Real, CSK_Imag
Richard Smithb4e85ed2012-01-06 16:39:00 +0000130 };
131
Richard Smith0a3bdb62011-11-04 02:25:55 +0000132 /// A path from a glvalue to a subobject of that glvalue.
133 struct SubobjectDesignator {
134 /// True if the subobject was named in a manner not supported by C++11. Such
135 /// lvalues can still be folded, but they are not core constant expressions
136 /// and we cannot perform lvalue-to-rvalue conversions on them.
137 bool Invalid : 1;
138
Richard Smithb4e85ed2012-01-06 16:39:00 +0000139 /// Is this a pointer one past the end of an object?
140 bool IsOnePastTheEnd : 1;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000141
Richard Smithb4e85ed2012-01-06 16:39:00 +0000142 /// The length of the path to the most-derived object of which this is a
143 /// subobject.
144 unsigned MostDerivedPathLength : 30;
145
146 /// The size of the array of which the most-derived object is an element, or
147 /// 0 if the most-derived object is not an array element.
148 uint64_t MostDerivedArraySize;
149
150 /// The type of the most derived object referred to by this address.
151 QualType MostDerivedType;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000152
Richard Smith9a17a682011-11-07 05:07:52 +0000153 typedef APValue::LValuePathEntry PathEntry;
154
Richard Smith0a3bdb62011-11-04 02:25:55 +0000155 /// The entries on the path from the glvalue to the designated subobject.
156 SmallVector<PathEntry, 8> Entries;
157
Richard Smithb4e85ed2012-01-06 16:39:00 +0000158 SubobjectDesignator() : Invalid(true) {}
Richard Smith0a3bdb62011-11-04 02:25:55 +0000159
Richard Smithb4e85ed2012-01-06 16:39:00 +0000160 explicit SubobjectDesignator(QualType T)
161 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
162 MostDerivedArraySize(0), MostDerivedType(T) {}
163
164 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
165 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
166 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith9a17a682011-11-07 05:07:52 +0000167 if (!Invalid) {
Richard Smithb4e85ed2012-01-06 16:39:00 +0000168 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith9a17a682011-11-07 05:07:52 +0000169 ArrayRef<PathEntry> VEntries = V.getLValuePath();
170 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
171 if (V.getLValueBase())
Richard Smithb4e85ed2012-01-06 16:39:00 +0000172 MostDerivedPathLength =
173 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174 V.getLValuePath(), MostDerivedArraySize,
175 MostDerivedType);
Richard Smith9a17a682011-11-07 05:07:52 +0000176 }
177 }
178
Richard Smith0a3bdb62011-11-04 02:25:55 +0000179 void setInvalid() {
180 Invalid = true;
181 Entries.clear();
182 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000183
184 /// Determine whether this is a one-past-the-end pointer.
185 bool isOnePastTheEnd() const {
186 if (IsOnePastTheEnd)
187 return true;
188 if (MostDerivedArraySize &&
189 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
190 return true;
191 return false;
192 }
193
194 /// Check that this refers to a valid subobject.
195 bool isValidSubobject() const {
196 if (Invalid)
197 return false;
198 return !isOnePastTheEnd();
199 }
200 /// Check that this refers to a valid subobject, and if not, produce a
201 /// relevant diagnostic and set the designator as invalid.
202 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
203
204 /// Update this designator to refer to the first element within this array.
205 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000206 PathEntry Entry;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000207 Entry.ArrayIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000208 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000209
210 // This is a most-derived object.
211 MostDerivedType = CAT->getElementType();
212 MostDerivedArraySize = CAT->getSize().getZExtValue();
213 MostDerivedPathLength = Entries.size();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000214 }
215 /// Update this designator to refer to the given base or member of this
216 /// object.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000217 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000218 PathEntry Entry;
Richard Smith180f4792011-11-10 06:34:14 +0000219 APValue::BaseOrMemberType Value(D, Virtual);
220 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith0a3bdb62011-11-04 02:25:55 +0000221 Entries.push_back(Entry);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000222
223 // If this isn't a base class, it's a new most-derived object.
224 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
225 MostDerivedType = FD->getType();
226 MostDerivedArraySize = 0;
227 MostDerivedPathLength = Entries.size();
228 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000229 }
Richard Smith86024012012-02-18 22:04:06 +0000230 /// Update this designator to refer to the given complex component.
231 void addComplexUnchecked(QualType EltTy, bool Imag) {
232 PathEntry Entry;
233 Entry.ArrayIndex = Imag;
234 Entries.push_back(Entry);
235
236 // This is technically a most-derived object, though in practice this
237 // is unlikely to matter.
238 MostDerivedType = EltTy;
239 MostDerivedArraySize = 2;
240 MostDerivedPathLength = Entries.size();
241 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000242 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000243 /// Add N to the address of this subobject.
Richard Smithb4e85ed2012-01-06 16:39:00 +0000244 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith0a3bdb62011-11-04 02:25:55 +0000245 if (Invalid) return;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000246 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith9a17a682011-11-07 05:07:52 +0000247 Entries.back().ArrayIndex += N;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000248 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
250 setInvalid();
251 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000252 return;
253 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000254 // [expr.add]p4: For the purposes of these operators, a pointer to a
255 // nonarray object behaves the same as a pointer to the first element of
256 // an array of length one with the type of the object as its element type.
257 if (IsOnePastTheEnd && N == (uint64_t)-1)
258 IsOnePastTheEnd = false;
259 else if (!IsOnePastTheEnd && N == 1)
260 IsOnePastTheEnd = true;
261 else if (N != 0) {
262 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000263 setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000264 }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000265 }
266 };
267
Richard Smithd0dccea2011-10-28 22:34:42 +0000268 /// A stack frame in the constexpr call stack.
269 struct CallStackFrame {
270 EvalInfo &Info;
271
272 /// Parent - The caller of this stack frame.
Richard Smithbd552ef2011-10-31 05:52:43 +0000273 CallStackFrame *Caller;
Richard Smithd0dccea2011-10-28 22:34:42 +0000274
Richard Smith08d6e032011-12-16 19:06:07 +0000275 /// CallLoc - The location of the call expression for this call.
276 SourceLocation CallLoc;
277
278 /// Callee - The function which was called.
279 const FunctionDecl *Callee;
280
Richard Smith83587db2012-02-15 02:18:13 +0000281 /// Index - The call index of this call.
282 unsigned Index;
283
Richard Smith180f4792011-11-10 06:34:14 +0000284 /// This - The binding for the this pointer in this call, if any.
285 const LValue *This;
286
Richard Smithd0dccea2011-10-28 22:34:42 +0000287 /// ParmBindings - Parameter bindings for this function call, indexed by
288 /// parameters' function scope indices.
Richard Smith1aa0be82012-03-03 22:46:17 +0000289 const APValue *Arguments;
Richard Smithd0dccea2011-10-28 22:34:42 +0000290
Eli Friedmanf6172ae2012-06-25 21:21:08 +0000291 // Note that we intentionally use std::map here so that references to
292 // values are stable.
293 typedef std::map<const Expr*, APValue> MapTy;
Richard Smithbd552ef2011-10-31 05:52:43 +0000294 typedef MapTy::const_iterator temp_iterator;
295 /// Temporaries - Temporary lvalues materialized within this stack frame.
296 MapTy Temporaries;
297
Richard Smith08d6e032011-12-16 19:06:07 +0000298 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
299 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000300 const APValue *Arguments);
Richard Smithbd552ef2011-10-31 05:52:43 +0000301 ~CallStackFrame();
Richard Smithd0dccea2011-10-28 22:34:42 +0000302 };
303
Richard Smithdd1f29b2011-12-12 09:28:41 +0000304 /// A partial diagnostic which we might know in advance that we are not going
305 /// to emit.
306 class OptionalDiagnostic {
307 PartialDiagnostic *Diag;
308
309 public:
310 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
311
312 template<typename T>
313 OptionalDiagnostic &operator<<(const T &v) {
314 if (Diag)
315 *Diag << v;
316 return *this;
317 }
Richard Smith789f9b62012-01-31 04:08:20 +0000318
319 OptionalDiagnostic &operator<<(const APSInt &I) {
320 if (Diag) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000321 SmallVector<char, 32> Buffer;
Richard Smith789f9b62012-01-31 04:08:20 +0000322 I.toString(Buffer);
323 *Diag << StringRef(Buffer.data(), Buffer.size());
324 }
325 return *this;
326 }
327
328 OptionalDiagnostic &operator<<(const APFloat &F) {
329 if (Diag) {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000330 SmallVector<char, 32> Buffer;
Richard Smith789f9b62012-01-31 04:08:20 +0000331 F.toString(Buffer);
332 *Diag << StringRef(Buffer.data(), Buffer.size());
333 }
334 return *this;
335 }
Richard Smithdd1f29b2011-12-12 09:28:41 +0000336 };
337
Richard Smith83587db2012-02-15 02:18:13 +0000338 /// EvalInfo - This is a private struct used by the evaluator to capture
339 /// information about a subexpression as it is folded. It retains information
340 /// about the AST context, but also maintains information about the folded
341 /// expression.
342 ///
343 /// If an expression could be evaluated, it is still possible it is not a C
344 /// "integer constant expression" or constant expression. If not, this struct
345 /// captures information about how and why not.
346 ///
347 /// One bit of information passed *into* the request for constant folding
348 /// indicates whether the subexpression is "evaluated" or not according to C
349 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
350 /// evaluate the expression regardless of what the RHS is, but C only allows
351 /// certain things in certain situations.
Richard Smithbd552ef2011-10-31 05:52:43 +0000352 struct EvalInfo {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000353 ASTContext &Ctx;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +0000354
Richard Smithbd552ef2011-10-31 05:52:43 +0000355 /// EvalStatus - Contains information about the evaluation.
356 Expr::EvalStatus &EvalStatus;
357
358 /// CurrentCall - The top of the constexpr call stack.
359 CallStackFrame *CurrentCall;
360
Richard Smithbd552ef2011-10-31 05:52:43 +0000361 /// CallStackDepth - The number of calls in the call stack right now.
362 unsigned CallStackDepth;
363
Richard Smith83587db2012-02-15 02:18:13 +0000364 /// NextCallIndex - The next call index to assign.
365 unsigned NextCallIndex;
366
Richard Smithbd552ef2011-10-31 05:52:43 +0000367 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith745f5142012-01-27 01:14:48 +0000368 /// initialized after CurrentCall and CallStackDepth.
Richard Smithbd552ef2011-10-31 05:52:43 +0000369 CallStackFrame BottomFrame;
370
Richard Smith180f4792011-11-10 06:34:14 +0000371 /// EvaluatingDecl - This is the declaration whose initializer is being
372 /// evaluated, if any.
373 const VarDecl *EvaluatingDecl;
374
375 /// EvaluatingDeclValue - This is the value being constructed for the
376 /// declaration whose initializer is being evaluated, if any.
377 APValue *EvaluatingDeclValue;
378
Richard Smithc1c5f272011-12-13 06:39:58 +0000379 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
380 /// notes attached to it will also be stored, otherwise they will not be.
381 bool HasActiveDiagnostic;
382
Richard Smith745f5142012-01-27 01:14:48 +0000383 /// CheckingPotentialConstantExpression - Are we checking whether the
384 /// expression is a potential constant expression? If so, some diagnostics
385 /// are suppressed.
386 bool CheckingPotentialConstantExpression;
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000387
388 bool IntOverflowCheckMode;
Richard Smith745f5142012-01-27 01:14:48 +0000389
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000390 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
391 bool OverflowCheckMode=false)
Richard Smithdd1f29b2011-12-12 09:28:41 +0000392 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smith83587db2012-02-15 02:18:13 +0000393 CallStackDepth(0), NextCallIndex(1),
394 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith745f5142012-01-27 01:14:48 +0000395 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000396 CheckingPotentialConstantExpression(false),
397 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smithbd552ef2011-10-31 05:52:43 +0000398
Richard Smith180f4792011-11-10 06:34:14 +0000399 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
400 EvaluatingDecl = VD;
401 EvaluatingDeclValue = &Value;
402 }
403
David Blaikie4e4d0842012-03-11 07:00:24 +0000404 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smithc18c4232011-11-21 19:36:32 +0000405
Richard Smithc1c5f272011-12-13 06:39:58 +0000406 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith745f5142012-01-27 01:14:48 +0000407 // Don't perform any constexpr calls (other than the call we're checking)
408 // when checking a potential constant expression.
409 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
410 return false;
Richard Smith83587db2012-02-15 02:18:13 +0000411 if (NextCallIndex == 0) {
412 // NextCallIndex has wrapped around.
413 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
414 return false;
415 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000416 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
417 return true;
418 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
419 << getLangOpts().ConstexprCallDepth;
420 return false;
Richard Smithc18c4232011-11-21 19:36:32 +0000421 }
Richard Smithf48fdb02011-12-09 22:58:01 +0000422
Richard Smith83587db2012-02-15 02:18:13 +0000423 CallStackFrame *getCallFrame(unsigned CallIndex) {
424 assert(CallIndex && "no call index in getCallFrame");
425 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
426 // be null in this loop.
427 CallStackFrame *Frame = CurrentCall;
428 while (Frame->Index > CallIndex)
429 Frame = Frame->Caller;
430 return (Frame->Index == CallIndex) ? Frame : 0;
431 }
432
Richard Smithc1c5f272011-12-13 06:39:58 +0000433 private:
434 /// Add a diagnostic to the diagnostics list.
435 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
436 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
437 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
438 return EvalStatus.Diag->back().second;
439 }
440
Richard Smith08d6e032011-12-16 19:06:07 +0000441 /// Add notes containing a call stack to the current point of evaluation.
442 void addCallStack(unsigned Limit);
443
Richard Smithc1c5f272011-12-13 06:39:58 +0000444 public:
Richard Smithf48fdb02011-12-09 22:58:01 +0000445 /// Diagnose that the evaluation cannot be folded.
Richard Smith7098cbd2011-12-21 05:04:46 +0000446 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
447 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000448 unsigned ExtraNotes = 0) {
Richard Smithf48fdb02011-12-09 22:58:01 +0000449 // If we have a prior diagnostic, it will be noting that the expression
450 // isn't a constant expression. This diagnostic is more important.
451 // FIXME: We might want to show both diagnostics to the user.
Richard Smithdd1f29b2011-12-12 09:28:41 +0000452 if (EvalStatus.Diag) {
Richard Smith08d6e032011-12-16 19:06:07 +0000453 unsigned CallStackNotes = CallStackDepth - 1;
454 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
455 if (Limit)
456 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith745f5142012-01-27 01:14:48 +0000457 if (CheckingPotentialConstantExpression)
458 CallStackNotes = 0;
Richard Smith08d6e032011-12-16 19:06:07 +0000459
Richard Smithc1c5f272011-12-13 06:39:58 +0000460 HasActiveDiagnostic = true;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000461 EvalStatus.Diag->clear();
Richard Smith08d6e032011-12-16 19:06:07 +0000462 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
463 addDiag(Loc, DiagId);
Richard Smith745f5142012-01-27 01:14:48 +0000464 if (!CheckingPotentialConstantExpression)
465 addCallStack(Limit);
Richard Smith08d6e032011-12-16 19:06:07 +0000466 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smithdd1f29b2011-12-12 09:28:41 +0000467 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000468 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000469 return OptionalDiagnostic();
470 }
471
Richard Smith5cfc7d82012-03-15 04:53:45 +0000472 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
473 = diag::note_invalid_subexpr_in_const_expr,
474 unsigned ExtraNotes = 0) {
475 if (EvalStatus.Diag)
476 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
477 HasActiveDiagnostic = false;
478 return OptionalDiagnostic();
479 }
480
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000481 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
482
Richard Smithdd1f29b2011-12-12 09:28:41 +0000483 /// Diagnose that the evaluation does not produce a C++11 core constant
484 /// expression.
Richard Smith5cfc7d82012-03-15 04:53:45 +0000485 template<typename LocArg>
486 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smith7098cbd2011-12-21 05:04:46 +0000487 = diag::note_invalid_subexpr_in_const_expr,
Richard Smithc1c5f272011-12-13 06:39:58 +0000488 unsigned ExtraNotes = 0) {
Richard Smithdd1f29b2011-12-12 09:28:41 +0000489 // Don't override a previous diagnostic.
Eli Friedman51e47df2012-02-21 22:41:33 +0000490 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
491 HasActiveDiagnostic = false;
Richard Smithdd1f29b2011-12-12 09:28:41 +0000492 return OptionalDiagnostic();
Eli Friedman51e47df2012-02-21 22:41:33 +0000493 }
Richard Smithc1c5f272011-12-13 06:39:58 +0000494 return Diag(Loc, DiagId, ExtraNotes);
495 }
496
497 /// Add a note to a prior diagnostic.
498 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
499 if (!HasActiveDiagnostic)
500 return OptionalDiagnostic();
501 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf48fdb02011-12-09 22:58:01 +0000502 }
Richard Smith099e7f62011-12-19 06:19:21 +0000503
504 /// Add a stack of notes to a prior diagnostic.
505 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
506 if (HasActiveDiagnostic) {
507 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
508 Diags.begin(), Diags.end());
509 }
510 }
Richard Smith745f5142012-01-27 01:14:48 +0000511
512 /// Should we continue evaluation as much as possible after encountering a
513 /// construct which can't be folded?
514 bool keepEvaluatingAfterFailure() {
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000515 // Should return true in IntOverflowCheckMode, so that we check for
516 // overflow even if some subexpressions can't be evaluated as constants.
Fariborz Jahanianad48a502013-01-24 22:11:45 +0000517 return IntOverflowCheckMode ||
518 (CheckingPotentialConstantExpression &&
519 EvalStatus.Diag && EvalStatus.Diag->empty());
Richard Smith745f5142012-01-27 01:14:48 +0000520 }
Richard Smithbd552ef2011-10-31 05:52:43 +0000521 };
Richard Smithf15fda02012-02-02 01:16:57 +0000522
523 /// Object used to treat all foldable expressions as constant expressions.
524 struct FoldConstant {
525 bool Enabled;
526
527 explicit FoldConstant(EvalInfo &Info)
528 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
529 !Info.EvalStatus.HasSideEffects) {
530 }
531 // Treat the value we've computed since this object was created as constant.
532 void Fold(EvalInfo &Info) {
533 if (Enabled && !Info.EvalStatus.Diag->empty() &&
534 !Info.EvalStatus.HasSideEffects)
535 Info.EvalStatus.Diag->clear();
536 }
537 };
Richard Smith74e1ad92012-02-16 02:46:34 +0000538
539 /// RAII object used to suppress diagnostics and side-effects from a
540 /// speculative evaluation.
541 class SpeculativeEvaluationRAII {
542 EvalInfo &Info;
543 Expr::EvalStatus Old;
544
545 public:
546 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000547 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith74e1ad92012-02-16 02:46:34 +0000548 : Info(Info), Old(Info.EvalStatus) {
549 Info.EvalStatus.Diag = NewDiag;
550 }
551 ~SpeculativeEvaluationRAII() {
552 Info.EvalStatus = Old;
553 }
554 };
Richard Smith08d6e032011-12-16 19:06:07 +0000555}
Richard Smithbd552ef2011-10-31 05:52:43 +0000556
Richard Smithb4e85ed2012-01-06 16:39:00 +0000557bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
558 CheckSubobjectKind CSK) {
559 if (Invalid)
560 return false;
561 if (isOnePastTheEnd()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000562 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000563 << CSK;
564 setInvalid();
565 return false;
566 }
567 return true;
568}
569
570void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
571 const Expr *E, uint64_t N) {
572 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000573 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000574 << static_cast<int>(N) << /*array*/ 0
575 << static_cast<unsigned>(MostDerivedArraySize);
576 else
Richard Smith5cfc7d82012-03-15 04:53:45 +0000577 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000578 << static_cast<int>(N) << /*non-array*/ 1;
579 setInvalid();
580}
581
Richard Smith08d6e032011-12-16 19:06:07 +0000582CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
583 const FunctionDecl *Callee, const LValue *This,
Richard Smith1aa0be82012-03-03 22:46:17 +0000584 const APValue *Arguments)
Richard Smith08d6e032011-12-16 19:06:07 +0000585 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smith83587db2012-02-15 02:18:13 +0000586 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smith08d6e032011-12-16 19:06:07 +0000587 Info.CurrentCall = this;
588 ++Info.CallStackDepth;
589}
590
591CallStackFrame::~CallStackFrame() {
592 assert(Info.CurrentCall == this && "calls retired out of order");
593 --Info.CallStackDepth;
594 Info.CurrentCall = Caller;
595}
596
597/// Produce a string describing the given constexpr call.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000598static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
Richard Smith08d6e032011-12-16 19:06:07 +0000599 unsigned ArgIndex = 0;
600 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith5ba73e12012-02-04 00:33:54 +0000601 !isa<CXXConstructorDecl>(Frame->Callee) &&
602 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smith08d6e032011-12-16 19:06:07 +0000603
604 if (!IsMemberCall)
605 Out << *Frame->Callee << '(';
606
607 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
608 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumi5fe31222012-01-26 09:37:36 +0000609 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smith08d6e032011-12-16 19:06:07 +0000610 Out << ", ";
611
612 const ParmVarDecl *Param = *I;
Richard Smith1aa0be82012-03-03 22:46:17 +0000613 const APValue &Arg = Frame->Arguments[ArgIndex];
614 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smith08d6e032011-12-16 19:06:07 +0000615
616 if (ArgIndex == 0 && IsMemberCall)
617 Out << "->" << *Frame->Callee << '(';
Richard Smithbd552ef2011-10-31 05:52:43 +0000618 }
619
Richard Smith08d6e032011-12-16 19:06:07 +0000620 Out << ')';
621}
622
623void EvalInfo::addCallStack(unsigned Limit) {
624 // Determine which calls to skip, if any.
625 unsigned ActiveCalls = CallStackDepth - 1;
626 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
627 if (Limit && Limit < ActiveCalls) {
628 SkipStart = Limit / 2 + Limit % 2;
629 SkipEnd = ActiveCalls - Limit / 2;
Richard Smithbd552ef2011-10-31 05:52:43 +0000630 }
631
Richard Smith08d6e032011-12-16 19:06:07 +0000632 // Walk the call stack and add the diagnostics.
633 unsigned CallIdx = 0;
634 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
635 Frame = Frame->Caller, ++CallIdx) {
636 // Skip this call?
637 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
638 if (CallIdx == SkipStart) {
639 // Note that we're skipping calls.
640 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
641 << unsigned(ActiveCalls - Limit);
642 }
643 continue;
644 }
645
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000646 SmallVector<char, 128> Buffer;
Richard Smith08d6e032011-12-16 19:06:07 +0000647 llvm::raw_svector_ostream Out(Buffer);
648 describeCall(Frame, Out);
649 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
650 }
651}
652
653namespace {
John McCallf4cf1a12010-05-07 17:22:02 +0000654 struct ComplexValue {
655 private:
656 bool IsInt;
657
658 public:
659 APSInt IntReal, IntImag;
660 APFloat FloatReal, FloatImag;
661
662 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
663
664 void makeComplexFloat() { IsInt = false; }
665 bool isComplexFloat() const { return !IsInt; }
666 APFloat &getComplexFloatReal() { return FloatReal; }
667 APFloat &getComplexFloatImag() { return FloatImag; }
668
669 void makeComplexInt() { IsInt = true; }
670 bool isComplexInt() const { return IsInt; }
671 APSInt &getComplexIntReal() { return IntReal; }
672 APSInt &getComplexIntImag() { return IntImag; }
673
Richard Smith1aa0be82012-03-03 22:46:17 +0000674 void moveInto(APValue &v) const {
John McCallf4cf1a12010-05-07 17:22:02 +0000675 if (isComplexFloat())
Richard Smith1aa0be82012-03-03 22:46:17 +0000676 v = APValue(FloatReal, FloatImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000677 else
Richard Smith1aa0be82012-03-03 22:46:17 +0000678 v = APValue(IntReal, IntImag);
John McCallf4cf1a12010-05-07 17:22:02 +0000679 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000680 void setFrom(const APValue &v) {
John McCall56ca35d2011-02-17 10:25:35 +0000681 assert(v.isComplexFloat() || v.isComplexInt());
682 if (v.isComplexFloat()) {
683 makeComplexFloat();
684 FloatReal = v.getComplexFloatReal();
685 FloatImag = v.getComplexFloatImag();
686 } else {
687 makeComplexInt();
688 IntReal = v.getComplexIntReal();
689 IntImag = v.getComplexIntImag();
690 }
691 }
John McCallf4cf1a12010-05-07 17:22:02 +0000692 };
John McCallefdb83e2010-05-07 21:00:08 +0000693
694 struct LValue {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000695 APValue::LValueBase Base;
John McCallefdb83e2010-05-07 21:00:08 +0000696 CharUnits Offset;
Richard Smith83587db2012-02-15 02:18:13 +0000697 unsigned CallIndex;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000698 SubobjectDesignator Designator;
John McCallefdb83e2010-05-07 21:00:08 +0000699
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000700 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith47a1eed2011-10-29 20:57:55 +0000701 CharUnits &getLValueOffset() { return Offset; }
Richard Smith625b8072011-10-31 01:37:14 +0000702 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smith83587db2012-02-15 02:18:13 +0000703 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith0a3bdb62011-11-04 02:25:55 +0000704 SubobjectDesignator &getLValueDesignator() { return Designator; }
705 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCallefdb83e2010-05-07 21:00:08 +0000706
Richard Smith1aa0be82012-03-03 22:46:17 +0000707 void moveInto(APValue &V) const {
708 if (Designator.Invalid)
709 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
710 else
711 V = APValue(Base, Offset, Designator.Entries,
712 Designator.IsOnePastTheEnd, CallIndex);
John McCallefdb83e2010-05-07 21:00:08 +0000713 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000714 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith47a1eed2011-10-29 20:57:55 +0000715 assert(V.isLValue());
716 Base = V.getLValueBase();
717 Offset = V.getLValueOffset();
Richard Smith83587db2012-02-15 02:18:13 +0000718 CallIndex = V.getLValueCallIndex();
Richard Smith1aa0be82012-03-03 22:46:17 +0000719 Designator = SubobjectDesignator(Ctx, V);
Richard Smith0a3bdb62011-11-04 02:25:55 +0000720 }
721
Richard Smith83587db2012-02-15 02:18:13 +0000722 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000723 Base = B;
Richard Smith0a3bdb62011-11-04 02:25:55 +0000724 Offset = CharUnits::Zero();
Richard Smith83587db2012-02-15 02:18:13 +0000725 CallIndex = I;
Richard Smithb4e85ed2012-01-06 16:39:00 +0000726 Designator = SubobjectDesignator(getType(B));
727 }
728
729 // Check that this LValue is not based on a null pointer. If it is, produce
730 // a diagnostic and mark the designator as invalid.
731 bool checkNullPointer(EvalInfo &Info, const Expr *E,
732 CheckSubobjectKind CSK) {
733 if (Designator.Invalid)
734 return false;
735 if (!Base) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000736 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smithb4e85ed2012-01-06 16:39:00 +0000737 << CSK;
738 Designator.setInvalid();
739 return false;
740 }
741 return true;
742 }
743
744 // Check this LValue refers to an object. If not, set the designator to be
745 // invalid and emit a diagnostic.
746 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000747 // Outside C++11, do not build a designator referring to a subobject of
748 // any object: we won't use such a designator for anything.
Richard Smith80ad52f2013-01-02 11:42:31 +0000749 if (!Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +0000750 Designator.setInvalid();
Richard Smithb4e85ed2012-01-06 16:39:00 +0000751 return checkNullPointer(Info, E, CSK) &&
752 Designator.checkSubobject(Info, E, CSK);
753 }
754
755 void addDecl(EvalInfo &Info, const Expr *E,
756 const Decl *D, bool Virtual = false) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000757 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
758 Designator.addDeclUnchecked(D, Virtual);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000759 }
760 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000761 if (checkSubobject(Info, E, CSK_ArrayToPointer))
762 Designator.addArrayUnchecked(CAT);
Richard Smithb4e85ed2012-01-06 16:39:00 +0000763 }
Richard Smith86024012012-02-18 22:04:06 +0000764 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000765 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
766 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith86024012012-02-18 22:04:06 +0000767 }
Richard Smithb4e85ed2012-01-06 16:39:00 +0000768 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith5cfc7d82012-03-15 04:53:45 +0000769 if (checkNullPointer(Info, E, CSK_ArrayIndex))
770 Designator.adjustIndex(Info, E, N);
John McCall56ca35d2011-02-17 10:25:35 +0000771 }
John McCallefdb83e2010-05-07 21:00:08 +0000772 };
Richard Smithe24f5fc2011-11-17 22:56:20 +0000773
774 struct MemberPtr {
775 MemberPtr() {}
776 explicit MemberPtr(const ValueDecl *Decl) :
777 DeclAndIsDerivedMember(Decl, false), Path() {}
778
779 /// The member or (direct or indirect) field referred to by this member
780 /// pointer, or 0 if this is a null member pointer.
781 const ValueDecl *getDecl() const {
782 return DeclAndIsDerivedMember.getPointer();
783 }
784 /// Is this actually a member of some type derived from the relevant class?
785 bool isDerivedMember() const {
786 return DeclAndIsDerivedMember.getInt();
787 }
788 /// Get the class which the declaration actually lives in.
789 const CXXRecordDecl *getContainingRecord() const {
790 return cast<CXXRecordDecl>(
791 DeclAndIsDerivedMember.getPointer()->getDeclContext());
792 }
793
Richard Smith1aa0be82012-03-03 22:46:17 +0000794 void moveInto(APValue &V) const {
795 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000796 }
Richard Smith1aa0be82012-03-03 22:46:17 +0000797 void setFrom(const APValue &V) {
Richard Smithe24f5fc2011-11-17 22:56:20 +0000798 assert(V.isMemberPointer());
799 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
800 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
801 Path.clear();
802 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
803 Path.insert(Path.end(), P.begin(), P.end());
804 }
805
806 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
807 /// whether the member is a member of some class derived from the class type
808 /// of the member pointer.
809 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
810 /// Path - The path of base/derived classes from the member declaration's
811 /// class (exclusive) to the class type of the member pointer (inclusive).
812 SmallVector<const CXXRecordDecl*, 4> Path;
813
814 /// Perform a cast towards the class of the Decl (either up or down the
815 /// hierarchy).
816 bool castBack(const CXXRecordDecl *Class) {
817 assert(!Path.empty());
818 const CXXRecordDecl *Expected;
819 if (Path.size() >= 2)
820 Expected = Path[Path.size() - 2];
821 else
822 Expected = getContainingRecord();
823 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
824 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
825 // if B does not contain the original member and is not a base or
826 // derived class of the class containing the original member, the result
827 // of the cast is undefined.
828 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
829 // (D::*). We consider that to be a language defect.
830 return false;
831 }
832 Path.pop_back();
833 return true;
834 }
835 /// Perform a base-to-derived member pointer cast.
836 bool castToDerived(const CXXRecordDecl *Derived) {
837 if (!getDecl())
838 return true;
839 if (!isDerivedMember()) {
840 Path.push_back(Derived);
841 return true;
842 }
843 if (!castBack(Derived))
844 return false;
845 if (Path.empty())
846 DeclAndIsDerivedMember.setInt(false);
847 return true;
848 }
849 /// Perform a derived-to-base member pointer cast.
850 bool castToBase(const CXXRecordDecl *Base) {
851 if (!getDecl())
852 return true;
853 if (Path.empty())
854 DeclAndIsDerivedMember.setInt(true);
855 if (isDerivedMember()) {
856 Path.push_back(Base);
857 return true;
858 }
859 return castBack(Base);
860 }
861 };
Richard Smithc1c5f272011-12-13 06:39:58 +0000862
Richard Smithb02e4622012-02-01 01:42:44 +0000863 /// Compare two member pointers, which are assumed to be of the same type.
864 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
865 if (!LHS.getDecl() || !RHS.getDecl())
866 return !LHS.getDecl() && !RHS.getDecl();
867 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
868 return false;
869 return LHS.Path == RHS.Path;
870 }
871
Richard Smithc1c5f272011-12-13 06:39:58 +0000872 /// Kinds of constant expression checking, for diagnostics.
873 enum CheckConstantExpressionKind {
874 CCEK_Constant, ///< A normal constant.
875 CCEK_ReturnValue, ///< A constexpr function return value.
876 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
877 };
John McCallf4cf1a12010-05-07 17:22:02 +0000878}
Chris Lattner87eae5e2008-07-11 22:52:41 +0000879
Richard Smith1aa0be82012-03-03 22:46:17 +0000880static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smith83587db2012-02-15 02:18:13 +0000881static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
882 const LValue &This, const Expr *E,
883 CheckConstantExpressionKind CCEK = CCEK_Constant,
884 bool AllowNonLiteralTypes = false);
John McCallefdb83e2010-05-07 21:00:08 +0000885static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
886static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +0000887static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
888 EvalInfo &Info);
889static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattner87eae5e2008-07-11 22:52:41 +0000890static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith1aa0be82012-03-03 22:46:17 +0000891static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattnerd9becd12009-10-28 23:59:40 +0000892 EvalInfo &Info);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +0000893static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCallf4cf1a12010-05-07 17:22:02 +0000894static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattnerf5eeb052008-07-11 18:11:29 +0000895
896//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +0000897// Misc utilities
898//===----------------------------------------------------------------------===//
899
Richard Smith180f4792011-11-10 06:34:14 +0000900/// Should this call expression be treated as a string literal?
901static bool IsStringLiteralCall(const CallExpr *E) {
902 unsigned Builtin = E->isBuiltinCall();
903 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
904 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
905}
906
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000907static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smith180f4792011-11-10 06:34:14 +0000908 // C++11 [expr.const]p3 An address constant expression is a prvalue core
909 // constant expression of pointer type that evaluates to...
910
911 // ... a null pointer value, or a prvalue core constant expression of type
912 // std::nullptr_t.
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000913 if (!B) return true;
John McCall42c8f872010-05-10 23:27:23 +0000914
Richard Smith1bf9a9e2011-11-12 22:28:03 +0000915 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
916 // ... the address of an object with static storage duration,
917 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
918 return VD->hasGlobalStorage();
919 // ... the address of a function,
920 return isa<FunctionDecl>(D);
921 }
922
923 const Expr *E = B.get<const Expr*>();
Richard Smith180f4792011-11-10 06:34:14 +0000924 switch (E->getStmtClass()) {
925 default:
926 return false;
Richard Smithb78ae972012-02-18 04:58:18 +0000927 case Expr::CompoundLiteralExprClass: {
928 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
929 return CLE->isFileScope() && CLE->isLValue();
930 }
Richard Smith180f4792011-11-10 06:34:14 +0000931 // A string literal has static storage duration.
932 case Expr::StringLiteralClass:
933 case Expr::PredefinedExprClass:
934 case Expr::ObjCStringLiteralClass:
935 case Expr::ObjCEncodeExprClass:
Richard Smith47d21452011-12-27 12:18:28 +0000936 case Expr::CXXTypeidExprClass:
Francois Pichete275a182012-04-16 04:08:35 +0000937 case Expr::CXXUuidofExprClass:
Richard Smith180f4792011-11-10 06:34:14 +0000938 return true;
939 case Expr::CallExprClass:
940 return IsStringLiteralCall(cast<CallExpr>(E));
941 // For GCC compatibility, &&label has static storage duration.
942 case Expr::AddrLabelExprClass:
943 return true;
944 // A Block literal expression may be used as the initialization value for
945 // Block variables at global or local static scope.
946 case Expr::BlockExprClass:
947 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith745f5142012-01-27 01:14:48 +0000948 case Expr::ImplicitValueInitExprClass:
949 // FIXME:
950 // We can never form an lvalue with an implicit value initialization as its
951 // base through expression evaluation, so these only appear in one case: the
952 // implicit variable declaration we invent when checking whether a constexpr
953 // constructor can produce a constant expression. We must assume that such
954 // an expression might be a global lvalue.
955 return true;
Richard Smith180f4792011-11-10 06:34:14 +0000956 }
John McCall42c8f872010-05-10 23:27:23 +0000957}
958
Richard Smith83587db2012-02-15 02:18:13 +0000959static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
960 assert(Base && "no location for a null lvalue");
961 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
962 if (VD)
963 Info.Note(VD->getLocation(), diag::note_declared_at);
964 else
Ted Kremenek890f0f12012-08-23 20:46:57 +0000965 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smith83587db2012-02-15 02:18:13 +0000966 diag::note_constexpr_temporary_here);
967}
968
Richard Smith9a17a682011-11-07 05:07:52 +0000969/// Check that this reference or pointer core constant expression is a valid
Richard Smith1aa0be82012-03-03 22:46:17 +0000970/// value for an address or reference constant expression. Return true if we
971/// can fold this expression, whether or not it's a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +0000972static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
973 QualType Type, const LValue &LVal) {
974 bool IsReferenceType = Type->isReferenceType();
975
Richard Smithc1c5f272011-12-13 06:39:58 +0000976 APValue::LValueBase Base = LVal.getLValueBase();
977 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
978
Richard Smithb78ae972012-02-18 04:58:18 +0000979 // Check that the object is a global. Note that the fake 'this' object we
980 // manufacture when checking potential constant expressions is conservatively
981 // assumed to be global here.
Richard Smithc1c5f272011-12-13 06:39:58 +0000982 if (!IsGlobalLValue(Base)) {
Richard Smith80ad52f2013-01-02 11:42:31 +0000983 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithc1c5f272011-12-13 06:39:58 +0000984 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +0000985 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
986 << IsReferenceType << !Designator.Entries.empty()
987 << !!VD << VD;
988 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +0000989 } else {
Richard Smith83587db2012-02-15 02:18:13 +0000990 Info.Diag(Loc);
Richard Smithc1c5f272011-12-13 06:39:58 +0000991 }
Richard Smith61e61622012-01-12 06:08:57 +0000992 // Don't allow references to temporaries to escape.
Richard Smith9a17a682011-11-07 05:07:52 +0000993 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +0000994 }
Richard Smith83587db2012-02-15 02:18:13 +0000995 assert((Info.CheckingPotentialConstantExpression ||
996 LVal.getLValueCallIndex() == 0) &&
997 "have call index for global lvalue");
Richard Smithb4e85ed2012-01-06 16:39:00 +0000998
Hans Wennborg48def652012-08-29 18:27:29 +0000999 // Check if this is a thread-local variable.
1000 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1001 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1002 if (Var->isThreadSpecified())
1003 return false;
1004 }
1005 }
1006
Richard Smithb4e85ed2012-01-06 16:39:00 +00001007 // Allow address constant expressions to be past-the-end pointers. This is
1008 // an extension: the standard requires them to point to an object.
1009 if (!IsReferenceType)
1010 return true;
1011
1012 // A reference constant expression must refer to an object.
1013 if (!Base) {
1014 // FIXME: diagnostic
Richard Smith83587db2012-02-15 02:18:13 +00001015 Info.CCEDiag(Loc);
Richard Smith61e61622012-01-12 06:08:57 +00001016 return true;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001017 }
1018
Richard Smithc1c5f272011-12-13 06:39:58 +00001019 // Does this refer one past the end of some object?
Richard Smithb4e85ed2012-01-06 16:39:00 +00001020 if (Designator.isOnePastTheEnd()) {
Richard Smithc1c5f272011-12-13 06:39:58 +00001021 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smith83587db2012-02-15 02:18:13 +00001022 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smithc1c5f272011-12-13 06:39:58 +00001023 << !Designator.Entries.empty() << !!VD << VD;
Richard Smith83587db2012-02-15 02:18:13 +00001024 NoteLValueLocation(Info, Base);
Richard Smithc1c5f272011-12-13 06:39:58 +00001025 }
1026
Richard Smith9a17a682011-11-07 05:07:52 +00001027 return true;
1028}
1029
Richard Smith51201882011-12-30 21:15:51 +00001030/// Check that this core constant expression is of literal type, and if not,
1031/// produce an appropriate diagnostic.
1032static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1033 if (!E->isRValue() || E->getType()->isLiteralType())
1034 return true;
1035
1036 // Prvalue constant expressions must be of literal types.
Richard Smith80ad52f2013-01-02 11:42:31 +00001037 if (Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001038 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smith51201882011-12-30 21:15:51 +00001039 << E->getType();
1040 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001041 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith51201882011-12-30 21:15:51 +00001042 return false;
1043}
1044
Richard Smith47a1eed2011-10-29 20:57:55 +00001045/// Check that this core constant expression value is a valid value for a
Richard Smith83587db2012-02-15 02:18:13 +00001046/// constant expression. If not, report an appropriate diagnostic. Does not
1047/// check that the expression is of literal type.
1048static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1049 QualType Type, const APValue &Value) {
1050 // Core issue 1454: For a literal constant expression of array or class type,
1051 // each subobject of its value shall have been initialized by a constant
1052 // expression.
1053 if (Value.isArray()) {
1054 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1055 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1056 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1057 Value.getArrayInitializedElt(I)))
1058 return false;
1059 }
1060 if (!Value.hasArrayFiller())
1061 return true;
1062 return CheckConstantExpression(Info, DiagLoc, EltTy,
1063 Value.getArrayFiller());
Richard Smith9a17a682011-11-07 05:07:52 +00001064 }
Richard Smith83587db2012-02-15 02:18:13 +00001065 if (Value.isUnion() && Value.getUnionField()) {
1066 return CheckConstantExpression(Info, DiagLoc,
1067 Value.getUnionField()->getType(),
1068 Value.getUnionValue());
1069 }
1070 if (Value.isStruct()) {
1071 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1072 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1073 unsigned BaseIndex = 0;
1074 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1075 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1076 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1077 Value.getStructBase(BaseIndex)))
1078 return false;
1079 }
1080 }
1081 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1082 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001083 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1084 Value.getStructField(I->getFieldIndex())))
Richard Smith83587db2012-02-15 02:18:13 +00001085 return false;
1086 }
1087 }
1088
1089 if (Value.isLValue()) {
Richard Smith83587db2012-02-15 02:18:13 +00001090 LValue LVal;
Richard Smith1aa0be82012-03-03 22:46:17 +00001091 LVal.setFrom(Info.Ctx, Value);
Richard Smith83587db2012-02-15 02:18:13 +00001092 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1093 }
1094
1095 // Everything else is fine.
1096 return true;
Richard Smith47a1eed2011-10-29 20:57:55 +00001097}
1098
Richard Smith9e36b532011-10-31 05:11:32 +00001099const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001100 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith9e36b532011-10-31 05:11:32 +00001101}
1102
1103static bool IsLiteralLValue(const LValue &Value) {
Richard Smith83587db2012-02-15 02:18:13 +00001104 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith9e36b532011-10-31 05:11:32 +00001105}
1106
Richard Smith65ac5982011-11-01 21:06:14 +00001107static bool IsWeakLValue(const LValue &Value) {
1108 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hames0dd7a252011-12-05 20:16:26 +00001109 return Decl && Decl->isWeak();
Richard Smith65ac5982011-11-01 21:06:14 +00001110}
1111
Richard Smith1aa0be82012-03-03 22:46:17 +00001112static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCall35542832010-05-07 21:34:32 +00001113 // A null base expression indicates a null pointer. These are always
1114 // evaluatable, and they are false unless the offset is zero.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001115 if (!Value.getLValueBase()) {
1116 Result = !Value.getLValueOffset().isZero();
John McCall35542832010-05-07 21:34:32 +00001117 return true;
1118 }
Rafael Espindolaa7d3c042010-05-07 15:18:43 +00001119
Richard Smithe24f5fc2011-11-17 22:56:20 +00001120 // We have a non-null base. These are generally known to be true, but if it's
1121 // a weak declaration it can be null at runtime.
John McCall35542832010-05-07 21:34:32 +00001122 Result = true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001123 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hames0dd7a252011-12-05 20:16:26 +00001124 return !Decl || !Decl->isWeak();
Eli Friedman5bc86102009-06-14 02:17:33 +00001125}
1126
Richard Smith1aa0be82012-03-03 22:46:17 +00001127static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smithc49bd112011-10-28 17:51:58 +00001128 switch (Val.getKind()) {
1129 case APValue::Uninitialized:
1130 return false;
1131 case APValue::Int:
1132 Result = Val.getInt().getBoolValue();
Eli Friedman4efaa272008-11-12 09:44:48 +00001133 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001134 case APValue::Float:
1135 Result = !Val.getFloat().isZero();
Eli Friedman4efaa272008-11-12 09:44:48 +00001136 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001137 case APValue::ComplexInt:
1138 Result = Val.getComplexIntReal().getBoolValue() ||
1139 Val.getComplexIntImag().getBoolValue();
1140 return true;
1141 case APValue::ComplexFloat:
1142 Result = !Val.getComplexFloatReal().isZero() ||
1143 !Val.getComplexFloatImag().isZero();
1144 return true;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001145 case APValue::LValue:
1146 return EvalPointerValueAsBool(Val, Result);
1147 case APValue::MemberPointer:
1148 Result = Val.getMemberPointerDecl();
1149 return true;
Richard Smithc49bd112011-10-28 17:51:58 +00001150 case APValue::Vector:
Richard Smithcc5d4f62011-11-07 09:22:26 +00001151 case APValue::Array:
Richard Smith180f4792011-11-10 06:34:14 +00001152 case APValue::Struct:
1153 case APValue::Union:
Eli Friedman65639282012-01-04 23:13:47 +00001154 case APValue::AddrLabelDiff:
Richard Smithc49bd112011-10-28 17:51:58 +00001155 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00001156 }
1157
Richard Smithc49bd112011-10-28 17:51:58 +00001158 llvm_unreachable("unknown APValue kind");
1159}
1160
1161static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1162 EvalInfo &Info) {
1163 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith1aa0be82012-03-03 22:46:17 +00001164 APValue Val;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001165 if (!Evaluate(Val, Info, E))
Richard Smithc49bd112011-10-28 17:51:58 +00001166 return false;
Argyrios Kyrtzidisd411a4b2012-02-27 20:21:34 +00001167 return HandleConversionToBool(Val, Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00001168}
1169
Richard Smithc1c5f272011-12-13 06:39:58 +00001170template<typename T>
Eli Friedman26dc97c2012-07-17 21:03:05 +00001171static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smithc1c5f272011-12-13 06:39:58 +00001172 const T &SrcValue, QualType DestType) {
Eli Friedman26dc97c2012-07-17 21:03:05 +00001173 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smith789f9b62012-01-31 04:08:20 +00001174 << SrcValue << DestType;
Richard Smithc1c5f272011-12-13 06:39:58 +00001175}
1176
1177static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1178 QualType SrcType, const APFloat &Value,
1179 QualType DestType, APSInt &Result) {
1180 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001181 // Determine whether we are converting to unsigned or signed.
Douglas Gregor575a1c92011-05-20 16:38:50 +00001182 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump1eb44332009-09-09 15:08:12 +00001183
Richard Smithc1c5f272011-12-13 06:39:58 +00001184 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001185 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001186 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1187 & APFloat::opInvalidOp)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001188 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001189 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001190}
1191
Richard Smithc1c5f272011-12-13 06:39:58 +00001192static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1193 QualType SrcType, QualType DestType,
1194 APFloat &Result) {
1195 APFloat Value = Result;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001196 bool ignored;
Richard Smithc1c5f272011-12-13 06:39:58 +00001197 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1198 APFloat::rmNearestTiesToEven, &ignored)
1199 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001200 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001201 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001202}
1203
Richard Smithf72fccf2012-01-30 22:27:01 +00001204static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1205 QualType DestType, QualType SrcType,
1206 APSInt &Value) {
1207 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001208 APSInt Result = Value;
1209 // Figure out if this is a truncate, extend or noop cast.
1210 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad9f71a8f2010-12-07 08:25:34 +00001211 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor575a1c92011-05-20 16:38:50 +00001212 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001213 return Result;
1214}
1215
Richard Smithc1c5f272011-12-13 06:39:58 +00001216static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1217 QualType SrcType, const APSInt &Value,
1218 QualType DestType, APFloat &Result) {
1219 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1220 if (Result.convertFromAPInt(Value, Value.isSigned(),
1221 APFloat::rmNearestTiesToEven)
1222 & APFloat::opOverflow)
Eli Friedman26dc97c2012-07-17 21:03:05 +00001223 HandleOverflow(Info, E, Value, DestType);
Richard Smithc1c5f272011-12-13 06:39:58 +00001224 return true;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00001225}
1226
Eli Friedmane6a24e82011-12-22 03:51:45 +00001227static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1228 llvm::APInt &Res) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001229 APValue SVal;
Eli Friedmane6a24e82011-12-22 03:51:45 +00001230 if (!Evaluate(SVal, Info, E))
1231 return false;
1232 if (SVal.isInt()) {
1233 Res = SVal.getInt();
1234 return true;
1235 }
1236 if (SVal.isFloat()) {
1237 Res = SVal.getFloat().bitcastToAPInt();
1238 return true;
1239 }
1240 if (SVal.isVector()) {
1241 QualType VecTy = E->getType();
1242 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1243 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1244 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1245 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1246 Res = llvm::APInt::getNullValue(VecSize);
1247 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1248 APValue &Elt = SVal.getVectorElt(i);
1249 llvm::APInt EltAsInt;
1250 if (Elt.isInt()) {
1251 EltAsInt = Elt.getInt();
1252 } else if (Elt.isFloat()) {
1253 EltAsInt = Elt.getFloat().bitcastToAPInt();
1254 } else {
1255 // Don't try to handle vectors of anything other than int or float
1256 // (not sure if it's possible to hit this case).
Richard Smith5cfc7d82012-03-15 04:53:45 +00001257 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001258 return false;
1259 }
1260 unsigned BaseEltSize = EltAsInt.getBitWidth();
1261 if (BigEndian)
1262 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1263 else
1264 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1265 }
1266 return true;
1267 }
1268 // Give up if the input isn't an int, float, or vector. For example, we
1269 // reject "(v4i16)(intptr_t)&a".
Richard Smith5cfc7d82012-03-15 04:53:45 +00001270 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedmane6a24e82011-12-22 03:51:45 +00001271 return false;
1272}
1273
Richard Smithb4e85ed2012-01-06 16:39:00 +00001274/// Cast an lvalue referring to a base subobject to a derived class, by
1275/// truncating the lvalue's path to the given length.
1276static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1277 const RecordDecl *TruncatedType,
1278 unsigned TruncatedElements) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00001279 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001280
1281 // Check we actually point to a derived class object.
1282 if (TruncatedElements == D.Entries.size())
1283 return true;
1284 assert(TruncatedElements >= D.MostDerivedPathLength &&
1285 "not casting to a derived class");
1286 if (!Result.checkSubobject(Info, E, CSK_Derived))
1287 return false;
1288
1289 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001290 const RecordDecl *RD = TruncatedType;
1291 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCall8d59dee2012-05-01 00:38:49 +00001292 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001293 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1294 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001295 if (isVirtualBaseClass(D.Entries[I]))
Richard Smith180f4792011-11-10 06:34:14 +00001296 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smithe24f5fc2011-11-17 22:56:20 +00001297 else
Richard Smith180f4792011-11-10 06:34:14 +00001298 Result.Offset -= Layout.getBaseClassOffset(Base);
1299 RD = Base;
1300 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001301 D.Entries.resize(TruncatedElements);
Richard Smith180f4792011-11-10 06:34:14 +00001302 return true;
1303}
1304
John McCall8d59dee2012-05-01 00:38:49 +00001305static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001306 const CXXRecordDecl *Derived,
1307 const CXXRecordDecl *Base,
1308 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001309 if (!RL) {
1310 if (Derived->isInvalidDecl()) return false;
1311 RL = &Info.Ctx.getASTRecordLayout(Derived);
1312 }
1313
Richard Smith180f4792011-11-10 06:34:14 +00001314 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001315 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCall8d59dee2012-05-01 00:38:49 +00001316 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001317}
1318
Richard Smithb4e85ed2012-01-06 16:39:00 +00001319static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smith180f4792011-11-10 06:34:14 +00001320 const CXXRecordDecl *DerivedDecl,
1321 const CXXBaseSpecifier *Base) {
1322 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1323
John McCall8d59dee2012-05-01 00:38:49 +00001324 if (!Base->isVirtual())
1325 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smith180f4792011-11-10 06:34:14 +00001326
Richard Smithb4e85ed2012-01-06 16:39:00 +00001327 SubobjectDesignator &D = Obj.Designator;
1328 if (D.Invalid)
Richard Smith180f4792011-11-10 06:34:14 +00001329 return false;
1330
Richard Smithb4e85ed2012-01-06 16:39:00 +00001331 // Extract most-derived object and corresponding type.
1332 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1333 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1334 return false;
1335
1336 // Find the virtual base class.
John McCall8d59dee2012-05-01 00:38:49 +00001337 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001338 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1339 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smithb4e85ed2012-01-06 16:39:00 +00001340 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smith180f4792011-11-10 06:34:14 +00001341 return true;
1342}
1343
1344/// Update LVal to refer to the given field, which must be a member of the type
1345/// currently described by LVal.
John McCall8d59dee2012-05-01 00:38:49 +00001346static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smith180f4792011-11-10 06:34:14 +00001347 const FieldDecl *FD,
1348 const ASTRecordLayout *RL = 0) {
John McCall8d59dee2012-05-01 00:38:49 +00001349 if (!RL) {
1350 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00001351 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCall8d59dee2012-05-01 00:38:49 +00001352 }
Richard Smith180f4792011-11-10 06:34:14 +00001353
1354 unsigned I = FD->getFieldIndex();
1355 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smithb4e85ed2012-01-06 16:39:00 +00001356 LVal.addDecl(Info, E, FD);
John McCall8d59dee2012-05-01 00:38:49 +00001357 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001358}
1359
Richard Smithd9b02e72012-01-25 22:15:11 +00001360/// Update LVal to refer to the given indirect field.
John McCall8d59dee2012-05-01 00:38:49 +00001361static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smithd9b02e72012-01-25 22:15:11 +00001362 LValue &LVal,
1363 const IndirectFieldDecl *IFD) {
1364 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1365 CE = IFD->chain_end(); C != CE; ++C)
John McCall8d59dee2012-05-01 00:38:49 +00001366 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1367 return false;
1368 return true;
Richard Smithd9b02e72012-01-25 22:15:11 +00001369}
1370
Richard Smith180f4792011-11-10 06:34:14 +00001371/// Get the size of the given type in char units.
Richard Smith74e1ad92012-02-16 02:46:34 +00001372static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1373 QualType Type, CharUnits &Size) {
Richard Smith180f4792011-11-10 06:34:14 +00001374 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1375 // extension.
1376 if (Type->isVoidType() || Type->isFunctionType()) {
1377 Size = CharUnits::One();
1378 return true;
1379 }
1380
1381 if (!Type->isConstantSizeType()) {
1382 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith74e1ad92012-02-16 02:46:34 +00001383 // FIXME: Better diagnostic.
1384 Info.Diag(Loc);
Richard Smith180f4792011-11-10 06:34:14 +00001385 return false;
1386 }
1387
1388 Size = Info.Ctx.getTypeSizeInChars(Type);
1389 return true;
1390}
1391
1392/// Update a pointer value to model pointer arithmetic.
1393/// \param Info - Information about the ongoing evaluation.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001394/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smith180f4792011-11-10 06:34:14 +00001395/// \param LVal - The pointer value to be updated.
1396/// \param EltTy - The pointee type represented by LVal.
1397/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001398static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1399 LValue &LVal, QualType EltTy,
1400 int64_t Adjustment) {
Richard Smith180f4792011-11-10 06:34:14 +00001401 CharUnits SizeOfPointee;
Richard Smith74e1ad92012-02-16 02:46:34 +00001402 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smith180f4792011-11-10 06:34:14 +00001403 return false;
1404
1405 // Compute the new offset in the appropriate width.
1406 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001407 LVal.adjustIndex(Info, E, Adjustment);
Richard Smith180f4792011-11-10 06:34:14 +00001408 return true;
1409}
1410
Richard Smith86024012012-02-18 22:04:06 +00001411/// Update an lvalue to refer to a component of a complex number.
1412/// \param Info - Information about the ongoing evaluation.
1413/// \param LVal - The lvalue to be updated.
1414/// \param EltTy - The complex number's component type.
1415/// \param Imag - False for the real component, true for the imaginary.
1416static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1417 LValue &LVal, QualType EltTy,
1418 bool Imag) {
1419 if (Imag) {
1420 CharUnits SizeOfComponent;
1421 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1422 return false;
1423 LVal.Offset += SizeOfComponent;
1424 }
1425 LVal.addComplex(Info, E, EltTy, Imag);
1426 return true;
1427}
1428
Richard Smith03f96112011-10-24 17:54:18 +00001429/// Try to evaluate the initializer for a variable declaration.
Richard Smithf48fdb02011-12-09 22:58:01 +00001430static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1431 const VarDecl *VD,
Richard Smith1aa0be82012-03-03 22:46:17 +00001432 CallStackFrame *Frame, APValue &Result) {
Richard Smithd0dccea2011-10-28 22:34:42 +00001433 // If this is a parameter to an active constexpr function call, perform
1434 // argument substitution.
1435 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith745f5142012-01-27 01:14:48 +00001436 // Assume arguments of a potential constant expression are unknown
1437 // constant expressions.
1438 if (Info.CheckingPotentialConstantExpression)
1439 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001440 if (!Frame || !Frame->Arguments) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001441 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith177dce72011-11-01 16:57:24 +00001442 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001443 }
Richard Smith177dce72011-11-01 16:57:24 +00001444 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1445 return true;
Richard Smithd0dccea2011-10-28 22:34:42 +00001446 }
Richard Smith03f96112011-10-24 17:54:18 +00001447
Richard Smith099e7f62011-12-19 06:19:21 +00001448 // Dig out the initializer, and use the declaration which it's attached to.
1449 const Expr *Init = VD->getAnyInitializer(VD);
1450 if (!Init || Init->isValueDependent()) {
Richard Smith745f5142012-01-27 01:14:48 +00001451 // If we're checking a potential constant expression, the variable could be
1452 // initialized later.
1453 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001454 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith099e7f62011-12-19 06:19:21 +00001455 return false;
1456 }
1457
Richard Smith180f4792011-11-10 06:34:14 +00001458 // If we're currently evaluating the initializer of this declaration, use that
1459 // in-flight value.
1460 if (Info.EvaluatingDecl == VD) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001461 Result = *Info.EvaluatingDeclValue;
Richard Smith180f4792011-11-10 06:34:14 +00001462 return !Result.isUninit();
1463 }
1464
Richard Smith65ac5982011-11-01 21:06:14 +00001465 // Never evaluate the initializer of a weak variable. We can't be sure that
1466 // this is the definition which will be used.
Richard Smithf48fdb02011-12-09 22:58:01 +00001467 if (VD->isWeak()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001468 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith65ac5982011-11-01 21:06:14 +00001469 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001470 }
Richard Smith65ac5982011-11-01 21:06:14 +00001471
Richard Smith099e7f62011-12-19 06:19:21 +00001472 // Check that we can fold the initializer. In C++, we will have already done
1473 // this in the cases where it matters for conformance.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001474 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smith099e7f62011-12-19 06:19:21 +00001475 if (!VD->evaluateValue(Notes)) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001476 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001477 Notes.size() + 1) << VD;
1478 Info.Note(VD->getLocation(), diag::note_declared_at);
1479 Info.addNotes(Notes);
Richard Smith47a1eed2011-10-29 20:57:55 +00001480 return false;
Richard Smith099e7f62011-12-19 06:19:21 +00001481 } else if (!VD->checkInitIsICE()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001482 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smith099e7f62011-12-19 06:19:21 +00001483 Notes.size() + 1) << VD;
1484 Info.Note(VD->getLocation(), diag::note_declared_at);
1485 Info.addNotes(Notes);
Richard Smithf48fdb02011-12-09 22:58:01 +00001486 }
Richard Smith03f96112011-10-24 17:54:18 +00001487
Richard Smith1aa0be82012-03-03 22:46:17 +00001488 Result = *VD->getEvaluatedValue();
Richard Smith47a1eed2011-10-29 20:57:55 +00001489 return true;
Richard Smith03f96112011-10-24 17:54:18 +00001490}
1491
Richard Smithc49bd112011-10-28 17:51:58 +00001492static bool IsConstNonVolatile(QualType T) {
Richard Smith03f96112011-10-24 17:54:18 +00001493 Qualifiers Quals = T.getQualifiers();
1494 return Quals.hasConst() && !Quals.hasVolatile();
1495}
1496
Richard Smith59efe262011-11-11 04:05:33 +00001497/// Get the base index of the given base class within an APValue representing
1498/// the given derived class.
1499static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1500 const CXXRecordDecl *Base) {
1501 Base = Base->getCanonicalDecl();
1502 unsigned Index = 0;
1503 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1504 E = Derived->bases_end(); I != E; ++I, ++Index) {
1505 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1506 return Index;
1507 }
1508
1509 llvm_unreachable("base class missing from derived class's bases list");
1510}
1511
Richard Smithfe587202012-04-15 02:50:59 +00001512/// Extract the value of a character from a string literal. CharType is used to
1513/// determine the expected signedness of the result -- a string literal used to
1514/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1515/// of the wrong signedness.
Richard Smithf3908f22012-02-17 03:35:37 +00001516static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smithfe587202012-04-15 02:50:59 +00001517 uint64_t Index, QualType CharType) {
Richard Smithf3908f22012-02-17 03:35:37 +00001518 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1519 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1520 assert(S && "unexpected string literal expression kind");
Richard Smithfe587202012-04-15 02:50:59 +00001521 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smithf3908f22012-02-17 03:35:37 +00001522
1523 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smithfe587202012-04-15 02:50:59 +00001524 CharType->isUnsignedIntegerType());
Richard Smithf3908f22012-02-17 03:35:37 +00001525 if (Index < S->getLength())
1526 Value = S->getCodeUnit(Index);
1527 return Value;
1528}
1529
Richard Smithcc5d4f62011-11-07 09:22:26 +00001530/// Extract the designated sub-object of an rvalue.
Richard Smithf48fdb02011-12-09 22:58:01 +00001531static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith1aa0be82012-03-03 22:46:17 +00001532 APValue &Obj, QualType ObjType,
Richard Smithcc5d4f62011-11-07 09:22:26 +00001533 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001534 if (Sub.Invalid)
1535 // A diagnostic will have already been produced.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001536 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00001537 if (Sub.isOnePastTheEnd()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001538 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001539 (unsigned)diag::note_constexpr_read_past_end :
1540 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001541 return false;
1542 }
Richard Smithf64699e2011-11-11 08:28:03 +00001543 if (Sub.Entries.empty())
Richard Smithcc5d4f62011-11-07 09:22:26 +00001544 return true;
Richard Smith745f5142012-01-27 01:14:48 +00001545 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1546 // This object might be initialized later.
1547 return false;
Richard Smithcc5d4f62011-11-07 09:22:26 +00001548
Richard Smith0069b842012-03-10 00:28:11 +00001549 APValue *O = &Obj;
Richard Smith180f4792011-11-10 06:34:14 +00001550 // Walk the designator's path to find the subobject.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001551 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithcc5d4f62011-11-07 09:22:26 +00001552 if (ObjType->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00001553 // Next subobject is an array element.
Richard Smithcc5d4f62011-11-07 09:22:26 +00001554 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf48fdb02011-12-09 22:58:01 +00001555 assert(CAT && "vla in literal type?");
Richard Smithcc5d4f62011-11-07 09:22:26 +00001556 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf48fdb02011-12-09 22:58:01 +00001557 if (CAT->getSize().ule(Index)) {
Richard Smith7098cbd2011-12-21 05:04:46 +00001558 // Note, it should not be possible to form a pointer with a valid
1559 // designator which points more than one past the end of the array.
Richard Smith80ad52f2013-01-02 11:42:31 +00001560 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gayaa5d5332011-12-21 19:36:37 +00001561 (unsigned)diag::note_constexpr_read_past_end :
1562 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001563 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001564 }
Richard Smithf3908f22012-02-17 03:35:37 +00001565 // An array object is represented as either an Array APValue or as an
1566 // LValue which refers to a string literal.
1567 if (O->isLValue()) {
1568 assert(I == N - 1 && "extracting subobject of character?");
1569 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith1aa0be82012-03-03 22:46:17 +00001570 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smithfe587202012-04-15 02:50:59 +00001571 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smithf3908f22012-02-17 03:35:37 +00001572 return true;
1573 } else if (O->getArrayInitializedElts() > Index)
Richard Smithcc5d4f62011-11-07 09:22:26 +00001574 O = &O->getArrayInitializedElt(Index);
1575 else
1576 O = &O->getArrayFiller();
1577 ObjType = CAT->getElementType();
Richard Smith86024012012-02-18 22:04:06 +00001578 } else if (ObjType->isAnyComplexType()) {
1579 // Next subobject is a complex number.
1580 uint64_t Index = Sub.Entries[I].ArrayIndex;
1581 if (Index > 1) {
Richard Smith80ad52f2013-01-02 11:42:31 +00001582 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Richard Smith86024012012-02-18 22:04:06 +00001583 (unsigned)diag::note_constexpr_read_past_end :
1584 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1585 return false;
1586 }
1587 assert(I == N - 1 && "extracting subobject of scalar?");
1588 if (O->isComplexInt()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00001589 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith86024012012-02-18 22:04:06 +00001590 : O->getComplexIntReal());
1591 } else {
1592 assert(O->isComplexFloat());
Richard Smith1aa0be82012-03-03 22:46:17 +00001593 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith86024012012-02-18 22:04:06 +00001594 : O->getComplexFloatReal());
1595 }
1596 return true;
Richard Smith180f4792011-11-10 06:34:14 +00001597 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smithb4e5e282012-02-09 03:29:58 +00001598 if (Field->isMutable()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001599 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smithb4e5e282012-02-09 03:29:58 +00001600 << Field;
1601 Info.Note(Field->getLocation(), diag::note_declared_at);
1602 return false;
1603 }
1604
Richard Smith180f4792011-11-10 06:34:14 +00001605 // Next subobject is a class, struct or union field.
1606 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1607 if (RD->isUnion()) {
1608 const FieldDecl *UnionField = O->getUnionField();
1609 if (!UnionField ||
Richard Smithf48fdb02011-12-09 22:58:01 +00001610 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001611 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smith7098cbd2011-12-21 05:04:46 +00001612 << Field << !UnionField << UnionField;
Richard Smith180f4792011-11-10 06:34:14 +00001613 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001614 }
Richard Smith180f4792011-11-10 06:34:14 +00001615 O = &O->getUnionValue();
1616 } else
1617 O = &O->getStructField(Field->getFieldIndex());
1618 ObjType = Field->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001619
1620 if (ObjType.isVolatileQualified()) {
1621 if (Info.getLangOpts().CPlusPlus) {
1622 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001623 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smith7098cbd2011-12-21 05:04:46 +00001624 << 2 << Field;
1625 Info.Note(Field->getLocation(), diag::note_declared_at);
1626 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001627 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001628 }
1629 return false;
1630 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001631 } else {
Richard Smith180f4792011-11-10 06:34:14 +00001632 // Next subobject is a base class.
Richard Smith59efe262011-11-11 04:05:33 +00001633 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1634 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1635 O = &O->getStructBase(getBaseIndex(Derived, Base));
1636 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001637 }
Richard Smith180f4792011-11-10 06:34:14 +00001638
Richard Smithf48fdb02011-12-09 22:58:01 +00001639 if (O->isUninit()) {
Richard Smith745f5142012-01-27 01:14:48 +00001640 if (!Info.CheckingPotentialConstantExpression)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001641 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smith180f4792011-11-10 06:34:14 +00001642 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001643 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00001644 }
1645
Richard Smith0069b842012-03-10 00:28:11 +00001646 // This may look super-stupid, but it serves an important purpose: if we just
1647 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1648 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1649 // object, which is destroyed by Tmp's destructor.
1650 APValue Tmp;
1651 O->swap(Tmp);
1652 Obj.swap(Tmp);
Richard Smithcc5d4f62011-11-07 09:22:26 +00001653 return true;
1654}
1655
Richard Smithf15fda02012-02-02 01:16:57 +00001656/// Find the position where two subobject designators diverge, or equivalently
1657/// the length of the common initial subsequence.
1658static unsigned FindDesignatorMismatch(QualType ObjType,
1659 const SubobjectDesignator &A,
1660 const SubobjectDesignator &B,
1661 bool &WasArrayIndex) {
1662 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1663 for (/**/; I != N; ++I) {
Richard Smith86024012012-02-18 22:04:06 +00001664 if (!ObjType.isNull() &&
1665 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smithf15fda02012-02-02 01:16:57 +00001666 // Next subobject is an array element.
1667 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1668 WasArrayIndex = true;
1669 return I;
1670 }
Richard Smith86024012012-02-18 22:04:06 +00001671 if (ObjType->isAnyComplexType())
1672 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1673 else
1674 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smithf15fda02012-02-02 01:16:57 +00001675 } else {
1676 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1677 WasArrayIndex = false;
1678 return I;
1679 }
1680 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1681 // Next subobject is a field.
1682 ObjType = FD->getType();
1683 else
1684 // Next subobject is a base class.
1685 ObjType = QualType();
1686 }
1687 }
1688 WasArrayIndex = false;
1689 return I;
1690}
1691
1692/// Determine whether the given subobject designators refer to elements of the
1693/// same array object.
1694static bool AreElementsOfSameArray(QualType ObjType,
1695 const SubobjectDesignator &A,
1696 const SubobjectDesignator &B) {
1697 if (A.Entries.size() != B.Entries.size())
1698 return false;
1699
1700 bool IsArray = A.MostDerivedArraySize != 0;
1701 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1702 // A is a subobject of the array element.
1703 return false;
1704
1705 // If A (and B) designates an array element, the last entry will be the array
1706 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1707 // of length 1' case, and the entire path must match.
1708 bool WasArrayIndex;
1709 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1710 return CommonLength >= A.Entries.size() - IsArray;
1711}
1712
Richard Smith180f4792011-11-10 06:34:14 +00001713/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1714/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1715/// for looking up the glvalue referred to by an entity of reference type.
1716///
1717/// \param Info - Information about the ongoing evaluation.
Richard Smithf48fdb02011-12-09 22:58:01 +00001718/// \param Conv - The expression for which we are performing the conversion.
1719/// Used for diagnostics.
Richard Smith9ec71972012-02-05 01:23:16 +00001720/// \param Type - The type we expect this conversion to produce, before
1721/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smith180f4792011-11-10 06:34:14 +00001722/// \param LVal - The glvalue on which we are attempting to perform this action.
1723/// \param RVal - The produced value will be placed here.
Richard Smithf48fdb02011-12-09 22:58:01 +00001724static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1725 QualType Type,
Richard Smith1aa0be82012-03-03 22:46:17 +00001726 const LValue &LVal, APValue &RVal) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00001727 if (LVal.Designator.Invalid)
1728 // A diagnostic will have already been produced.
1729 return false;
1730
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001731 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smithc49bd112011-10-28 17:51:58 +00001732
Richard Smithf48fdb02011-12-09 22:58:01 +00001733 if (!LVal.Base) {
1734 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smith5cfc7d82012-03-15 04:53:45 +00001735 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith7098cbd2011-12-21 05:04:46 +00001736 return false;
1737 }
1738
Richard Smith83587db2012-02-15 02:18:13 +00001739 CallStackFrame *Frame = 0;
1740 if (LVal.CallIndex) {
1741 Frame = Info.getCallFrame(LVal.CallIndex);
1742 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001743 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001744 NoteLValueLocation(Info, LVal.Base);
1745 return false;
1746 }
1747 }
1748
Richard Smith7098cbd2011-12-21 05:04:46 +00001749 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1750 // is not a constant expression (even if the object is non-volatile). We also
1751 // apply this rule to C++98, in order to conform to the expected 'volatile'
1752 // semantics.
1753 if (Type.isVolatileQualified()) {
1754 if (Info.getLangOpts().CPlusPlus)
Richard Smith5cfc7d82012-03-15 04:53:45 +00001755 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smith7098cbd2011-12-21 05:04:46 +00001756 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00001757 Info.Diag(Conv);
Richard Smithc49bd112011-10-28 17:51:58 +00001758 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001759 }
Richard Smithc49bd112011-10-28 17:51:58 +00001760
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001761 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smithc49bd112011-10-28 17:51:58 +00001762 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1763 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smithd0dccea2011-10-28 22:34:42 +00001764 // expressions are constant expressions too. Inside constexpr functions,
1765 // parameters are constant expressions even if they're non-const.
Richard Smithc49bd112011-10-28 17:51:58 +00001766 // In C, such things can also be folded, although they are not ICEs.
Richard Smithc49bd112011-10-28 17:51:58 +00001767 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregord2008e22012-04-06 22:40:38 +00001768 if (VD) {
1769 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1770 VD = VDef;
1771 }
Richard Smithf48fdb02011-12-09 22:58:01 +00001772 if (!VD || VD->isInvalidDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001773 Info.Diag(Conv);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001774 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001775 }
1776
Richard Smith7098cbd2011-12-21 05:04:46 +00001777 // DR1313: If the object is volatile-qualified but the glvalue was not,
1778 // behavior is undefined so the result is not a constant expression.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001779 QualType VT = VD->getType();
Richard Smith7098cbd2011-12-21 05:04:46 +00001780 if (VT.isVolatileQualified()) {
1781 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001782 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001783 Info.Note(VD->getLocation(), diag::note_declared_at);
1784 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001785 Info.Diag(Conv);
Richard Smithf48fdb02011-12-09 22:58:01 +00001786 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001787 return false;
1788 }
1789
1790 if (!isa<ParmVarDecl>(VD)) {
1791 if (VD->isConstexpr()) {
1792 // OK, we can read this variable.
1793 } else if (VT->isIntegralOrEnumerationType()) {
1794 if (!VT.isConstQualified()) {
1795 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001796 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001797 Info.Note(VD->getLocation(), diag::note_declared_at);
1798 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001799 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001800 }
1801 return false;
1802 }
1803 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1804 // We support folding of const floating-point types, in order to make
1805 // static const data members of such types (supported as an extension)
1806 // more useful.
Richard Smith80ad52f2013-01-02 11:42:31 +00001807 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001808 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001809 Info.Note(VD->getLocation(), diag::note_declared_at);
1810 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001811 Info.CCEDiag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001812 }
1813 } else {
1814 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smith80ad52f2013-01-02 11:42:31 +00001815 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001816 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith7098cbd2011-12-21 05:04:46 +00001817 Info.Note(VD->getLocation(), diag::note_declared_at);
1818 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001819 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001820 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001821 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001822 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001823 }
Richard Smith7098cbd2011-12-21 05:04:46 +00001824
Richard Smithf48fdb02011-12-09 22:58:01 +00001825 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smithc49bd112011-10-28 17:51:58 +00001826 return false;
1827
Richard Smith47a1eed2011-10-29 20:57:55 +00001828 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf48fdb02011-12-09 22:58:01 +00001829 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001830
1831 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1832 // conversion. This happens when the declaration and the lvalue should be
1833 // considered synonymous, for instance when initializing an array of char
1834 // from a string literal. Continue as if the initializer lvalue was the
1835 // value we were originally given.
Richard Smith0a3bdb62011-11-04 02:25:55 +00001836 assert(RVal.getLValueOffset().isZero() &&
1837 "offset for lvalue init of non-reference");
Richard Smith1bf9a9e2011-11-12 22:28:03 +00001838 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smith83587db2012-02-15 02:18:13 +00001839
1840 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1841 Frame = Info.getCallFrame(CallIndex);
1842 if (!Frame) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001843 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smith83587db2012-02-15 02:18:13 +00001844 NoteLValueLocation(Info, RVal.getLValueBase());
1845 return false;
1846 }
1847 } else {
1848 Frame = 0;
1849 }
Richard Smithc49bd112011-10-28 17:51:58 +00001850 }
1851
Richard Smith7098cbd2011-12-21 05:04:46 +00001852 // Volatile temporary objects cannot be read in constant expressions.
1853 if (Base->getType().isVolatileQualified()) {
1854 if (Info.getLangOpts().CPlusPlus) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001855 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smith7098cbd2011-12-21 05:04:46 +00001856 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1857 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001858 Info.Diag(Conv);
Richard Smith7098cbd2011-12-21 05:04:46 +00001859 }
1860 return false;
1861 }
1862
Richard Smithcc5d4f62011-11-07 09:22:26 +00001863 if (Frame) {
1864 // If this is a temporary expression with a nontrivial initializer, grab the
1865 // value from the relevant stack frame.
1866 RVal = Frame->Temporaries[Base];
1867 } else if (const CompoundLiteralExpr *CLE
1868 = dyn_cast<CompoundLiteralExpr>(Base)) {
1869 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1870 // initializer until now for such expressions. Such an expression can't be
1871 // an ICE in C, so this only matters for fold.
1872 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1873 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1874 return false;
Richard Smithf3908f22012-02-17 03:35:37 +00001875 } else if (isa<StringLiteral>(Base)) {
1876 // We represent a string literal array as an lvalue pointing at the
1877 // corresponding expression, rather than building an array of chars.
1878 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith1aa0be82012-03-03 22:46:17 +00001879 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf48fdb02011-12-09 22:58:01 +00001880 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00001881 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith0a3bdb62011-11-04 02:25:55 +00001882 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00001883 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00001884
Richard Smithf48fdb02011-12-09 22:58:01 +00001885 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1886 Type);
Richard Smithc49bd112011-10-28 17:51:58 +00001887}
1888
Richard Smith59efe262011-11-11 04:05:33 +00001889/// Build an lvalue for the object argument of a member function call.
1890static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1891 LValue &This) {
1892 if (Object->getType()->isPointerType())
1893 return EvaluatePointer(Object, This, Info);
1894
1895 if (Object->isGLValue())
1896 return EvaluateLValue(Object, This, Info);
1897
Richard Smithe24f5fc2011-11-17 22:56:20 +00001898 if (Object->getType()->isLiteralType())
1899 return EvaluateTemporary(Object, This, Info);
1900
1901 return false;
1902}
1903
1904/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1905/// lvalue referring to the result.
1906///
1907/// \param Info - Information about the ongoing evaluation.
1908/// \param BO - The member pointer access operation.
1909/// \param LV - Filled in with a reference to the resulting object.
1910/// \param IncludeMember - Specifies whether the member itself is included in
1911/// the resulting LValue subobject designator. This is not possible when
1912/// creating a bound member function.
1913/// \return The field or method declaration to which the member pointer refers,
1914/// or 0 if evaluation fails.
1915static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1916 const BinaryOperator *BO,
1917 LValue &LV,
1918 bool IncludeMember = true) {
1919 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1920
Richard Smith745f5142012-01-27 01:14:48 +00001921 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1922 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smithe24f5fc2011-11-17 22:56:20 +00001923 return 0;
1924
1925 MemberPtr MemPtr;
1926 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1927 return 0;
1928
1929 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1930 // member value, the behavior is undefined.
1931 if (!MemPtr.getDecl())
1932 return 0;
1933
Richard Smith745f5142012-01-27 01:14:48 +00001934 if (!EvalObjOK)
1935 return 0;
1936
Richard Smithe24f5fc2011-11-17 22:56:20 +00001937 if (MemPtr.isDerivedMember()) {
1938 // This is a member of some derived class. Truncate LV appropriately.
Richard Smithe24f5fc2011-11-17 22:56:20 +00001939 // The end of the derived-to-base path for the base object must match the
1940 // derived-to-base path for the member pointer.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001941 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smithe24f5fc2011-11-17 22:56:20 +00001942 LV.Designator.Entries.size())
1943 return 0;
1944 unsigned PathLengthToMember =
1945 LV.Designator.Entries.size() - MemPtr.Path.size();
1946 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1947 const CXXRecordDecl *LVDecl = getAsBaseClass(
1948 LV.Designator.Entries[PathLengthToMember + I]);
1949 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1950 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1951 return 0;
1952 }
1953
1954 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00001955 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1956 PathLengthToMember))
1957 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001958 } else if (!MemPtr.Path.empty()) {
1959 // Extend the LValue path with the member pointer's path.
1960 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1961 MemPtr.Path.size() + IncludeMember);
1962
1963 // Walk down to the appropriate base class.
1964 QualType LVType = BO->getLHS()->getType();
1965 if (const PointerType *PT = LVType->getAs<PointerType>())
1966 LVType = PT->getPointeeType();
1967 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1968 assert(RD && "member pointer access on non-class-type expression");
1969 // The first class in the path is that of the lvalue.
1970 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1971 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCall8d59dee2012-05-01 00:38:49 +00001972 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1973 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001974 RD = Base;
1975 }
1976 // Finally cast to the class containing the member.
John McCall8d59dee2012-05-01 00:38:49 +00001977 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1978 return 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00001979 }
1980
1981 // Add the member. Note that we cannot build bound member functions here.
1982 if (IncludeMember) {
John McCall8d59dee2012-05-01 00:38:49 +00001983 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
1984 if (!HandleLValueMember(Info, BO, LV, FD))
1985 return 0;
1986 } else if (const IndirectFieldDecl *IFD =
1987 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
1988 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
1989 return 0;
1990 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00001991 llvm_unreachable("can't construct reference to bound member function");
John McCall8d59dee2012-05-01 00:38:49 +00001992 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00001993 }
1994
1995 return MemPtr.getDecl();
1996}
1997
1998/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
1999/// the provided lvalue, which currently refers to the base object.
2000static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2001 LValue &Result) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002002 SubobjectDesignator &D = Result.Designator;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002003 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002004 return false;
2005
Richard Smithb4e85ed2012-01-06 16:39:00 +00002006 QualType TargetQT = E->getType();
2007 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2008 TargetQT = PT->getPointeeType();
2009
2010 // Check this cast lands within the final derived-to-base subobject path.
2011 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002012 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002013 << D.MostDerivedType << TargetQT;
2014 return false;
2015 }
2016
Richard Smithe24f5fc2011-11-17 22:56:20 +00002017 // Check the type of the final cast. We don't need to check the path,
2018 // since a cast can only be formed if the path is unique.
2019 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002020 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2021 const CXXRecordDecl *FinalType;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002022 if (NewEntriesSize == D.MostDerivedPathLength)
2023 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2024 else
Richard Smithe24f5fc2011-11-17 22:56:20 +00002025 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smithb4e85ed2012-01-06 16:39:00 +00002026 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002027 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smithb4e85ed2012-01-06 16:39:00 +00002028 << D.MostDerivedType << TargetQT;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002029 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00002030 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002031
2032 // Truncate the lvalue to the appropriate derived class.
Richard Smithb4e85ed2012-01-06 16:39:00 +00002033 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smith59efe262011-11-11 04:05:33 +00002034}
2035
Mike Stumpc4c90452009-10-27 22:09:17 +00002036namespace {
Richard Smithd0dccea2011-10-28 22:34:42 +00002037enum EvalStmtResult {
2038 /// Evaluation failed.
2039 ESR_Failed,
2040 /// Hit a 'return' statement.
2041 ESR_Returned,
2042 /// Evaluation succeeded.
2043 ESR_Succeeded
2044};
2045}
2046
2047// Evaluate a statement.
Richard Smith1aa0be82012-03-03 22:46:17 +00002048static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smithd0dccea2011-10-28 22:34:42 +00002049 const Stmt *S) {
2050 switch (S->getStmtClass()) {
2051 default:
2052 return ESR_Failed;
2053
2054 case Stmt::NullStmtClass:
2055 case Stmt::DeclStmtClass:
2056 return ESR_Succeeded;
2057
Richard Smithc1c5f272011-12-13 06:39:58 +00002058 case Stmt::ReturnStmtClass: {
Richard Smithc1c5f272011-12-13 06:39:58 +00002059 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith83587db2012-02-15 02:18:13 +00002060 if (!Evaluate(Result, Info, RetExpr))
Richard Smithc1c5f272011-12-13 06:39:58 +00002061 return ESR_Failed;
2062 return ESR_Returned;
2063 }
Richard Smithd0dccea2011-10-28 22:34:42 +00002064
2065 case Stmt::CompoundStmtClass: {
2066 const CompoundStmt *CS = cast<CompoundStmt>(S);
2067 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2068 BE = CS->body_end(); BI != BE; ++BI) {
2069 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2070 if (ESR != ESR_Succeeded)
2071 return ESR;
2072 }
2073 return ESR_Succeeded;
2074 }
2075 }
2076}
2077
Richard Smith61802452011-12-22 02:22:31 +00002078/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2079/// default constructor. If so, we'll fold it whether or not it's marked as
2080/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2081/// so we need special handling.
2082static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smith51201882011-12-30 21:15:51 +00002083 const CXXConstructorDecl *CD,
2084 bool IsValueInitialization) {
Richard Smith61802452011-12-22 02:22:31 +00002085 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2086 return false;
2087
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002088 // Value-initialization does not call a trivial default constructor, so such a
2089 // call is a core constant expression whether or not the constructor is
2090 // constexpr.
2091 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith80ad52f2013-01-02 11:42:31 +00002092 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith4c3fc9b2012-01-18 05:21:49 +00002093 // FIXME: If DiagDecl is an implicitly-declared special member function,
2094 // we should be much more explicit about why it's not constexpr.
2095 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2096 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2097 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smith61802452011-12-22 02:22:31 +00002098 } else {
2099 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2100 }
2101 }
2102 return true;
2103}
2104
Richard Smithc1c5f272011-12-13 06:39:58 +00002105/// CheckConstexprFunction - Check that a function can be called in a constant
2106/// expression.
2107static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2108 const FunctionDecl *Declaration,
2109 const FunctionDecl *Definition) {
Richard Smith745f5142012-01-27 01:14:48 +00002110 // Potential constant expressions can contain calls to declared, but not yet
2111 // defined, constexpr functions.
2112 if (Info.CheckingPotentialConstantExpression && !Definition &&
2113 Declaration->isConstexpr())
2114 return false;
2115
Richard Smithc1c5f272011-12-13 06:39:58 +00002116 // Can we evaluate this function call?
2117 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2118 return true;
2119
Richard Smith80ad52f2013-01-02 11:42:31 +00002120 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithc1c5f272011-12-13 06:39:58 +00002121 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith099e7f62011-12-19 06:19:21 +00002122 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2123 // should be much more explicit about why it's not constexpr.
Richard Smithc1c5f272011-12-13 06:39:58 +00002124 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2125 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2126 << DiagDecl;
2127 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2128 } else {
2129 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2130 }
2131 return false;
2132}
2133
Richard Smith180f4792011-11-10 06:34:14 +00002134namespace {
Richard Smith1aa0be82012-03-03 22:46:17 +00002135typedef SmallVector<APValue, 8> ArgVector;
Richard Smith180f4792011-11-10 06:34:14 +00002136}
2137
2138/// EvaluateArgs - Evaluate the arguments to a function call.
2139static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2140 EvalInfo &Info) {
Richard Smith745f5142012-01-27 01:14:48 +00002141 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002142 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith745f5142012-01-27 01:14:48 +00002143 I != E; ++I) {
2144 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2145 // If we're checking for a potential constant expression, evaluate all
2146 // initializers even if some of them fail.
2147 if (!Info.keepEvaluatingAfterFailure())
2148 return false;
2149 Success = false;
2150 }
2151 }
2152 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002153}
2154
Richard Smithd0dccea2011-10-28 22:34:42 +00002155/// Evaluate a function call.
Richard Smith745f5142012-01-27 01:14:48 +00002156static bool HandleFunctionCall(SourceLocation CallLoc,
2157 const FunctionDecl *Callee, const LValue *This,
Richard Smithf48fdb02011-12-09 22:58:01 +00002158 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith1aa0be82012-03-03 22:46:17 +00002159 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002160 ArgVector ArgValues(Args.size());
2161 if (!EvaluateArgs(Args, ArgValues, Info))
2162 return false;
Richard Smithd0dccea2011-10-28 22:34:42 +00002163
Richard Smith745f5142012-01-27 01:14:48 +00002164 if (!Info.CheckCallLimit(CallLoc))
2165 return false;
2166
2167 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smithd0dccea2011-10-28 22:34:42 +00002168 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2169}
2170
Richard Smith180f4792011-11-10 06:34:14 +00002171/// Evaluate a constructor call.
Richard Smith745f5142012-01-27 01:14:48 +00002172static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smith59efe262011-11-11 04:05:33 +00002173 ArrayRef<const Expr*> Args,
Richard Smith180f4792011-11-10 06:34:14 +00002174 const CXXConstructorDecl *Definition,
Richard Smith51201882011-12-30 21:15:51 +00002175 EvalInfo &Info, APValue &Result) {
Richard Smith180f4792011-11-10 06:34:14 +00002176 ArgVector ArgValues(Args.size());
2177 if (!EvaluateArgs(Args, ArgValues, Info))
2178 return false;
2179
Richard Smith745f5142012-01-27 01:14:48 +00002180 if (!Info.CheckCallLimit(CallLoc))
2181 return false;
2182
Richard Smith86c3ae42012-02-13 03:54:03 +00002183 const CXXRecordDecl *RD = Definition->getParent();
2184 if (RD->getNumVBases()) {
2185 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2186 return false;
2187 }
2188
Richard Smith745f5142012-01-27 01:14:48 +00002189 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smith180f4792011-11-10 06:34:14 +00002190
2191 // If it's a delegating constructor, just delegate.
2192 if (Definition->isDelegatingConstructor()) {
2193 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith83587db2012-02-15 02:18:13 +00002194 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smith180f4792011-11-10 06:34:14 +00002195 }
2196
Richard Smith610a60c2012-01-10 04:32:03 +00002197 // For a trivial copy or move constructor, perform an APValue copy. This is
2198 // essential for unions, where the operations performed by the constructor
2199 // cannot be represented by ctor-initializers.
Richard Smith610a60c2012-01-10 04:32:03 +00002200 if (Definition->isDefaulted() &&
Douglas Gregorf6cfe8b2012-02-24 07:55:51 +00002201 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2202 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith610a60c2012-01-10 04:32:03 +00002203 LValue RHS;
Richard Smith1aa0be82012-03-03 22:46:17 +00002204 RHS.setFrom(Info.Ctx, ArgValues[0]);
2205 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2206 RHS, Result);
Richard Smith610a60c2012-01-10 04:32:03 +00002207 }
2208
2209 // Reserve space for the struct members.
Richard Smith51201882011-12-30 21:15:51 +00002210 if (!RD->isUnion() && Result.isUninit())
Richard Smith180f4792011-11-10 06:34:14 +00002211 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2212 std::distance(RD->field_begin(), RD->field_end()));
2213
John McCall8d59dee2012-05-01 00:38:49 +00002214 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00002215 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2216
Richard Smith745f5142012-01-27 01:14:48 +00002217 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00002218 unsigned BasesSeen = 0;
2219#ifndef NDEBUG
2220 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2221#endif
2222 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2223 E = Definition->init_end(); I != E; ++I) {
Richard Smith745f5142012-01-27 01:14:48 +00002224 LValue Subobject = This;
2225 APValue *Value = &Result;
2226
2227 // Determine the subobject to initialize.
Richard Smith180f4792011-11-10 06:34:14 +00002228 if ((*I)->isBaseInitializer()) {
2229 QualType BaseType((*I)->getBaseClass(), 0);
2230#ifndef NDEBUG
2231 // Non-virtual base classes are initialized in the order in the class
Richard Smith86c3ae42012-02-13 03:54:03 +00002232 // definition. We have already checked for virtual base classes.
Richard Smith180f4792011-11-10 06:34:14 +00002233 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2234 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2235 "base class initializers not in expected order");
2236 ++BaseIt;
2237#endif
John McCall8d59dee2012-05-01 00:38:49 +00002238 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2239 BaseType->getAsCXXRecordDecl(), &Layout))
2240 return false;
Richard Smith745f5142012-01-27 01:14:48 +00002241 Value = &Result.getStructBase(BasesSeen++);
Richard Smith180f4792011-11-10 06:34:14 +00002242 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCall8d59dee2012-05-01 00:38:49 +00002243 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2244 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002245 if (RD->isUnion()) {
2246 Result = APValue(FD);
Richard Smith745f5142012-01-27 01:14:48 +00002247 Value = &Result.getUnionValue();
2248 } else {
2249 Value = &Result.getStructField(FD->getFieldIndex());
2250 }
Richard Smithd9b02e72012-01-25 22:15:11 +00002251 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smithd9b02e72012-01-25 22:15:11 +00002252 // Walk the indirect field decl's chain to find the object to initialize,
2253 // and make sure we've initialized every step along it.
2254 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2255 CE = IFD->chain_end();
2256 C != CE; ++C) {
2257 FieldDecl *FD = cast<FieldDecl>(*C);
2258 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2259 // Switch the union field if it differs. This happens if we had
2260 // preceding zero-initialization, and we're now initializing a union
2261 // subobject other than the first.
2262 // FIXME: In this case, the values of the other subobjects are
2263 // specified, since zero-initialization sets all padding bits to zero.
2264 if (Value->isUninit() ||
2265 (Value->isUnion() && Value->getUnionField() != FD)) {
2266 if (CD->isUnion())
2267 *Value = APValue(FD);
2268 else
2269 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2270 std::distance(CD->field_begin(), CD->field_end()));
2271 }
John McCall8d59dee2012-05-01 00:38:49 +00002272 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2273 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002274 if (CD->isUnion())
2275 Value = &Value->getUnionValue();
2276 else
2277 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smithd9b02e72012-01-25 22:15:11 +00002278 }
Richard Smith180f4792011-11-10 06:34:14 +00002279 } else {
Richard Smithd9b02e72012-01-25 22:15:11 +00002280 llvm_unreachable("unknown base initializer kind");
Richard Smith180f4792011-11-10 06:34:14 +00002281 }
Richard Smith745f5142012-01-27 01:14:48 +00002282
Richard Smith83587db2012-02-15 02:18:13 +00002283 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2284 (*I)->isBaseInitializer()
Richard Smith745f5142012-01-27 01:14:48 +00002285 ? CCEK_Constant : CCEK_MemberInit)) {
2286 // If we're checking for a potential constant expression, evaluate all
2287 // initializers even if some of them fail.
2288 if (!Info.keepEvaluatingAfterFailure())
2289 return false;
2290 Success = false;
2291 }
Richard Smith180f4792011-11-10 06:34:14 +00002292 }
2293
Richard Smith745f5142012-01-27 01:14:48 +00002294 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00002295}
2296
Eli Friedman4efaa272008-11-12 09:44:48 +00002297//===----------------------------------------------------------------------===//
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002298// Generic Evaluation
2299//===----------------------------------------------------------------------===//
2300namespace {
2301
Richard Smithf48fdb02011-12-09 22:58:01 +00002302// FIXME: RetTy is always bool. Remove it.
2303template <class Derived, typename RetTy=bool>
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002304class ExprEvaluatorBase
2305 : public ConstStmtVisitor<Derived, RetTy> {
2306private:
Richard Smith1aa0be82012-03-03 22:46:17 +00002307 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002308 return static_cast<Derived*>(this)->Success(V, E);
2309 }
Richard Smith51201882011-12-30 21:15:51 +00002310 RetTy DerivedZeroInitialization(const Expr *E) {
2311 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002312 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002313
Richard Smith74e1ad92012-02-16 02:46:34 +00002314 // Check whether a conditional operator with a non-constant condition is a
2315 // potential constant expression. If neither arm is a potential constant
2316 // expression, then the conditional operator is not either.
2317 template<typename ConditionalOperator>
2318 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2319 assert(Info.CheckingPotentialConstantExpression);
2320
2321 // Speculatively evaluate both arms.
2322 {
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002323 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith74e1ad92012-02-16 02:46:34 +00002324 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2325
2326 StmtVisitorTy::Visit(E->getFalseExpr());
2327 if (Diag.empty())
2328 return;
2329
2330 Diag.clear();
2331 StmtVisitorTy::Visit(E->getTrueExpr());
2332 if (Diag.empty())
2333 return;
2334 }
2335
2336 Error(E, diag::note_constexpr_conditional_never_const);
2337 }
2338
2339
2340 template<typename ConditionalOperator>
2341 bool HandleConditionalOperator(const ConditionalOperator *E) {
2342 bool BoolResult;
2343 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2344 if (Info.CheckingPotentialConstantExpression)
2345 CheckPotentialConstantConditional(E);
2346 return false;
2347 }
2348
2349 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2350 return StmtVisitorTy::Visit(EvalExpr);
2351 }
2352
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002353protected:
2354 EvalInfo &Info;
2355 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2356 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2357
Richard Smithdd1f29b2011-12-12 09:28:41 +00002358 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002359 return Info.CCEDiag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002360 }
2361
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00002362 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2363
2364public:
2365 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2366
2367 EvalInfo &getEvalInfo() { return Info; }
2368
Richard Smithf48fdb02011-12-09 22:58:01 +00002369 /// Report an evaluation error. This should only be called when an error is
2370 /// first discovered. When propagating an error, just return false.
2371 bool Error(const Expr *E, diag::kind D) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00002372 Info.Diag(E, D);
Richard Smithf48fdb02011-12-09 22:58:01 +00002373 return false;
2374 }
2375 bool Error(const Expr *E) {
2376 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2377 }
2378
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002379 RetTy VisitStmt(const Stmt *) {
David Blaikieb219cfc2011-09-23 05:06:16 +00002380 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002381 }
2382 RetTy VisitExpr(const Expr *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002383 return Error(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002384 }
2385
2386 RetTy VisitParenExpr(const ParenExpr *E)
2387 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2388 RetTy VisitUnaryExtension(const UnaryOperator *E)
2389 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2390 RetTy VisitUnaryPlus(const UnaryOperator *E)
2391 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2392 RetTy VisitChooseExpr(const ChooseExpr *E)
2393 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2394 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2395 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall91a57552011-07-15 05:09:51 +00002396 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2397 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smith3d75ca82011-11-09 02:12:41 +00002398 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2399 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smithbc6abe92011-12-19 22:12:41 +00002400 // We cannot create any objects for which cleanups are required, so there is
2401 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2402 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2403 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002404
Richard Smithc216a012011-12-12 12:46:16 +00002405 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2406 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2407 return static_cast<Derived*>(this)->VisitCastExpr(E);
2408 }
2409 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2410 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2411 return static_cast<Derived*>(this)->VisitCastExpr(E);
2412 }
2413
Richard Smithe24f5fc2011-11-17 22:56:20 +00002414 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2415 switch (E->getOpcode()) {
2416 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00002417 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002418
2419 case BO_Comma:
2420 VisitIgnoredValue(E->getLHS());
2421 return StmtVisitorTy::Visit(E->getRHS());
2422
2423 case BO_PtrMemD:
2424 case BO_PtrMemI: {
2425 LValue Obj;
2426 if (!HandleMemberPointerAccess(Info, E, Obj))
2427 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002428 APValue Result;
Richard Smithf48fdb02011-12-09 22:58:01 +00002429 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smithe24f5fc2011-11-17 22:56:20 +00002430 return false;
2431 return DerivedSuccess(Result, E);
2432 }
2433 }
2434 }
2435
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002436 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002437 // Evaluate and cache the common expression. We treat it as a temporary,
2438 // even though it's not quite the same thing.
2439 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2440 Info, E->getCommon()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002441 return false;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002442
Richard Smith74e1ad92012-02-16 02:46:34 +00002443 return HandleConditionalOperator(E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002444 }
2445
2446 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smithf15fda02012-02-02 01:16:57 +00002447 bool IsBcpCall = false;
2448 // If the condition (ignoring parens) is a __builtin_constant_p call,
2449 // the result is a constant expression if it can be folded without
2450 // side-effects. This is an important GNU extension. See GCC PR38377
2451 // for discussion.
2452 if (const CallExpr *CallCE =
2453 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2454 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2455 IsBcpCall = true;
2456
2457 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2458 // constant expression; we can't check whether it's potentially foldable.
2459 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2460 return false;
2461
2462 FoldConstant Fold(Info);
2463
Richard Smith74e1ad92012-02-16 02:46:34 +00002464 if (!HandleConditionalOperator(E))
Richard Smithf15fda02012-02-02 01:16:57 +00002465 return false;
2466
2467 if (IsBcpCall)
2468 Fold.Fold(Info);
2469
2470 return true;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002471 }
2472
2473 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smithe92b1f42012-06-26 08:12:11 +00002474 APValue &Value = Info.CurrentCall->Temporaries[E];
2475 if (Value.isUninit()) {
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002476 const Expr *Source = E->getSourceExpr();
2477 if (!Source)
Richard Smithf48fdb02011-12-09 22:58:01 +00002478 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002479 if (Source == E) { // sanity checking.
2480 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf48fdb02011-12-09 22:58:01 +00002481 return Error(E);
Argyrios Kyrtzidis42786832011-12-09 02:44:48 +00002482 }
2483 return StmtVisitorTy::Visit(Source);
2484 }
Richard Smithe92b1f42012-06-26 08:12:11 +00002485 return DerivedSuccess(Value, E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002486 }
Richard Smithf10d9172011-10-11 21:43:33 +00002487
Richard Smithd0dccea2011-10-28 22:34:42 +00002488 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00002489 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smithd0dccea2011-10-28 22:34:42 +00002490 QualType CalleeType = Callee->getType();
2491
Richard Smithd0dccea2011-10-28 22:34:42 +00002492 const FunctionDecl *FD = 0;
Richard Smith59efe262011-11-11 04:05:33 +00002493 LValue *This = 0, ThisVal;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00002494 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith86c3ae42012-02-13 03:54:03 +00002495 bool HasQualifier = false;
Richard Smith6c957872011-11-10 09:31:24 +00002496
Richard Smith59efe262011-11-11 04:05:33 +00002497 // Extract function decl and 'this' pointer from the callee.
2498 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002499 const ValueDecl *Member = 0;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002500 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2501 // Explicit bound member calls, such as x.f() or p->g();
2502 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002503 return false;
2504 Member = ME->getMemberDecl();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002505 This = &ThisVal;
Richard Smith86c3ae42012-02-13 03:54:03 +00002506 HasQualifier = ME->hasQualifier();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002507 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2508 // Indirect bound member calls ('.*' or '->*').
Richard Smithf48fdb02011-12-09 22:58:01 +00002509 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2510 if (!Member) return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002511 This = &ThisVal;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002512 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002513 return Error(Callee);
2514
2515 FD = dyn_cast<FunctionDecl>(Member);
2516 if (!FD)
2517 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002518 } else if (CalleeType->isFunctionPointerType()) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002519 LValue Call;
2520 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00002521 return false;
Richard Smith59efe262011-11-11 04:05:33 +00002522
Richard Smithb4e85ed2012-01-06 16:39:00 +00002523 if (!Call.getLValueOffset().isZero())
Richard Smithf48fdb02011-12-09 22:58:01 +00002524 return Error(Callee);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002525 FD = dyn_cast_or_null<FunctionDecl>(
2526 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smith59efe262011-11-11 04:05:33 +00002527 if (!FD)
Richard Smithf48fdb02011-12-09 22:58:01 +00002528 return Error(Callee);
Richard Smith59efe262011-11-11 04:05:33 +00002529
2530 // Overloaded operator calls to member functions are represented as normal
2531 // calls with '*this' as the first argument.
2532 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2533 if (MD && !MD->isStatic()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00002534 // FIXME: When selecting an implicit conversion for an overloaded
2535 // operator delete, we sometimes try to evaluate calls to conversion
2536 // operators without a 'this' parameter!
2537 if (Args.empty())
2538 return Error(E);
2539
Richard Smith59efe262011-11-11 04:05:33 +00002540 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2541 return false;
2542 This = &ThisVal;
2543 Args = Args.slice(1);
2544 }
2545
2546 // Don't call function pointers which have been cast to some other type.
2547 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf48fdb02011-12-09 22:58:01 +00002548 return Error(E);
Richard Smith59efe262011-11-11 04:05:33 +00002549 } else
Richard Smithf48fdb02011-12-09 22:58:01 +00002550 return Error(E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002551
Richard Smithb04035a2012-02-01 02:39:43 +00002552 if (This && !This->checkSubobject(Info, E, CSK_This))
2553 return false;
2554
Richard Smith86c3ae42012-02-13 03:54:03 +00002555 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2556 // calls to such functions in constant expressions.
2557 if (This && !HasQualifier &&
2558 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2559 return Error(E, diag::note_constexpr_virtual_call);
2560
Richard Smithc1c5f272011-12-13 06:39:58 +00002561 const FunctionDecl *Definition = 0;
Richard Smithd0dccea2011-10-28 22:34:42 +00002562 Stmt *Body = FD->getBody(Definition);
Richard Smith1aa0be82012-03-03 22:46:17 +00002563 APValue Result;
Richard Smithd0dccea2011-10-28 22:34:42 +00002564
Richard Smithc1c5f272011-12-13 06:39:58 +00002565 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith745f5142012-01-27 01:14:48 +00002566 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2567 Info, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00002568 return false;
2569
Richard Smith83587db2012-02-15 02:18:13 +00002570 return DerivedSuccess(Result, E);
Richard Smithd0dccea2011-10-28 22:34:42 +00002571 }
2572
Richard Smithc49bd112011-10-28 17:51:58 +00002573 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2574 return StmtVisitorTy::Visit(E->getInitializer());
2575 }
Richard Smithf10d9172011-10-11 21:43:33 +00002576 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman71523d62012-01-03 23:54:05 +00002577 if (E->getNumInits() == 0)
2578 return DerivedZeroInitialization(E);
2579 if (E->getNumInits() == 1)
2580 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf48fdb02011-12-09 22:58:01 +00002581 return Error(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002582 }
2583 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002584 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002585 }
2586 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002587 return DerivedZeroInitialization(E);
Richard Smithf10d9172011-10-11 21:43:33 +00002588 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002589 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00002590 return DerivedZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002591 }
Richard Smithf10d9172011-10-11 21:43:33 +00002592
Richard Smith180f4792011-11-10 06:34:14 +00002593 /// A member expression where the object is a prvalue is itself a prvalue.
2594 RetTy VisitMemberExpr(const MemberExpr *E) {
2595 assert(!E->isArrow() && "missing call to bound member function?");
2596
Richard Smith1aa0be82012-03-03 22:46:17 +00002597 APValue Val;
Richard Smith180f4792011-11-10 06:34:14 +00002598 if (!Evaluate(Val, Info, E->getBase()))
2599 return false;
2600
2601 QualType BaseTy = E->getBase()->getType();
2602
2603 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf48fdb02011-12-09 22:58:01 +00002604 if (!FD) return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00002605 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek890f0f12012-08-23 20:46:57 +00002606 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smith180f4792011-11-10 06:34:14 +00002607 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2608
Richard Smithb4e85ed2012-01-06 16:39:00 +00002609 SubobjectDesignator Designator(BaseTy);
2610 Designator.addDeclUnchecked(FD);
Richard Smith180f4792011-11-10 06:34:14 +00002611
Richard Smithf48fdb02011-12-09 22:58:01 +00002612 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smith180f4792011-11-10 06:34:14 +00002613 DerivedSuccess(Val, E);
2614 }
2615
Richard Smithc49bd112011-10-28 17:51:58 +00002616 RetTy VisitCastExpr(const CastExpr *E) {
2617 switch (E->getCastKind()) {
2618 default:
2619 break;
2620
David Chisnall7a7ee302012-01-16 17:27:18 +00002621 case CK_AtomicToNonAtomic:
2622 case CK_NonAtomicToAtomic:
Richard Smithc49bd112011-10-28 17:51:58 +00002623 case CK_NoOp:
Richard Smith7d580a42012-01-17 21:17:26 +00002624 case CK_UserDefinedConversion:
Richard Smithc49bd112011-10-28 17:51:58 +00002625 return StmtVisitorTy::Visit(E->getSubExpr());
2626
2627 case CK_LValueToRValue: {
2628 LValue LVal;
Richard Smithf48fdb02011-12-09 22:58:01 +00002629 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2630 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00002631 APValue RVal;
Richard Smith9ec71972012-02-05 01:23:16 +00002632 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2633 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2634 LVal, RVal))
Richard Smithf48fdb02011-12-09 22:58:01 +00002635 return false;
2636 return DerivedSuccess(RVal, E);
Richard Smithc49bd112011-10-28 17:51:58 +00002637 }
2638 }
2639
Richard Smithf48fdb02011-12-09 22:58:01 +00002640 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002641 }
2642
Richard Smith8327fad2011-10-24 18:44:57 +00002643 /// Visit a value which is evaluated, but whose value is ignored.
2644 void VisitIgnoredValue(const Expr *E) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002645 APValue Scratch;
Richard Smith8327fad2011-10-24 18:44:57 +00002646 if (!Evaluate(Scratch, Info, E))
2647 Info.EvalStatus.HasSideEffects = true;
2648 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002649};
2650
2651}
2652
2653//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00002654// Common base class for lvalue and temporary evaluation.
2655//===----------------------------------------------------------------------===//
2656namespace {
2657template<class Derived>
2658class LValueExprEvaluatorBase
2659 : public ExprEvaluatorBase<Derived, bool> {
2660protected:
2661 LValue &Result;
2662 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2663 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2664
2665 bool Success(APValue::LValueBase B) {
2666 Result.set(B);
2667 return true;
2668 }
2669
2670public:
2671 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2672 ExprEvaluatorBaseTy(Info), Result(Result) {}
2673
Richard Smith1aa0be82012-03-03 22:46:17 +00002674 bool Success(const APValue &V, const Expr *E) {
2675 Result.setFrom(this->Info.Ctx, V);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002676 return true;
2677 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002678
Richard Smithe24f5fc2011-11-17 22:56:20 +00002679 bool VisitMemberExpr(const MemberExpr *E) {
2680 // Handle non-static data members.
2681 QualType BaseTy;
2682 if (E->isArrow()) {
2683 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2684 return false;
Ted Kremenek890f0f12012-08-23 20:46:57 +00002685 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithc1c5f272011-12-13 06:39:58 +00002686 } else if (E->getBase()->isRValue()) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00002687 assert(E->getBase()->getType()->isRecordType());
Richard Smithc1c5f272011-12-13 06:39:58 +00002688 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2689 return false;
2690 BaseTy = E->getBase()->getType();
Richard Smithe24f5fc2011-11-17 22:56:20 +00002691 } else {
2692 if (!this->Visit(E->getBase()))
2693 return false;
2694 BaseTy = E->getBase()->getType();
2695 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00002696
Richard Smithd9b02e72012-01-25 22:15:11 +00002697 const ValueDecl *MD = E->getMemberDecl();
2698 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2699 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2700 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2701 (void)BaseTy;
John McCall8d59dee2012-05-01 00:38:49 +00002702 if (!HandleLValueMember(this->Info, E, Result, FD))
2703 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002704 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCall8d59dee2012-05-01 00:38:49 +00002705 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2706 return false;
Richard Smithd9b02e72012-01-25 22:15:11 +00002707 } else
2708 return this->Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002709
Richard Smithd9b02e72012-01-25 22:15:11 +00002710 if (MD->getType()->isReferenceType()) {
Richard Smith1aa0be82012-03-03 22:46:17 +00002711 APValue RefValue;
Richard Smithd9b02e72012-01-25 22:15:11 +00002712 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smithe24f5fc2011-11-17 22:56:20 +00002713 RefValue))
2714 return false;
2715 return Success(RefValue, E);
2716 }
2717 return true;
2718 }
2719
2720 bool VisitBinaryOperator(const BinaryOperator *E) {
2721 switch (E->getOpcode()) {
2722 default:
2723 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2724
2725 case BO_PtrMemD:
2726 case BO_PtrMemI:
2727 return HandleMemberPointerAccess(this->Info, E, Result);
2728 }
2729 }
2730
2731 bool VisitCastExpr(const CastExpr *E) {
2732 switch (E->getCastKind()) {
2733 default:
2734 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2735
2736 case CK_DerivedToBase:
2737 case CK_UncheckedDerivedToBase: {
2738 if (!this->Visit(E->getSubExpr()))
2739 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002740
2741 // Now figure out the necessary offset to add to the base LV to get from
2742 // the derived class to the base class.
2743 QualType Type = E->getSubExpr()->getType();
2744
2745 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2746 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00002747 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smithe24f5fc2011-11-17 22:56:20 +00002748 *PathI))
2749 return false;
2750 Type = (*PathI)->getType();
2751 }
2752
2753 return true;
2754 }
2755 }
2756 }
2757};
2758}
2759
2760//===----------------------------------------------------------------------===//
Eli Friedman4efaa272008-11-12 09:44:48 +00002761// LValue Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00002762//
2763// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2764// function designators (in C), decl references to void objects (in C), and
2765// temporaries (if building with -Wno-address-of-temporary).
2766//
2767// LValue evaluation produces values comprising a base expression of one of the
2768// following types:
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002769// - Declarations
2770// * VarDecl
2771// * FunctionDecl
2772// - Literals
Richard Smithc49bd112011-10-28 17:51:58 +00002773// * CompoundLiteralExpr in C
2774// * StringLiteral
Richard Smith47d21452011-12-27 12:18:28 +00002775// * CXXTypeidExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002776// * PredefinedExpr
Richard Smith180f4792011-11-10 06:34:14 +00002777// * ObjCStringLiteralExpr
Richard Smithc49bd112011-10-28 17:51:58 +00002778// * ObjCEncodeExpr
2779// * AddrLabelExpr
2780// * BlockExpr
2781// * CallExpr for a MakeStringConstant builtin
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002782// - Locals and temporaries
Richard Smith83587db2012-02-15 02:18:13 +00002783// * Any Expr, with a CallIndex indicating the function in which the temporary
2784// was evaluated.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002785// plus an offset in bytes.
Eli Friedman4efaa272008-11-12 09:44:48 +00002786//===----------------------------------------------------------------------===//
2787namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002788class LValueExprEvaluator
Richard Smithe24f5fc2011-11-17 22:56:20 +00002789 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman4efaa272008-11-12 09:44:48 +00002790public:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002791 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2792 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00002793
Richard Smithc49bd112011-10-28 17:51:58 +00002794 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2795
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002796 bool VisitDeclRefExpr(const DeclRefExpr *E);
2797 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smithbd552ef2011-10-31 05:52:43 +00002798 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002799 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2800 bool VisitMemberExpr(const MemberExpr *E);
2801 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2802 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith47d21452011-12-27 12:18:28 +00002803 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichete275a182012-04-16 04:08:35 +00002804 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002805 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2806 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith86024012012-02-18 22:04:06 +00002807 bool VisitUnaryReal(const UnaryOperator *E);
2808 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002809
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002810 bool VisitCastExpr(const CastExpr *E) {
Anders Carlsson26bc2202009-10-03 16:30:22 +00002811 switch (E->getCastKind()) {
2812 default:
Richard Smithe24f5fc2011-11-17 22:56:20 +00002813 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002814
Eli Friedmandb924222011-10-11 00:13:24 +00002815 case CK_LValueBitCast:
Richard Smithc216a012011-12-12 12:46:16 +00002816 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith0a3bdb62011-11-04 02:25:55 +00002817 if (!Visit(E->getSubExpr()))
2818 return false;
2819 Result.Designator.setInvalid();
2820 return true;
Eli Friedmandb924222011-10-11 00:13:24 +00002821
Richard Smithe24f5fc2011-11-17 22:56:20 +00002822 case CK_BaseToDerived:
Richard Smith180f4792011-11-10 06:34:14 +00002823 if (!Visit(E->getSubExpr()))
2824 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00002825 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlsson26bc2202009-10-03 16:30:22 +00002826 }
2827 }
Eli Friedman4efaa272008-11-12 09:44:48 +00002828};
2829} // end anonymous namespace
2830
Richard Smithc49bd112011-10-28 17:51:58 +00002831/// Evaluate an expression as an lvalue. This can be legitimately called on
2832/// expressions which are not glvalues, in a few cases:
2833/// * function designators in C,
2834/// * "extern void" objects,
2835/// * temporaries, if building with -Wno-address-of-temporary.
John McCallefdb83e2010-05-07 21:00:08 +00002836static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00002837 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2838 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2839 "can't evaluate expression as an lvalue");
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002840 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002841}
2842
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002843bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002844 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2845 return Success(FD);
2846 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smithc49bd112011-10-28 17:51:58 +00002847 return VisitVarDecl(E, VD);
2848 return Error(E);
2849}
Richard Smith436c8892011-10-24 23:14:33 +00002850
Richard Smithc49bd112011-10-28 17:51:58 +00002851bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smith177dce72011-11-01 16:57:24 +00002852 if (!VD->getType()->isReferenceType()) {
2853 if (isa<ParmVarDecl>(VD)) {
Richard Smith83587db2012-02-15 02:18:13 +00002854 Result.set(VD, Info.CurrentCall->Index);
Richard Smith177dce72011-11-01 16:57:24 +00002855 return true;
2856 }
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002857 return Success(VD);
Richard Smith177dce72011-11-01 16:57:24 +00002858 }
Eli Friedman50c39ea2009-05-27 06:04:58 +00002859
Richard Smith1aa0be82012-03-03 22:46:17 +00002860 APValue V;
Richard Smithf48fdb02011-12-09 22:58:01 +00002861 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2862 return false;
2863 return Success(V, E);
Anders Carlsson35873c42008-11-24 04:41:22 +00002864}
2865
Richard Smithbd552ef2011-10-31 05:52:43 +00002866bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2867 const MaterializeTemporaryExpr *E) {
Jordan Rose1fd1e282013-04-11 00:58:58 +00002868 if (E->getType()->isRecordType())
2869 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smithe24f5fc2011-11-17 22:56:20 +00002870
Richard Smith83587db2012-02-15 02:18:13 +00002871 Result.set(E, Info.CurrentCall->Index);
Jordan Rose1fd1e282013-04-11 00:58:58 +00002872 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2873 Result, E->GetTemporaryExpr());
Richard Smithbd552ef2011-10-31 05:52:43 +00002874}
2875
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002876bool
2877LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002878 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2879 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2880 // only see this when folding in C, so there's no standard to follow here.
John McCallefdb83e2010-05-07 21:00:08 +00002881 return Success(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002882}
2883
Richard Smith47d21452011-12-27 12:18:28 +00002884bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith9be36ab2012-10-17 23:52:07 +00002885 if (!E->isPotentiallyEvaluated())
Richard Smith47d21452011-12-27 12:18:28 +00002886 return Success(E);
Richard Smith9be36ab2012-10-17 23:52:07 +00002887
2888 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
2889 << E->getExprOperand()->getType()
2890 << E->getExprOperand()->getSourceRange();
2891 return false;
Richard Smith47d21452011-12-27 12:18:28 +00002892}
2893
Francois Pichete275a182012-04-16 04:08:35 +00002894bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2895 return Success(E);
2896}
2897
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002898bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002899 // Handle static data members.
2900 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2901 VisitIgnoredValue(E->getBase());
2902 return VisitVarDecl(E, VD);
2903 }
2904
Richard Smithd0dccea2011-10-28 22:34:42 +00002905 // Handle static member functions.
2906 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2907 if (MD->isStatic()) {
2908 VisitIgnoredValue(E->getBase());
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002909 return Success(MD);
Richard Smithd0dccea2011-10-28 22:34:42 +00002910 }
2911 }
2912
Richard Smith180f4792011-11-10 06:34:14 +00002913 // Handle non-static data members.
Richard Smithe24f5fc2011-11-17 22:56:20 +00002914 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00002915}
2916
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002917bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00002918 // FIXME: Deal with vectors as array subscript bases.
2919 if (E->getBase()->getType()->isVectorType())
Richard Smithf48fdb02011-12-09 22:58:01 +00002920 return Error(E);
Richard Smithc49bd112011-10-28 17:51:58 +00002921
Anders Carlsson3068d112008-11-16 19:01:22 +00002922 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002923 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00002924
Anders Carlsson3068d112008-11-16 19:01:22 +00002925 APSInt Index;
2926 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCallefdb83e2010-05-07 21:00:08 +00002927 return false;
Richard Smith180f4792011-11-10 06:34:14 +00002928 int64_t IndexValue
2929 = Index.isSigned() ? Index.getSExtValue()
2930 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson3068d112008-11-16 19:01:22 +00002931
Richard Smithb4e85ed2012-01-06 16:39:00 +00002932 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson3068d112008-11-16 19:01:22 +00002933}
Eli Friedman4efaa272008-11-12 09:44:48 +00002934
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002935bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCallefdb83e2010-05-07 21:00:08 +00002936 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedmane8761c82009-02-20 01:57:15 +00002937}
2938
Richard Smith86024012012-02-18 22:04:06 +00002939bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2940 if (!Visit(E->getSubExpr()))
2941 return false;
2942 // __real is a no-op on scalar lvalues.
2943 if (E->getSubExpr()->getType()->isAnyComplexType())
2944 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
2945 return true;
2946}
2947
2948bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
2949 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
2950 "lvalue __imag__ on scalar?");
2951 if (!Visit(E->getSubExpr()))
2952 return false;
2953 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
2954 return true;
2955}
2956
Eli Friedman4efaa272008-11-12 09:44:48 +00002957//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002958// Pointer Evaluation
2959//===----------------------------------------------------------------------===//
2960
Anders Carlssonc754aa62008-07-08 05:13:58 +00002961namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00002962class PointerExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002963 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCallefdb83e2010-05-07 21:00:08 +00002964 LValue &Result;
2965
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002966 bool Success(const Expr *E) {
Richard Smith1bf9a9e2011-11-12 22:28:03 +00002967 Result.set(E);
John McCallefdb83e2010-05-07 21:00:08 +00002968 return true;
2969 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002970public:
Mike Stump1eb44332009-09-09 15:08:12 +00002971
John McCallefdb83e2010-05-07 21:00:08 +00002972 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002973 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00002974
Richard Smith1aa0be82012-03-03 22:46:17 +00002975 bool Success(const APValue &V, const Expr *E) {
2976 Result.setFrom(Info.Ctx, V);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002977 return true;
2978 }
Richard Smith51201882011-12-30 21:15:51 +00002979 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00002980 return Success((Expr*)0);
2981 }
Anders Carlsson2bad1682008-07-08 14:30:00 +00002982
John McCallefdb83e2010-05-07 21:00:08 +00002983 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002984 bool VisitCastExpr(const CastExpr* E);
John McCallefdb83e2010-05-07 21:00:08 +00002985 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002986 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCallefdb83e2010-05-07 21:00:08 +00002987 { return Success(E); }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002988 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremenekebcb57a2012-03-06 20:05:56 +00002989 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002990 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCallefdb83e2010-05-07 21:00:08 +00002991 { return Success(E); }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00002992 bool VisitCallExpr(const CallExpr *E);
2993 bool VisitBlockExpr(const BlockExpr *E) {
John McCall469a1eb2011-02-02 13:00:07 +00002994 if (!E->getBlockDecl()->hasCaptures())
John McCallefdb83e2010-05-07 21:00:08 +00002995 return Success(E);
Richard Smithf48fdb02011-12-09 22:58:01 +00002996 return Error(E);
Mike Stumpb83d2872009-02-19 22:01:56 +00002997 }
Richard Smith180f4792011-11-10 06:34:14 +00002998 bool VisitCXXThisExpr(const CXXThisExpr *E) {
2999 if (!Info.CurrentCall->This)
Richard Smithf48fdb02011-12-09 22:58:01 +00003000 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003001 Result = *Info.CurrentCall->This;
3002 return true;
3003 }
John McCall56ca35d2011-02-17 10:25:35 +00003004
Eli Friedmanba98d6b2009-03-23 04:56:01 +00003005 // FIXME: Missing: @protocol, @selector
Anders Carlsson650c92f2008-07-08 15:34:11 +00003006};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003007} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00003008
John McCallefdb83e2010-05-07 21:00:08 +00003009static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003010 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003011 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003012}
3013
John McCallefdb83e2010-05-07 21:00:08 +00003014bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCall2de56d12010-08-25 11:45:40 +00003015 if (E->getOpcode() != BO_Add &&
3016 E->getOpcode() != BO_Sub)
Richard Smithe24f5fc2011-11-17 22:56:20 +00003017 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003018
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003019 const Expr *PExp = E->getLHS();
3020 const Expr *IExp = E->getRHS();
3021 if (IExp->getType()->isPointerType())
3022 std::swap(PExp, IExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003023
Richard Smith745f5142012-01-27 01:14:48 +00003024 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3025 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCallefdb83e2010-05-07 21:00:08 +00003026 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00003027
John McCallefdb83e2010-05-07 21:00:08 +00003028 llvm::APSInt Offset;
Richard Smith745f5142012-01-27 01:14:48 +00003029 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCallefdb83e2010-05-07 21:00:08 +00003030 return false;
3031 int64_t AdditionalOffset
3032 = Offset.isSigned() ? Offset.getSExtValue()
3033 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith0a3bdb62011-11-04 02:25:55 +00003034 if (E->getOpcode() == BO_Sub)
3035 AdditionalOffset = -AdditionalOffset;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003036
Ted Kremenek890f0f12012-08-23 20:46:57 +00003037 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithb4e85ed2012-01-06 16:39:00 +00003038 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3039 AdditionalOffset);
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003040}
Eli Friedman4efaa272008-11-12 09:44:48 +00003041
John McCallefdb83e2010-05-07 21:00:08 +00003042bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3043 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003044}
Mike Stump1eb44332009-09-09 15:08:12 +00003045
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003046bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3047 const Expr* SubExpr = E->getSubExpr();
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003048
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003049 switch (E->getCastKind()) {
3050 default:
3051 break;
3052
John McCall2de56d12010-08-25 11:45:40 +00003053 case CK_BitCast:
John McCall1d9b3b22011-09-09 05:25:32 +00003054 case CK_CPointerToObjCPointerCast:
3055 case CK_BlockPointerToObjCPointerCast:
John McCall2de56d12010-08-25 11:45:40 +00003056 case CK_AnyPointerToBlockPointerCast:
Richard Smith28c1ce72012-01-15 03:25:41 +00003057 if (!Visit(SubExpr))
3058 return false;
Richard Smithc216a012011-12-12 12:46:16 +00003059 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3060 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3061 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003062 if (!E->getType()->isVoidPointerType()) {
Richard Smith28c1ce72012-01-15 03:25:41 +00003063 Result.Designator.setInvalid();
Richard Smith4cd9b8f2011-12-12 19:10:03 +00003064 if (SubExpr->getType()->isVoidPointerType())
3065 CCEDiag(E, diag::note_constexpr_invalid_cast)
3066 << 3 << SubExpr->getType();
3067 else
3068 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3069 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003070 return true;
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003071
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003072 case CK_DerivedToBase:
3073 case CK_UncheckedDerivedToBase: {
Richard Smith47a1eed2011-10-29 20:57:55 +00003074 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003075 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003076 if (!Result.Base && Result.Offset.isZero())
3077 return true;
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003078
Richard Smith180f4792011-11-10 06:34:14 +00003079 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003080 // the derived class to the base class.
Richard Smith180f4792011-11-10 06:34:14 +00003081 QualType Type =
3082 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003083
Richard Smith180f4792011-11-10 06:34:14 +00003084 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003085 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smithb4e85ed2012-01-06 16:39:00 +00003086 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3087 *PathI))
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003088 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003089 Type = (*PathI)->getType();
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003090 }
3091
Anders Carlsson5c5a7642010-10-31 20:41:46 +00003092 return true;
3093 }
3094
Richard Smithe24f5fc2011-11-17 22:56:20 +00003095 case CK_BaseToDerived:
3096 if (!Visit(E->getSubExpr()))
3097 return false;
3098 if (!Result.Base && Result.Offset.isZero())
3099 return true;
3100 return HandleBaseToDerivedCast(Info, E, Result);
3101
Richard Smith47a1eed2011-10-29 20:57:55 +00003102 case CK_NullToPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003103 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003104 return ZeroInitialization(E);
John McCall404cd162010-11-13 01:35:44 +00003105
John McCall2de56d12010-08-25 11:45:40 +00003106 case CK_IntegralToPointer: {
Richard Smithc216a012011-12-12 12:46:16 +00003107 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3108
Richard Smith1aa0be82012-03-03 22:46:17 +00003109 APValue Value;
John McCallefdb83e2010-05-07 21:00:08 +00003110 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman09a8a0e2009-12-27 05:43:15 +00003111 break;
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00003112
John McCallefdb83e2010-05-07 21:00:08 +00003113 if (Value.isInt()) {
Richard Smith47a1eed2011-10-29 20:57:55 +00003114 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3115 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00003116 Result.Base = (Expr*)0;
Richard Smith47a1eed2011-10-29 20:57:55 +00003117 Result.Offset = CharUnits::fromQuantity(N);
Richard Smith83587db2012-02-15 02:18:13 +00003118 Result.CallIndex = 0;
Richard Smith0a3bdb62011-11-04 02:25:55 +00003119 Result.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00003120 return true;
3121 } else {
3122 // Cast is of an lvalue, no need to change value.
Richard Smith1aa0be82012-03-03 22:46:17 +00003123 Result.setFrom(Info.Ctx, Value);
John McCallefdb83e2010-05-07 21:00:08 +00003124 return true;
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003125 }
3126 }
John McCall2de56d12010-08-25 11:45:40 +00003127 case CK_ArrayToPointerDecay:
Richard Smithe24f5fc2011-11-17 22:56:20 +00003128 if (SubExpr->isGLValue()) {
3129 if (!EvaluateLValue(SubExpr, Result, Info))
3130 return false;
3131 } else {
Richard Smith83587db2012-02-15 02:18:13 +00003132 Result.set(SubExpr, Info.CurrentCall->Index);
3133 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3134 Info, Result, SubExpr))
Richard Smithe24f5fc2011-11-17 22:56:20 +00003135 return false;
3136 }
Richard Smith0a3bdb62011-11-04 02:25:55 +00003137 // The result is a pointer to the first element of the array.
Richard Smithb4e85ed2012-01-06 16:39:00 +00003138 if (const ConstantArrayType *CAT
3139 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3140 Result.addArray(Info, E, CAT);
3141 else
3142 Result.Designator.setInvalid();
Richard Smith0a3bdb62011-11-04 02:25:55 +00003143 return true;
Richard Smith6a7c94a2011-10-31 20:57:44 +00003144
John McCall2de56d12010-08-25 11:45:40 +00003145 case CK_FunctionToPointerDecay:
Richard Smith6a7c94a2011-10-31 20:57:44 +00003146 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman4efaa272008-11-12 09:44:48 +00003147 }
3148
Richard Smithc49bd112011-10-28 17:51:58 +00003149 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump1eb44332009-09-09 15:08:12 +00003150}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003151
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003152bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003153 if (IsStringLiteralCall(E))
John McCallefdb83e2010-05-07 21:00:08 +00003154 return Success(E);
Eli Friedman3941b182009-01-25 01:54:01 +00003155
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003156 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00003157}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003158
3159//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003160// Member Pointer Evaluation
3161//===----------------------------------------------------------------------===//
3162
3163namespace {
3164class MemberPointerExprEvaluator
3165 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3166 MemberPtr &Result;
3167
3168 bool Success(const ValueDecl *D) {
3169 Result = MemberPtr(D);
3170 return true;
3171 }
3172public:
3173
3174 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3175 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3176
Richard Smith1aa0be82012-03-03 22:46:17 +00003177 bool Success(const APValue &V, const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003178 Result.setFrom(V);
3179 return true;
3180 }
Richard Smith51201882011-12-30 21:15:51 +00003181 bool ZeroInitialization(const Expr *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00003182 return Success((const ValueDecl*)0);
3183 }
3184
3185 bool VisitCastExpr(const CastExpr *E);
3186 bool VisitUnaryAddrOf(const UnaryOperator *E);
3187};
3188} // end anonymous namespace
3189
3190static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3191 EvalInfo &Info) {
3192 assert(E->isRValue() && E->getType()->isMemberPointerType());
3193 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3194}
3195
3196bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3197 switch (E->getCastKind()) {
3198 default:
3199 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3200
3201 case CK_NullToMemberPointer:
Richard Smith49149fe2012-04-08 08:02:07 +00003202 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003203 return ZeroInitialization(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003204
3205 case CK_BaseToDerivedMemberPointer: {
3206 if (!Visit(E->getSubExpr()))
3207 return false;
3208 if (E->path_empty())
3209 return true;
3210 // Base-to-derived member pointer casts store the path in derived-to-base
3211 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3212 // the wrong end of the derived->base arc, so stagger the path by one class.
3213 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3214 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3215 PathI != PathE; ++PathI) {
3216 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3217 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3218 if (!Result.castToDerived(Derived))
Richard Smithf48fdb02011-12-09 22:58:01 +00003219 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003220 }
3221 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3222 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf48fdb02011-12-09 22:58:01 +00003223 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003224 return true;
3225 }
3226
3227 case CK_DerivedToBaseMemberPointer:
3228 if (!Visit(E->getSubExpr()))
3229 return false;
3230 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3231 PathE = E->path_end(); PathI != PathE; ++PathI) {
3232 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3233 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3234 if (!Result.castToBase(Base))
Richard Smithf48fdb02011-12-09 22:58:01 +00003235 return Error(E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003236 }
3237 return true;
3238 }
3239}
3240
3241bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3242 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3243 // member can be formed.
3244 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3245}
3246
3247//===----------------------------------------------------------------------===//
Richard Smith180f4792011-11-10 06:34:14 +00003248// Record Evaluation
3249//===----------------------------------------------------------------------===//
3250
3251namespace {
3252 class RecordExprEvaluator
3253 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3254 const LValue &This;
3255 APValue &Result;
3256 public:
3257
3258 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3259 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3260
Richard Smith1aa0be82012-03-03 22:46:17 +00003261 bool Success(const APValue &V, const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003262 Result = V;
3263 return true;
Richard Smith180f4792011-11-10 06:34:14 +00003264 }
Richard Smith51201882011-12-30 21:15:51 +00003265 bool ZeroInitialization(const Expr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003266
Richard Smith59efe262011-11-11 04:05:33 +00003267 bool VisitCastExpr(const CastExpr *E);
Richard Smith180f4792011-11-10 06:34:14 +00003268 bool VisitInitListExpr(const InitListExpr *E);
3269 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3270 };
3271}
3272
Richard Smith51201882011-12-30 21:15:51 +00003273/// Perform zero-initialization on an object of non-union class type.
3274/// C++11 [dcl.init]p5:
3275/// To zero-initialize an object or reference of type T means:
3276/// [...]
3277/// -- if T is a (possibly cv-qualified) non-union class type,
3278/// each non-static data member and each base-class subobject is
3279/// zero-initialized
Richard Smithb4e85ed2012-01-06 16:39:00 +00003280static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3281 const RecordDecl *RD,
Richard Smith51201882011-12-30 21:15:51 +00003282 const LValue &This, APValue &Result) {
3283 assert(!RD->isUnion() && "Expected non-union class type");
3284 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3285 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3286 std::distance(RD->field_begin(), RD->field_end()));
3287
John McCall8d59dee2012-05-01 00:38:49 +00003288 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003289 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3290
3291 if (CD) {
3292 unsigned Index = 0;
3293 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smithb4e85ed2012-01-06 16:39:00 +00003294 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smith51201882011-12-30 21:15:51 +00003295 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3296 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003297 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3298 return false;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003299 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smith51201882011-12-30 21:15:51 +00003300 Result.getStructBase(Index)))
3301 return false;
3302 }
3303 }
3304
Richard Smithb4e85ed2012-01-06 16:39:00 +00003305 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3306 I != End; ++I) {
Richard Smith51201882011-12-30 21:15:51 +00003307 // -- if T is a reference type, no initialization is performed.
David Blaikie262bc182012-04-30 02:36:29 +00003308 if (I->getType()->isReferenceType())
Richard Smith51201882011-12-30 21:15:51 +00003309 continue;
3310
3311 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003312 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003313 return false;
Richard Smith51201882011-12-30 21:15:51 +00003314
David Blaikie262bc182012-04-30 02:36:29 +00003315 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003316 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003317 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003318 return false;
3319 }
3320
3321 return true;
3322}
3323
3324bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3325 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003326 if (RD->isInvalidDecl()) return false;
Richard Smith51201882011-12-30 21:15:51 +00003327 if (RD->isUnion()) {
3328 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3329 // object's first non-static named data member is zero-initialized
3330 RecordDecl::field_iterator I = RD->field_begin();
3331 if (I == RD->field_end()) {
3332 Result = APValue((const FieldDecl*)0);
3333 return true;
3334 }
3335
3336 LValue Subobject = This;
David Blaikie581deb32012-06-06 20:45:41 +00003337 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCall8d59dee2012-05-01 00:38:49 +00003338 return false;
David Blaikie581deb32012-06-06 20:45:41 +00003339 Result = APValue(*I);
David Blaikie262bc182012-04-30 02:36:29 +00003340 ImplicitValueInitExpr VIE(I->getType());
Richard Smith83587db2012-02-15 02:18:13 +00003341 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003342 }
3343
Richard Smithce582fe2012-02-17 00:44:16 +00003344 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00003345 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smithce582fe2012-02-17 00:44:16 +00003346 return false;
3347 }
3348
Richard Smithb4e85ed2012-01-06 16:39:00 +00003349 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smith51201882011-12-30 21:15:51 +00003350}
3351
Richard Smith59efe262011-11-11 04:05:33 +00003352bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3353 switch (E->getCastKind()) {
3354 default:
3355 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3356
3357 case CK_ConstructorConversion:
3358 return Visit(E->getSubExpr());
3359
3360 case CK_DerivedToBase:
3361 case CK_UncheckedDerivedToBase: {
Richard Smith1aa0be82012-03-03 22:46:17 +00003362 APValue DerivedObject;
Richard Smithf48fdb02011-12-09 22:58:01 +00003363 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smith59efe262011-11-11 04:05:33 +00003364 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00003365 if (!DerivedObject.isStruct())
3366 return Error(E->getSubExpr());
Richard Smith59efe262011-11-11 04:05:33 +00003367
3368 // Derived-to-base rvalue conversion: just slice off the derived part.
3369 APValue *Value = &DerivedObject;
3370 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3371 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3372 PathE = E->path_end(); PathI != PathE; ++PathI) {
3373 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3374 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3375 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3376 RD = Base;
3377 }
3378 Result = *Value;
3379 return true;
3380 }
3381 }
3382}
3383
Richard Smith180f4792011-11-10 06:34:14 +00003384bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redl24fe7982012-02-19 14:53:49 +00003385 // Cannot constant-evaluate std::initializer_list inits.
3386 if (E->initializesStdInitializerList())
3387 return false;
3388
Richard Smith180f4792011-11-10 06:34:14 +00003389 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall1de9d7d2012-04-26 18:10:01 +00003390 if (RD->isInvalidDecl()) return false;
Richard Smith180f4792011-11-10 06:34:14 +00003391 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3392
3393 if (RD->isUnion()) {
Richard Smithec789162012-01-12 18:54:33 +00003394 const FieldDecl *Field = E->getInitializedFieldInUnion();
3395 Result = APValue(Field);
3396 if (!Field)
Richard Smith180f4792011-11-10 06:34:14 +00003397 return true;
Richard Smithec789162012-01-12 18:54:33 +00003398
3399 // If the initializer list for a union does not contain any elements, the
3400 // first element of the union is value-initialized.
3401 ImplicitValueInitExpr VIE(Field->getType());
3402 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3403
Richard Smith180f4792011-11-10 06:34:14 +00003404 LValue Subobject = This;
John McCall8d59dee2012-05-01 00:38:49 +00003405 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3406 return false;
Richard Smith83587db2012-02-15 02:18:13 +00003407 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smith180f4792011-11-10 06:34:14 +00003408 }
3409
3410 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3411 "initializer list for class with base classes");
3412 Result = APValue(APValue::UninitStruct(), 0,
3413 std::distance(RD->field_begin(), RD->field_end()));
3414 unsigned ElementNo = 0;
Richard Smith745f5142012-01-27 01:14:48 +00003415 bool Success = true;
Richard Smith180f4792011-11-10 06:34:14 +00003416 for (RecordDecl::field_iterator Field = RD->field_begin(),
3417 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3418 // Anonymous bit-fields are not considered members of the class for
3419 // purposes of aggregate initialization.
3420 if (Field->isUnnamedBitfield())
3421 continue;
3422
3423 LValue Subobject = This;
Richard Smith180f4792011-11-10 06:34:14 +00003424
Richard Smith745f5142012-01-27 01:14:48 +00003425 bool HaveInit = ElementNo < E->getNumInits();
3426
3427 // FIXME: Diagnostics here should point to the end of the initializer
3428 // list, not the start.
John McCall8d59dee2012-05-01 00:38:49 +00003429 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie581deb32012-06-06 20:45:41 +00003430 Subobject, *Field, &Layout))
John McCall8d59dee2012-05-01 00:38:49 +00003431 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003432
3433 // Perform an implicit value-initialization for members beyond the end of
3434 // the initializer list.
3435 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3436
Richard Smith83587db2012-02-15 02:18:13 +00003437 if (!EvaluateInPlace(
David Blaikie262bc182012-04-30 02:36:29 +00003438 Result.getStructField(Field->getFieldIndex()),
Richard Smith745f5142012-01-27 01:14:48 +00003439 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3440 if (!Info.keepEvaluatingAfterFailure())
Richard Smith180f4792011-11-10 06:34:14 +00003441 return false;
Richard Smith745f5142012-01-27 01:14:48 +00003442 Success = false;
Richard Smith180f4792011-11-10 06:34:14 +00003443 }
3444 }
3445
Richard Smith745f5142012-01-27 01:14:48 +00003446 return Success;
Richard Smith180f4792011-11-10 06:34:14 +00003447}
3448
3449bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3450 const CXXConstructorDecl *FD = E->getConstructor();
John McCall1de9d7d2012-04-26 18:10:01 +00003451 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3452
Richard Smith51201882011-12-30 21:15:51 +00003453 bool ZeroInit = E->requiresZeroInitialization();
3454 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003455 // If we've already performed zero-initialization, we're already done.
3456 if (!Result.isUninit())
3457 return true;
3458
Richard Smith51201882011-12-30 21:15:51 +00003459 if (ZeroInit)
3460 return ZeroInitialization(E);
3461
Richard Smith61802452011-12-22 02:22:31 +00003462 const CXXRecordDecl *RD = FD->getParent();
3463 if (RD->isUnion())
3464 Result = APValue((FieldDecl*)0);
3465 else
3466 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3467 std::distance(RD->field_begin(), RD->field_end()));
3468 return true;
3469 }
3470
Richard Smith180f4792011-11-10 06:34:14 +00003471 const FunctionDecl *Definition = 0;
3472 FD->getBody(Definition);
3473
Richard Smithc1c5f272011-12-13 06:39:58 +00003474 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3475 return false;
Richard Smith180f4792011-11-10 06:34:14 +00003476
Richard Smith610a60c2012-01-10 04:32:03 +00003477 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smith51201882011-12-30 21:15:51 +00003478 if (E->isElidable() && !ZeroInit)
Richard Smith180f4792011-11-10 06:34:14 +00003479 if (const MaterializeTemporaryExpr *ME
3480 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3481 return Visit(ME->GetTemporaryExpr());
3482
Richard Smith51201882011-12-30 21:15:51 +00003483 if (ZeroInit && !ZeroInitialization(E))
3484 return false;
3485
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003486 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003487 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf48fdb02011-12-09 22:58:01 +00003488 cast<CXXConstructorDecl>(Definition), Info,
3489 Result);
Richard Smith180f4792011-11-10 06:34:14 +00003490}
3491
3492static bool EvaluateRecord(const Expr *E, const LValue &This,
3493 APValue &Result, EvalInfo &Info) {
3494 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smith180f4792011-11-10 06:34:14 +00003495 "can't evaluate expression as a record rvalue");
3496 return RecordExprEvaluator(Info, This, Result).Visit(E);
3497}
3498
3499//===----------------------------------------------------------------------===//
Richard Smithe24f5fc2011-11-17 22:56:20 +00003500// Temporary Evaluation
3501//
3502// Temporaries are represented in the AST as rvalues, but generally behave like
3503// lvalues. The full-object of which the temporary is a subobject is implicitly
3504// materialized so that a reference can bind to it.
3505//===----------------------------------------------------------------------===//
3506namespace {
3507class TemporaryExprEvaluator
3508 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3509public:
3510 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3511 LValueExprEvaluatorBaseTy(Info, Result) {}
3512
3513 /// Visit an expression which constructs the value of this temporary.
3514 bool VisitConstructExpr(const Expr *E) {
Richard Smith83587db2012-02-15 02:18:13 +00003515 Result.set(E, Info.CurrentCall->Index);
3516 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003517 }
3518
3519 bool VisitCastExpr(const CastExpr *E) {
3520 switch (E->getCastKind()) {
3521 default:
3522 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3523
3524 case CK_ConstructorConversion:
3525 return VisitConstructExpr(E->getSubExpr());
3526 }
3527 }
3528 bool VisitInitListExpr(const InitListExpr *E) {
3529 return VisitConstructExpr(E);
3530 }
3531 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3532 return VisitConstructExpr(E);
3533 }
3534 bool VisitCallExpr(const CallExpr *E) {
3535 return VisitConstructExpr(E);
3536 }
3537};
3538} // end anonymous namespace
3539
3540/// Evaluate an expression of record type as a temporary.
3541static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithaf2c7a12011-12-19 22:01:37 +00003542 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smithe24f5fc2011-11-17 22:56:20 +00003543 return TemporaryExprEvaluator(Info, Result).Visit(E);
3544}
3545
3546//===----------------------------------------------------------------------===//
Nate Begeman59b5da62009-01-18 03:20:47 +00003547// Vector Evaluation
3548//===----------------------------------------------------------------------===//
3549
3550namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003551 class VectorExprEvaluator
Richard Smith07fc6572011-10-22 21:10:00 +00003552 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3553 APValue &Result;
Nate Begeman59b5da62009-01-18 03:20:47 +00003554 public:
Mike Stump1eb44332009-09-09 15:08:12 +00003555
Richard Smith07fc6572011-10-22 21:10:00 +00003556 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3557 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump1eb44332009-09-09 15:08:12 +00003558
Richard Smith07fc6572011-10-22 21:10:00 +00003559 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3560 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3561 // FIXME: remove this APValue copy.
3562 Result = APValue(V.data(), V.size());
3563 return true;
3564 }
Richard Smith1aa0be82012-03-03 22:46:17 +00003565 bool Success(const APValue &V, const Expr *E) {
Richard Smith69c2c502011-11-04 05:33:44 +00003566 assert(V.isVector());
Richard Smith07fc6572011-10-22 21:10:00 +00003567 Result = V;
3568 return true;
3569 }
Richard Smith51201882011-12-30 21:15:51 +00003570 bool ZeroInitialization(const Expr *E);
Mike Stump1eb44332009-09-09 15:08:12 +00003571
Richard Smith07fc6572011-10-22 21:10:00 +00003572 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman91110ee2009-02-23 04:23:56 +00003573 { return Visit(E->getSubExpr()); }
Richard Smith07fc6572011-10-22 21:10:00 +00003574 bool VisitCastExpr(const CastExpr* E);
Richard Smith07fc6572011-10-22 21:10:00 +00003575 bool VisitInitListExpr(const InitListExpr *E);
3576 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003577 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedman2217c872009-02-22 11:46:18 +00003578 // binary comparisons, binary and/or/xor,
Eli Friedman91110ee2009-02-23 04:23:56 +00003579 // shufflevector, ExtVectorElementExpr
Nate Begeman59b5da62009-01-18 03:20:47 +00003580 };
3581} // end anonymous namespace
3582
3583static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00003584 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith07fc6572011-10-22 21:10:00 +00003585 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003586}
3587
Richard Smith07fc6572011-10-22 21:10:00 +00003588bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3589 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanc0b8b192009-07-01 07:50:47 +00003590 unsigned NElts = VTy->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003591
Richard Smithd62ca372011-12-06 22:44:34 +00003592 const Expr *SE = E->getSubExpr();
Nate Begemane8c9e922009-06-26 18:22:18 +00003593 QualType SETy = SE->getType();
Nate Begeman59b5da62009-01-18 03:20:47 +00003594
Eli Friedman46a52322011-03-25 00:43:55 +00003595 switch (E->getCastKind()) {
3596 case CK_VectorSplat: {
Richard Smith07fc6572011-10-22 21:10:00 +00003597 APValue Val = APValue();
Eli Friedman46a52322011-03-25 00:43:55 +00003598 if (SETy->isIntegerType()) {
3599 APSInt IntResult;
3600 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003601 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003602 Val = APValue(IntResult);
Eli Friedman46a52322011-03-25 00:43:55 +00003603 } else if (SETy->isRealFloatingType()) {
3604 APFloat F(0.0);
3605 if (!EvaluateFloat(SE, F, Info))
Richard Smithf48fdb02011-12-09 22:58:01 +00003606 return false;
Richard Smith07fc6572011-10-22 21:10:00 +00003607 Val = APValue(F);
Eli Friedman46a52322011-03-25 00:43:55 +00003608 } else {
Richard Smith07fc6572011-10-22 21:10:00 +00003609 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003610 }
Nate Begemanc0b8b192009-07-01 07:50:47 +00003611
3612 // Splat and create vector APValue.
Richard Smith07fc6572011-10-22 21:10:00 +00003613 SmallVector<APValue, 4> Elts(NElts, Val);
3614 return Success(Elts, E);
Nate Begemane8c9e922009-06-26 18:22:18 +00003615 }
Eli Friedmane6a24e82011-12-22 03:51:45 +00003616 case CK_BitCast: {
3617 // Evaluate the operand into an APInt we can extract from.
3618 llvm::APInt SValInt;
3619 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3620 return false;
3621 // Extract the elements
3622 QualType EltTy = VTy->getElementType();
3623 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3624 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3625 SmallVector<APValue, 4> Elts;
3626 if (EltTy->isRealFloatingType()) {
3627 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedmane6a24e82011-12-22 03:51:45 +00003628 unsigned FloatEltSize = EltSize;
3629 if (&Sem == &APFloat::x87DoubleExtended)
3630 FloatEltSize = 80;
3631 for (unsigned i = 0; i < NElts; i++) {
3632 llvm::APInt Elt;
3633 if (BigEndian)
3634 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3635 else
3636 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover9ec55f22013-01-22 09:46:51 +00003637 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedmane6a24e82011-12-22 03:51:45 +00003638 }
3639 } else if (EltTy->isIntegerType()) {
3640 for (unsigned i = 0; i < NElts; i++) {
3641 llvm::APInt Elt;
3642 if (BigEndian)
3643 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3644 else
3645 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3646 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3647 }
3648 } else {
3649 return Error(E);
3650 }
3651 return Success(Elts, E);
3652 }
Eli Friedman46a52322011-03-25 00:43:55 +00003653 default:
Richard Smithc49bd112011-10-28 17:51:58 +00003654 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00003655 }
Nate Begeman59b5da62009-01-18 03:20:47 +00003656}
3657
Richard Smith07fc6572011-10-22 21:10:00 +00003658bool
Nate Begeman59b5da62009-01-18 03:20:47 +00003659VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003660 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman59b5da62009-01-18 03:20:47 +00003661 unsigned NumInits = E->getNumInits();
Eli Friedman91110ee2009-02-23 04:23:56 +00003662 unsigned NumElements = VT->getNumElements();
Mike Stump1eb44332009-09-09 15:08:12 +00003663
Nate Begeman59b5da62009-01-18 03:20:47 +00003664 QualType EltTy = VT->getElementType();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003665 SmallVector<APValue, 4> Elements;
Nate Begeman59b5da62009-01-18 03:20:47 +00003666
Eli Friedman3edd5a92012-01-03 23:24:20 +00003667 // The number of initializers can be less than the number of
3668 // vector elements. For OpenCL, this can be due to nested vector
3669 // initialization. For GCC compatibility, missing trailing elements
3670 // should be initialized with zeroes.
3671 unsigned CountInits = 0, CountElts = 0;
3672 while (CountElts < NumElements) {
3673 // Handle nested vector initialization.
3674 if (CountInits < NumInits
3675 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3676 APValue v;
3677 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3678 return Error(E);
3679 unsigned vlen = v.getVectorLength();
3680 for (unsigned j = 0; j < vlen; j++)
3681 Elements.push_back(v.getVectorElt(j));
3682 CountElts += vlen;
3683 } else if (EltTy->isIntegerType()) {
Nate Begeman59b5da62009-01-18 03:20:47 +00003684 llvm::APSInt sInt(32);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003685 if (CountInits < NumInits) {
3686 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003687 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003688 } else // trailing integer zero.
3689 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3690 Elements.push_back(APValue(sInt));
3691 CountElts++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003692 } else {
3693 llvm::APFloat f(0.0);
Eli Friedman3edd5a92012-01-03 23:24:20 +00003694 if (CountInits < NumInits) {
3695 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smith4b1f6842012-03-13 20:58:32 +00003696 return false;
Eli Friedman3edd5a92012-01-03 23:24:20 +00003697 } else // trailing float zero.
3698 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3699 Elements.push_back(APValue(f));
3700 CountElts++;
John McCalla7d6c222010-06-11 17:54:15 +00003701 }
Eli Friedman3edd5a92012-01-03 23:24:20 +00003702 CountInits++;
Nate Begeman59b5da62009-01-18 03:20:47 +00003703 }
Richard Smith07fc6572011-10-22 21:10:00 +00003704 return Success(Elements, E);
Nate Begeman59b5da62009-01-18 03:20:47 +00003705}
3706
Richard Smith07fc6572011-10-22 21:10:00 +00003707bool
Richard Smith51201882011-12-30 21:15:51 +00003708VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith07fc6572011-10-22 21:10:00 +00003709 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman91110ee2009-02-23 04:23:56 +00003710 QualType EltTy = VT->getElementType();
3711 APValue ZeroElement;
3712 if (EltTy->isIntegerType())
3713 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3714 else
3715 ZeroElement =
3716 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3717
Chris Lattner5f9e2722011-07-23 10:55:15 +00003718 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith07fc6572011-10-22 21:10:00 +00003719 return Success(Elements, E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003720}
3721
Richard Smith07fc6572011-10-22 21:10:00 +00003722bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith8327fad2011-10-24 18:44:57 +00003723 VisitIgnoredValue(E->getSubExpr());
Richard Smith51201882011-12-30 21:15:51 +00003724 return ZeroInitialization(E);
Eli Friedman91110ee2009-02-23 04:23:56 +00003725}
3726
Nate Begeman59b5da62009-01-18 03:20:47 +00003727//===----------------------------------------------------------------------===//
Richard Smithcc5d4f62011-11-07 09:22:26 +00003728// Array Evaluation
3729//===----------------------------------------------------------------------===//
3730
3731namespace {
3732 class ArrayExprEvaluator
3733 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smith180f4792011-11-10 06:34:14 +00003734 const LValue &This;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003735 APValue &Result;
3736 public:
3737
Richard Smith180f4792011-11-10 06:34:14 +00003738 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3739 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithcc5d4f62011-11-07 09:22:26 +00003740
3741 bool Success(const APValue &V, const Expr *E) {
Richard Smithf3908f22012-02-17 03:35:37 +00003742 assert((V.isArray() || V.isLValue()) &&
3743 "expected array or string literal");
Richard Smithcc5d4f62011-11-07 09:22:26 +00003744 Result = V;
3745 return true;
3746 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003747
Richard Smith51201882011-12-30 21:15:51 +00003748 bool ZeroInitialization(const Expr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00003749 const ConstantArrayType *CAT =
3750 Info.Ctx.getAsConstantArrayType(E->getType());
3751 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003752 return Error(E);
Richard Smith180f4792011-11-10 06:34:14 +00003753
3754 Result = APValue(APValue::UninitArray(), 0,
3755 CAT->getSize().getZExtValue());
3756 if (!Result.hasArrayFiller()) return true;
3757
Richard Smith51201882011-12-30 21:15:51 +00003758 // Zero-initialize all elements.
Richard Smith180f4792011-11-10 06:34:14 +00003759 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003760 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003761 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smith83587db2012-02-15 02:18:13 +00003762 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smith180f4792011-11-10 06:34:14 +00003763 }
3764
Richard Smithcc5d4f62011-11-07 09:22:26 +00003765 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003766 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003767 };
3768} // end anonymous namespace
3769
Richard Smith180f4792011-11-10 06:34:14 +00003770static bool EvaluateArray(const Expr *E, const LValue &This,
3771 APValue &Result, EvalInfo &Info) {
Richard Smith51201882011-12-30 21:15:51 +00003772 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smith180f4792011-11-10 06:34:14 +00003773 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003774}
3775
3776bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3777 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3778 if (!CAT)
Richard Smithf48fdb02011-12-09 22:58:01 +00003779 return Error(E);
Richard Smithcc5d4f62011-11-07 09:22:26 +00003780
Richard Smith974c5f92011-12-22 01:07:19 +00003781 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3782 // an appropriately-typed string literal enclosed in braces.
Richard Smithfe587202012-04-15 02:50:59 +00003783 if (E->isStringLiteralInit()) {
Richard Smith974c5f92011-12-22 01:07:19 +00003784 LValue LV;
3785 if (!EvaluateLValue(E->getInit(0), LV, Info))
3786 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00003787 APValue Val;
Richard Smithf3908f22012-02-17 03:35:37 +00003788 LV.moveInto(Val);
3789 return Success(Val, E);
Richard Smith974c5f92011-12-22 01:07:19 +00003790 }
3791
Richard Smith745f5142012-01-27 01:14:48 +00003792 bool Success = true;
3793
Richard Smithde31aa72012-07-07 22:48:24 +00003794 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
3795 "zero-initialized array shouldn't have any initialized elts");
3796 APValue Filler;
3797 if (Result.isArray() && Result.hasArrayFiller())
3798 Filler = Result.getArrayFiller();
3799
Richard Smithcc5d4f62011-11-07 09:22:26 +00003800 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3801 CAT->getSize().getZExtValue());
Richard Smithde31aa72012-07-07 22:48:24 +00003802
3803 // If the array was previously zero-initialized, preserve the
3804 // zero-initialized values.
3805 if (!Filler.isUninit()) {
3806 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
3807 Result.getArrayInitializedElt(I) = Filler;
3808 if (Result.hasArrayFiller())
3809 Result.getArrayFiller() = Filler;
3810 }
3811
Richard Smith180f4792011-11-10 06:34:14 +00003812 LValue Subobject = This;
Richard Smithb4e85ed2012-01-06 16:39:00 +00003813 Subobject.addArray(Info, E, CAT);
Richard Smith180f4792011-11-10 06:34:14 +00003814 unsigned Index = 0;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003815 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smith180f4792011-11-10 06:34:14 +00003816 I != End; ++I, ++Index) {
Richard Smith83587db2012-02-15 02:18:13 +00003817 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3818 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith745f5142012-01-27 01:14:48 +00003819 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3820 CAT->getElementType(), 1)) {
3821 if (!Info.keepEvaluatingAfterFailure())
3822 return false;
3823 Success = false;
3824 }
Richard Smith180f4792011-11-10 06:34:14 +00003825 }
Richard Smithcc5d4f62011-11-07 09:22:26 +00003826
Richard Smith745f5142012-01-27 01:14:48 +00003827 if (!Result.hasArrayFiller()) return Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003828 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smith180f4792011-11-10 06:34:14 +00003829 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3830 // but sometimes does:
3831 // struct S { constexpr S() : p(&p) {} void *p; };
3832 // S s[10] = {};
Richard Smith83587db2012-02-15 02:18:13 +00003833 return EvaluateInPlace(Result.getArrayFiller(), Info,
3834 Subobject, E->getArrayFiller()) && Success;
Richard Smithcc5d4f62011-11-07 09:22:26 +00003835}
3836
Richard Smithe24f5fc2011-11-17 22:56:20 +00003837bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smithde31aa72012-07-07 22:48:24 +00003838 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3839 // but sometimes does:
3840 // struct S { constexpr S() : p(&p) {} void *p; };
3841 // S s[10];
3842 LValue Subobject = This;
3843
3844 APValue *Value = &Result;
3845 bool HadZeroInit = true;
Richard Smitha4334df2012-07-10 22:12:55 +00003846 QualType ElemTy = E->getType();
3847 while (const ConstantArrayType *CAT =
3848 Info.Ctx.getAsConstantArrayType(ElemTy)) {
Richard Smithde31aa72012-07-07 22:48:24 +00003849 Subobject.addArray(Info, E, CAT);
3850 HadZeroInit &= !Value->isUninit();
3851 if (!HadZeroInit)
3852 *Value = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3853 if (!Value->hasArrayFiller())
3854 return true;
Richard Smithde31aa72012-07-07 22:48:24 +00003855 Value = &Value->getArrayFiller();
Richard Smitha4334df2012-07-10 22:12:55 +00003856 ElemTy = CAT->getElementType();
Richard Smithde31aa72012-07-07 22:48:24 +00003857 }
Richard Smithe24f5fc2011-11-17 22:56:20 +00003858
Richard Smitha4334df2012-07-10 22:12:55 +00003859 if (!ElemTy->isRecordType())
3860 return Error(E);
3861
Richard Smithe24f5fc2011-11-17 22:56:20 +00003862 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smith61802452011-12-22 02:22:31 +00003863
Richard Smith51201882011-12-30 21:15:51 +00003864 bool ZeroInit = E->requiresZeroInitialization();
3865 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smithec789162012-01-12 18:54:33 +00003866 if (HadZeroInit)
3867 return true;
3868
Richard Smith51201882011-12-30 21:15:51 +00003869 if (ZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003870 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003871 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smith51201882011-12-30 21:15:51 +00003872 }
3873
Richard Smith61802452011-12-22 02:22:31 +00003874 const CXXRecordDecl *RD = FD->getParent();
3875 if (RD->isUnion())
Richard Smithde31aa72012-07-07 22:48:24 +00003876 *Value = APValue((FieldDecl*)0);
Richard Smith61802452011-12-22 02:22:31 +00003877 else
Richard Smithde31aa72012-07-07 22:48:24 +00003878 *Value =
Richard Smith61802452011-12-22 02:22:31 +00003879 APValue(APValue::UninitStruct(), RD->getNumBases(),
3880 std::distance(RD->field_begin(), RD->field_end()));
3881 return true;
3882 }
3883
Richard Smithe24f5fc2011-11-17 22:56:20 +00003884 const FunctionDecl *Definition = 0;
3885 FD->getBody(Definition);
3886
Richard Smithc1c5f272011-12-13 06:39:58 +00003887 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3888 return false;
Richard Smithe24f5fc2011-11-17 22:56:20 +00003889
Richard Smithec789162012-01-12 18:54:33 +00003890 if (ZeroInit && !HadZeroInit) {
Richard Smitha4334df2012-07-10 22:12:55 +00003891 ImplicitValueInitExpr VIE(ElemTy);
Richard Smithde31aa72012-07-07 22:48:24 +00003892 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smith51201882011-12-30 21:15:51 +00003893 return false;
3894 }
3895
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00003896 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith745f5142012-01-27 01:14:48 +00003897 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smithe24f5fc2011-11-17 22:56:20 +00003898 cast<CXXConstructorDecl>(Definition),
Richard Smithde31aa72012-07-07 22:48:24 +00003899 Info, *Value);
Richard Smithe24f5fc2011-11-17 22:56:20 +00003900}
3901
Richard Smithcc5d4f62011-11-07 09:22:26 +00003902//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003903// Integer Evaluation
Richard Smithc49bd112011-10-28 17:51:58 +00003904//
3905// As a GNU extension, we support casting pointers to sufficiently-wide integer
3906// types and back in constant folding. Integer values are thus represented
3907// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003908//===----------------------------------------------------------------------===//
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003909
3910namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00003911class IntExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003912 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith1aa0be82012-03-03 22:46:17 +00003913 APValue &Result;
Anders Carlssonc754aa62008-07-08 05:13:58 +00003914public:
Richard Smith1aa0be82012-03-03 22:46:17 +00003915 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003916 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattnerf5eeb052008-07-11 18:11:29 +00003917
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003918 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003919 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003920 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003921 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003922 "Invalid evaluation result.");
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00003923 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003924 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003925 Result = APValue(SI);
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003926 return true;
3927 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003928 bool Success(const llvm::APSInt &SI, const Expr *E) {
3929 return Success(SI, E, Result);
3930 }
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003931
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003932 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003933 assert(E->getType()->isIntegralOrEnumerationType() &&
3934 "Invalid evaluation result.");
Daniel Dunbar30c37f42009-02-19 20:17:33 +00003935 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbar3f7d9952009-02-19 18:37:50 +00003936 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003937 Result = APValue(APSInt(I));
Douglas Gregor575a1c92011-05-20 16:38:50 +00003938 Result.getInt().setIsUnsigned(
3939 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar131eb432009-02-19 09:06:44 +00003940 return true;
3941 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003942 bool Success(const llvm::APInt &I, const Expr *E) {
3943 return Success(I, E, Result);
3944 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003945
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003946 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregor2ade35e2010-06-16 00:17:44 +00003947 assert(E->getType()->isIntegralOrEnumerationType() &&
3948 "Invalid evaluation result.");
Richard Smith1aa0be82012-03-03 22:46:17 +00003949 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar131eb432009-02-19 09:06:44 +00003950 return true;
3951 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00003952 bool Success(uint64_t Value, const Expr *E) {
3953 return Success(Value, E, Result);
3954 }
Daniel Dunbar131eb432009-02-19 09:06:44 +00003955
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00003956 bool Success(CharUnits Size, const Expr *E) {
3957 return Success(Size.getQuantity(), E);
3958 }
3959
Richard Smith1aa0be82012-03-03 22:46:17 +00003960 bool Success(const APValue &V, const Expr *E) {
Eli Friedman5930a4c2012-01-05 23:59:40 +00003961 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith342f1f82011-10-29 22:55:55 +00003962 Result = V;
3963 return true;
3964 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003965 return Success(V.getInt(), E);
Chris Lattner32fea9d2008-11-12 07:43:42 +00003966 }
Mike Stump1eb44332009-09-09 15:08:12 +00003967
Richard Smith51201882011-12-30 21:15:51 +00003968 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smithf10d9172011-10-11 21:43:33 +00003969
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003970 //===--------------------------------------------------------------------===//
3971 // Visitor Methods
3972 //===--------------------------------------------------------------------===//
Anders Carlssonc754aa62008-07-08 05:13:58 +00003973
Chris Lattner4c4867e2008-07-12 00:38:25 +00003974 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003975 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003976 }
3977 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00003978 return Success(E->getValue(), E);
Chris Lattner4c4867e2008-07-12 00:38:25 +00003979 }
Eli Friedman04309752009-11-24 05:28:59 +00003980
3981 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3982 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003983 if (CheckReferencedDecl(E, E->getDecl()))
3984 return true;
3985
3986 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003987 }
3988 bool VisitMemberExpr(const MemberExpr *E) {
3989 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smithc49bd112011-10-28 17:51:58 +00003990 VisitIgnoredValue(E->getBase());
Eli Friedman04309752009-11-24 05:28:59 +00003991 return true;
3992 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003993
3994 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman04309752009-11-24 05:28:59 +00003995 }
3996
Peter Collingbourne8cad3042011-05-13 03:29:01 +00003997 bool VisitCallExpr(const CallExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00003998 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00003999 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnerb542afe2008-07-11 19:10:17 +00004000 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson06a36752008-07-08 05:49:43 +00004001
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004002 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00004003 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl05189992008-11-11 17:56:53 +00004004
Anders Carlsson3068d112008-11-16 19:01:22 +00004005 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar131eb432009-02-19 09:06:44 +00004006 return Success(E->getValue(), E);
Anders Carlsson3068d112008-11-16 19:01:22 +00004007 }
Mike Stump1eb44332009-09-09 15:08:12 +00004008
Ted Kremenekebcb57a2012-03-06 20:05:56 +00004009 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4010 return Success(E->getValue(), E);
4011 }
4012
Richard Smithf10d9172011-10-11 21:43:33 +00004013 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson3f704562008-12-21 22:39:40 +00004014 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smith51201882011-12-30 21:15:51 +00004015 return ZeroInitialization(E);
Eli Friedman664a1042009-02-27 04:45:43 +00004016 }
4017
Sebastian Redl64b45f72009-01-05 20:52:13 +00004018 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl0dfd8482010-09-13 20:56:31 +00004019 return Success(E->getValue(), E);
Sebastian Redl64b45f72009-01-05 20:52:13 +00004020 }
4021
Francois Pichet6ad6f282010-12-07 00:08:36 +00004022 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4023 return Success(E->getValue(), E);
4024 }
4025
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00004026 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4027 return Success(E->getValue(), E);
4028 }
4029
John Wiegley21ff2e52011-04-28 00:16:57 +00004030 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4031 return Success(E->getValue(), E);
4032 }
4033
John Wiegley55262202011-04-25 06:54:41 +00004034 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4035 return Success(E->getValue(), E);
4036 }
4037
Eli Friedman722c7172009-02-28 03:59:05 +00004038 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004039 bool VisitUnaryImag(const UnaryOperator *E);
4040
Sebastian Redl295995c2010-09-10 20:55:47 +00004041 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregoree8aff02011-01-04 17:33:58 +00004042 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redlcea8d962011-09-24 17:48:14 +00004043
Chris Lattnerfcee0012008-07-11 21:24:13 +00004044private:
Ken Dyck8b752f12010-01-27 17:10:57 +00004045 CharUnits GetAlignOfExpr(const Expr *E);
4046 CharUnits GetAlignOfType(QualType T);
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004047 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004048 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman664a1042009-02-27 04:45:43 +00004049 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlssona25ae3d2008-07-08 14:35:21 +00004050};
Chris Lattnerf5eeb052008-07-11 18:11:29 +00004051} // end anonymous namespace
Anders Carlsson650c92f2008-07-08 15:34:11 +00004052
Richard Smithc49bd112011-10-28 17:51:58 +00004053/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4054/// produce either the integer value or a pointer.
4055///
4056/// GCC has a heinous extension which folds casts between pointer types and
4057/// pointer-sized integral types. We support this by allowing the evaluation of
4058/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4059/// Some simple arithmetic on such values is supported (they are treated much
4060/// like char*).
Richard Smith1aa0be82012-03-03 22:46:17 +00004061static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith47a1eed2011-10-29 20:57:55 +00004062 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00004063 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004064 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004065}
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004066
Richard Smithf48fdb02011-12-09 22:58:01 +00004067static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith1aa0be82012-03-03 22:46:17 +00004068 APValue Val;
Richard Smithf48fdb02011-12-09 22:58:01 +00004069 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbar69ab26a2009-02-20 18:22:23 +00004070 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00004071 if (!Val.isInt()) {
4072 // FIXME: It would be better to produce the diagnostic for casting
4073 // a pointer to an integer.
Richard Smith5cfc7d82012-03-15 04:53:45 +00004074 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf48fdb02011-12-09 22:58:01 +00004075 return false;
4076 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00004077 Result = Val.getInt();
4078 return true;
Anders Carlsson650c92f2008-07-08 15:34:11 +00004079}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004080
Richard Smithf48fdb02011-12-09 22:58:01 +00004081/// Check whether the given declaration can be directly converted to an integral
4082/// rvalue. If not, no diagnostic is produced; there are other things we can
4083/// try.
Eli Friedman04309752009-11-24 05:28:59 +00004084bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner4c4867e2008-07-12 00:38:25 +00004085 // Enums are integer constant exprs.
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004086 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara973c4fc2011-07-02 13:13:53 +00004087 // Check for signedness/width mismatches between E type and ECD value.
4088 bool SameSign = (ECD->getInitVal().isSigned()
4089 == E->getType()->isSignedIntegerOrEnumerationType());
4090 bool SameWidth = (ECD->getInitVal().getBitWidth()
4091 == Info.Ctx.getIntWidth(E->getType()));
4092 if (SameSign && SameWidth)
4093 return Success(ECD->getInitVal(), E);
4094 else {
4095 // Get rid of mismatch (otherwise Success assertions will fail)
4096 // by computing a new value matching the type of E.
4097 llvm::APSInt Val = ECD->getInitVal();
4098 if (!SameSign)
4099 Val.setIsSigned(!ECD->getInitVal().isSigned());
4100 if (!SameWidth)
4101 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4102 return Success(Val, E);
4103 }
Abramo Bagnarabfbdcd82011-06-30 09:36:05 +00004104 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004105 return false;
Chris Lattner4c4867e2008-07-12 00:38:25 +00004106}
4107
Chris Lattnera4d55d82008-10-06 06:40:35 +00004108/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4109/// as GCC.
4110static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4111 // The following enum mimics the values returned by GCC.
Sebastian Redl7c80bd62009-03-16 23:22:08 +00004112 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattnera4d55d82008-10-06 06:40:35 +00004113 enum gcc_type_class {
4114 no_type_class = -1,
4115 void_type_class, integer_type_class, char_type_class,
4116 enumeral_type_class, boolean_type_class,
4117 pointer_type_class, reference_type_class, offset_type_class,
4118 real_type_class, complex_type_class,
4119 function_type_class, method_type_class,
4120 record_type_class, union_type_class,
4121 array_type_class, string_type_class,
4122 lang_type_class
4123 };
Mike Stump1eb44332009-09-09 15:08:12 +00004124
4125 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattnera4d55d82008-10-06 06:40:35 +00004126 // ideal, however it is what gcc does.
4127 if (E->getNumArgs() == 0)
4128 return no_type_class;
Mike Stump1eb44332009-09-09 15:08:12 +00004129
Chris Lattnera4d55d82008-10-06 06:40:35 +00004130 QualType ArgTy = E->getArg(0)->getType();
4131 if (ArgTy->isVoidType())
4132 return void_type_class;
4133 else if (ArgTy->isEnumeralType())
4134 return enumeral_type_class;
4135 else if (ArgTy->isBooleanType())
4136 return boolean_type_class;
4137 else if (ArgTy->isCharType())
4138 return string_type_class; // gcc doesn't appear to use char_type_class
4139 else if (ArgTy->isIntegerType())
4140 return integer_type_class;
4141 else if (ArgTy->isPointerType())
4142 return pointer_type_class;
4143 else if (ArgTy->isReferenceType())
4144 return reference_type_class;
4145 else if (ArgTy->isRealType())
4146 return real_type_class;
4147 else if (ArgTy->isComplexType())
4148 return complex_type_class;
4149 else if (ArgTy->isFunctionType())
4150 return function_type_class;
Douglas Gregorfb87b892010-04-26 21:31:17 +00004151 else if (ArgTy->isStructureOrClassType())
Chris Lattnera4d55d82008-10-06 06:40:35 +00004152 return record_type_class;
4153 else if (ArgTy->isUnionType())
4154 return union_type_class;
4155 else if (ArgTy->isArrayType())
4156 return array_type_class;
4157 else if (ArgTy->isUnionType())
4158 return union_type_class;
4159 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikieb219cfc2011-09-23 05:06:16 +00004160 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattnera4d55d82008-10-06 06:40:35 +00004161}
4162
Richard Smith80d4b552011-12-28 19:48:30 +00004163/// EvaluateBuiltinConstantPForLValue - Determine the result of
4164/// __builtin_constant_p when applied to the given lvalue.
4165///
4166/// An lvalue is only "constant" if it is a pointer or reference to the first
4167/// character of a string literal.
4168template<typename LValue>
4169static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregor8e55ed12012-03-11 02:23:56 +00004170 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith80d4b552011-12-28 19:48:30 +00004171 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4172}
4173
4174/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4175/// GCC as we can manage.
4176static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4177 QualType ArgType = Arg->getType();
4178
4179 // __builtin_constant_p always has one operand. The rules which gcc follows
4180 // are not precisely documented, but are as follows:
4181 //
4182 // - If the operand is of integral, floating, complex or enumeration type,
4183 // and can be folded to a known value of that type, it returns 1.
4184 // - If the operand and can be folded to a pointer to the first character
4185 // of a string literal (or such a pointer cast to an integral type), it
4186 // returns 1.
4187 //
4188 // Otherwise, it returns 0.
4189 //
4190 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4191 // its support for this does not currently work.
4192 if (ArgType->isIntegralOrEnumerationType()) {
4193 Expr::EvalResult Result;
4194 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4195 return false;
4196
4197 APValue &V = Result.Val;
4198 if (V.getKind() == APValue::Int)
4199 return true;
4200
4201 return EvaluateBuiltinConstantPForLValue(V);
4202 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4203 return Arg->isEvaluatable(Ctx);
4204 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4205 LValue LV;
4206 Expr::EvalStatus Status;
4207 EvalInfo Info(Ctx, Status);
4208 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4209 : EvaluatePointer(Arg, LV, Info)) &&
4210 !Status.HasSideEffects)
4211 return EvaluateBuiltinConstantPForLValue(LV);
4212 }
4213
4214 // Anything else isn't considered to be sufficiently constant.
4215 return false;
4216}
4217
John McCall42c8f872010-05-10 23:27:23 +00004218/// Retrieves the "underlying object type" of the given expression,
4219/// as used by __builtin_object_size.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004220QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4221 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4222 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall42c8f872010-05-10 23:27:23 +00004223 return VD->getType();
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004224 } else if (const Expr *E = B.get<const Expr*>()) {
4225 if (isa<CompoundLiteralExpr>(E))
4226 return E->getType();
John McCall42c8f872010-05-10 23:27:23 +00004227 }
4228
4229 return QualType();
4230}
4231
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004232bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall42c8f872010-05-10 23:27:23 +00004233 LValue Base;
Richard Smithc6794852012-05-23 04:13:20 +00004234
4235 {
4236 // The operand of __builtin_object_size is never evaluated for side-effects.
4237 // If there are any, but we can determine the pointed-to object anyway, then
4238 // ignore the side-effects.
4239 SpeculativeEvaluationRAII SpeculativeEval(Info);
4240 if (!EvaluatePointer(E->getArg(0), Base, Info))
4241 return false;
4242 }
John McCall42c8f872010-05-10 23:27:23 +00004243
4244 // If we can prove the base is null, lower to zero now.
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004245 if (!Base.getLValueBase()) return Success(0, E);
John McCall42c8f872010-05-10 23:27:23 +00004246
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004247 QualType T = GetObjectType(Base.getLValueBase());
John McCall42c8f872010-05-10 23:27:23 +00004248 if (T.isNull() ||
4249 T->isIncompleteType() ||
Eli Friedman13578692010-08-05 02:49:48 +00004250 T->isFunctionType() ||
John McCall42c8f872010-05-10 23:27:23 +00004251 T->isVariablyModifiedType() ||
4252 T->isDependentType())
Richard Smithf48fdb02011-12-09 22:58:01 +00004253 return Error(E);
John McCall42c8f872010-05-10 23:27:23 +00004254
4255 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4256 CharUnits Offset = Base.getLValueOffset();
4257
4258 if (!Offset.isNegative() && Offset <= Size)
4259 Size -= Offset;
4260 else
4261 Size = CharUnits::Zero();
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00004262 return Success(Size, E);
John McCall42c8f872010-05-10 23:27:23 +00004263}
4264
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004265bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith2c39d712012-04-13 00:45:38 +00004266 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner019f4e82008-10-06 05:28:25 +00004267 default:
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004268 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004269
4270 case Builtin::BI__builtin_object_size: {
John McCall42c8f872010-05-10 23:27:23 +00004271 if (TryEvaluateBuiltinObjectSize(E))
4272 return true;
Mike Stump64eda9e2009-10-26 18:35:08 +00004273
Richard Smith8ae4ec22012-08-07 04:16:51 +00004274 // If evaluating the argument has side-effects, we can't determine the size
4275 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4276 // handle all cases where the expression has side-effects.
Fariborz Jahanian393c2472009-11-05 18:03:03 +00004277 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004278 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattnercf184652009-11-03 19:48:51 +00004279 return Success(-1ULL, E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004280 return Success(0, E);
4281 }
Mike Stumpc4c90452009-10-27 22:09:17 +00004282
Richard Smithc6794852012-05-23 04:13:20 +00004283 // Expression had no side effects, but we couldn't statically determine the
4284 // size of the referenced object.
Richard Smithf48fdb02011-12-09 22:58:01 +00004285 return Error(E);
Mike Stump64eda9e2009-10-26 18:35:08 +00004286 }
4287
Benjamin Kramerd1900572012-10-06 14:42:22 +00004288 case Builtin::BI__builtin_bswap16:
Richard Smith70d38f32012-09-28 20:20:52 +00004289 case Builtin::BI__builtin_bswap32:
4290 case Builtin::BI__builtin_bswap64: {
4291 APSInt Val;
4292 if (!EvaluateInteger(E->getArg(0), Val, Info))
4293 return false;
4294
4295 return Success(Val.byteSwap(), E);
4296 }
4297
Chris Lattner019f4e82008-10-06 05:28:25 +00004298 case Builtin::BI__builtin_classify_type:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004299 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump1eb44332009-09-09 15:08:12 +00004300
Richard Smith80d4b552011-12-28 19:48:30 +00004301 case Builtin::BI__builtin_constant_p:
4302 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smithe052d462011-12-09 02:04:48 +00004303
Chris Lattner21fb98e2009-09-23 06:06:36 +00004304 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00004305 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00004306 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattner21fb98e2009-09-23 06:06:36 +00004307 return Success(Operand, E);
4308 }
Eli Friedmanc4a26382010-02-13 00:10:10 +00004309
4310 case Builtin::BI__builtin_expect:
4311 return Visit(E->getArg(0));
Richard Smith40b993a2012-01-18 03:06:12 +00004312
Douglas Gregor5726d402010-09-10 06:27:15 +00004313 case Builtin::BIstrlen:
Richard Smith40b993a2012-01-18 03:06:12 +00004314 // A call to strlen is not a constant expression.
Richard Smith80ad52f2013-01-02 11:42:31 +00004315 if (Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00004316 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith40b993a2012-01-18 03:06:12 +00004317 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4318 else
Richard Smith5cfc7d82012-03-15 04:53:45 +00004319 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith40b993a2012-01-18 03:06:12 +00004320 // Fall through.
Douglas Gregor5726d402010-09-10 06:27:15 +00004321 case Builtin::BI__builtin_strlen:
4322 // As an extension, we support strlen() and __builtin_strlen() as constant
4323 // expressions when the argument is a string literal.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00004324 if (const StringLiteral *S
Douglas Gregor5726d402010-09-10 06:27:15 +00004325 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4326 // The string literal may have embedded null characters. Find the first
4327 // one and truncate there.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004328 StringRef Str = S->getString();
4329 StringRef::size_type Pos = Str.find(0);
4330 if (Pos != StringRef::npos)
Douglas Gregor5726d402010-09-10 06:27:15 +00004331 Str = Str.substr(0, Pos);
4332
4333 return Success(Str.size(), E);
4334 }
4335
Richard Smithf48fdb02011-12-09 22:58:01 +00004336 return Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004337
Richard Smith2c39d712012-04-13 00:45:38 +00004338 case Builtin::BI__atomic_always_lock_free:
Richard Smithfafbf062012-04-11 17:55:32 +00004339 case Builtin::BI__atomic_is_lock_free:
4340 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedman454b57a2011-10-17 21:44:23 +00004341 APSInt SizeVal;
4342 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4343 return false;
4344
4345 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4346 // of two less than the maximum inline atomic width, we know it is
4347 // lock-free. If the size isn't a power of two, or greater than the
4348 // maximum alignment where we promote atomics, we know it is not lock-free
4349 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4350 // the answer can only be determined at runtime; for example, 16-byte
4351 // atomics have lock-free implementations on some, but not all,
4352 // x86-64 processors.
4353
4354 // Check power-of-two.
4355 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith2c39d712012-04-13 00:45:38 +00004356 if (Size.isPowerOfTwo()) {
4357 // Check against inlining width.
4358 unsigned InlineWidthBits =
4359 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4360 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4361 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4362 Size == CharUnits::One() ||
4363 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4364 Expr::NPC_NeverValueDependent))
4365 // OK, we will inline appropriately-aligned operations of this size,
4366 // and _Atomic(T) is appropriately-aligned.
4367 return Success(1, E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004368
Richard Smith2c39d712012-04-13 00:45:38 +00004369 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4370 castAs<PointerType>()->getPointeeType();
4371 if (!PointeeType->isIncompleteType() &&
4372 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4373 // OK, we will inline operations on this object.
4374 return Success(1, E);
4375 }
4376 }
4377 }
Eli Friedman454b57a2011-10-17 21:44:23 +00004378
Richard Smith2c39d712012-04-13 00:45:38 +00004379 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4380 Success(0, E) : Error(E);
Eli Friedman454b57a2011-10-17 21:44:23 +00004381 }
Chris Lattner019f4e82008-10-06 05:28:25 +00004382 }
Chris Lattner4c4867e2008-07-12 00:38:25 +00004383}
Anders Carlsson650c92f2008-07-08 15:34:11 +00004384
Richard Smith625b8072011-10-31 01:37:14 +00004385static bool HasSameBase(const LValue &A, const LValue &B) {
4386 if (!A.getLValueBase())
4387 return !B.getLValueBase();
4388 if (!B.getLValueBase())
4389 return false;
4390
Richard Smith1bf9a9e2011-11-12 22:28:03 +00004391 if (A.getLValueBase().getOpaqueValue() !=
4392 B.getLValueBase().getOpaqueValue()) {
Richard Smith625b8072011-10-31 01:37:14 +00004393 const Decl *ADecl = GetLValueBaseDecl(A);
4394 if (!ADecl)
4395 return false;
4396 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith9a17a682011-11-07 05:07:52 +00004397 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith625b8072011-10-31 01:37:14 +00004398 return false;
4399 }
4400
4401 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smith83587db2012-02-15 02:18:13 +00004402 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith625b8072011-10-31 01:37:14 +00004403}
4404
Richard Smith7b48a292012-02-01 05:53:12 +00004405/// Perform the given integer operation, which is known to need at most BitWidth
4406/// bits, and check for overflow in the original type (if that type was not an
4407/// unsigned type).
4408template<typename Operation>
4409static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4410 const APSInt &LHS, const APSInt &RHS,
4411 unsigned BitWidth, Operation Op) {
4412 if (LHS.isUnsigned())
4413 return Op(LHS, RHS);
4414
4415 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4416 APSInt Result = Value.trunc(LHS.getBitWidth());
Fariborz Jahanianad48a502013-01-24 22:11:45 +00004417 if (Result.extend(BitWidth) != Value) {
4418 if (Info.getIntOverflowCheckMode())
4419 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
4420 diag::warn_integer_constant_overflow)
4421 << Result.toString(10) << E->getType();
4422 else
4423 HandleOverflow(Info, E, Value, E->getType());
4424 }
Richard Smith7b48a292012-02-01 05:53:12 +00004425 return Result;
4426}
4427
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004428namespace {
Richard Smithc49bd112011-10-28 17:51:58 +00004429
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004430/// \brief Data recursive integer evaluator of certain binary operators.
4431///
4432/// We use a data recursive algorithm for binary operators so that we are able
4433/// to handle extreme cases of chained binary operators without causing stack
4434/// overflow.
4435class DataRecursiveIntBinOpEvaluator {
4436 struct EvalResult {
4437 APValue Val;
4438 bool Failed;
4439
4440 EvalResult() : Failed(false) { }
4441
4442 void swap(EvalResult &RHS) {
4443 Val.swap(RHS.Val);
4444 Failed = RHS.Failed;
4445 RHS.Failed = false;
4446 }
4447 };
4448
4449 struct Job {
4450 const Expr *E;
4451 EvalResult LHSResult; // meaningful only for binary operator expression.
4452 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4453
4454 Job() : StoredInfo(0) { }
4455 void startSpeculativeEval(EvalInfo &Info) {
4456 OldEvalStatus = Info.EvalStatus;
4457 Info.EvalStatus.Diag = 0;
4458 StoredInfo = &Info;
4459 }
4460 ~Job() {
4461 if (StoredInfo) {
4462 StoredInfo->EvalStatus = OldEvalStatus;
4463 }
4464 }
4465 private:
4466 EvalInfo *StoredInfo; // non-null if status changed.
4467 Expr::EvalStatus OldEvalStatus;
4468 };
4469
4470 SmallVector<Job, 16> Queue;
4471
4472 IntExprEvaluator &IntEval;
4473 EvalInfo &Info;
4474 APValue &FinalResult;
4475
4476public:
4477 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4478 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4479
4480 /// \brief True if \param E is a binary operator that we are going to handle
4481 /// data recursively.
4482 /// We handle binary operators that are comma, logical, or that have operands
4483 /// with integral or enumeration type.
4484 static bool shouldEnqueue(const BinaryOperator *E) {
4485 return E->getOpcode() == BO_Comma ||
4486 E->isLogicalOp() ||
4487 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4488 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedmana6afa762008-11-13 06:09:17 +00004489 }
4490
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004491 bool Traverse(const BinaryOperator *E) {
4492 enqueue(E);
4493 EvalResult PrevResult;
Richard Trieub7783052012-03-21 23:30:30 +00004494 while (!Queue.empty())
4495 process(PrevResult);
4496
4497 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004498
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004499 FinalResult.swap(PrevResult.Val);
4500 return true;
4501 }
4502
4503private:
4504 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4505 return IntEval.Success(Value, E, Result);
4506 }
4507 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4508 return IntEval.Success(Value, E, Result);
4509 }
4510 bool Error(const Expr *E) {
4511 return IntEval.Error(E);
4512 }
4513 bool Error(const Expr *E, diag::kind D) {
4514 return IntEval.Error(E, D);
4515 }
4516
4517 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4518 return Info.CCEDiag(E, D);
4519 }
4520
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004521 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4522 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004523 bool &SuppressRHSDiags);
4524
4525 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4526 const BinaryOperator *E, APValue &Result);
4527
4528 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4529 Result.Failed = !Evaluate(Result.Val, Info, E);
4530 if (Result.Failed)
4531 Result.Val = APValue();
4532 }
4533
Richard Trieub7783052012-03-21 23:30:30 +00004534 void process(EvalResult &Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004535
4536 void enqueue(const Expr *E) {
4537 E = E->IgnoreParens();
4538 Queue.resize(Queue.size()+1);
4539 Queue.back().E = E;
4540 Queue.back().Kind = Job::AnyExprKind;
4541 }
4542};
4543
4544}
4545
4546bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004547 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004548 bool &SuppressRHSDiags) {
4549 if (E->getOpcode() == BO_Comma) {
4550 // Ignore LHS but note if we could not evaluate it.
4551 if (LHSResult.Failed)
4552 Info.EvalStatus.HasSideEffects = true;
4553 return true;
4554 }
4555
4556 if (E->isLogicalOp()) {
4557 bool lhsResult;
4558 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004559 // We were able to evaluate the LHS, see if we can get away with not
4560 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004561 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004562 Success(lhsResult, E, LHSResult.Val);
4563 return false; // Ignore RHS
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004564 }
4565 } else {
4566 // Since we weren't able to evaluate the left hand side, it
4567 // must have had side effects.
4568 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004569
4570 // We can't evaluate the LHS; however, sometimes the result
4571 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4572 // Don't ignore RHS and suppress diagnostics from this arm.
4573 SuppressRHSDiags = true;
4574 }
4575
4576 return true;
4577 }
4578
4579 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4580 E->getRHS()->getType()->isIntegralOrEnumerationType());
4581
4582 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004583 return false; // Ignore RHS;
4584
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004585 return true;
4586}
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004587
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004588bool DataRecursiveIntBinOpEvaluator::
4589 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4590 const BinaryOperator *E, APValue &Result) {
4591 if (E->getOpcode() == BO_Comma) {
4592 if (RHSResult.Failed)
4593 return false;
4594 Result = RHSResult.Val;
4595 return true;
4596 }
4597
4598 if (E->isLogicalOp()) {
4599 bool lhsResult, rhsResult;
4600 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4601 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4602
4603 if (LHSIsOK) {
4604 if (RHSIsOK) {
4605 if (E->getOpcode() == BO_LOr)
4606 return Success(lhsResult || rhsResult, E, Result);
4607 else
4608 return Success(lhsResult && rhsResult, E, Result);
4609 }
4610 } else {
4611 if (RHSIsOK) {
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004612 // We can't evaluate the LHS; however, sometimes the result
4613 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4614 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004615 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004616 }
4617 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004618
Argyrios Kyrtzidis2fa975c2012-02-25 23:21:37 +00004619 return false;
4620 }
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004621
4622 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4623 E->getRHS()->getType()->isIntegralOrEnumerationType());
4624
4625 if (LHSResult.Failed || RHSResult.Failed)
4626 return false;
4627
4628 const APValue &LHSVal = LHSResult.Val;
4629 const APValue &RHSVal = RHSResult.Val;
4630
4631 // Handle cases like (unsigned long)&a + 4.
4632 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4633 Result = LHSVal;
4634 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4635 RHSVal.getInt().getZExtValue());
4636 if (E->getOpcode() == BO_Add)
4637 Result.getLValueOffset() += AdditionalOffset;
4638 else
4639 Result.getLValueOffset() -= AdditionalOffset;
4640 return true;
4641 }
4642
4643 // Handle cases like 4 + (unsigned long)&a
4644 if (E->getOpcode() == BO_Add &&
4645 RHSVal.isLValue() && LHSVal.isInt()) {
4646 Result = RHSVal;
4647 Result.getLValueOffset() += CharUnits::fromQuantity(
4648 LHSVal.getInt().getZExtValue());
4649 return true;
4650 }
4651
4652 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4653 // Handle (intptr_t)&&A - (intptr_t)&&B.
4654 if (!LHSVal.getLValueOffset().isZero() ||
4655 !RHSVal.getLValueOffset().isZero())
4656 return false;
4657 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4658 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4659 if (!LHSExpr || !RHSExpr)
4660 return false;
4661 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4662 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4663 if (!LHSAddrExpr || !RHSAddrExpr)
4664 return false;
4665 // Make sure both labels come from the same function.
4666 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4667 RHSAddrExpr->getLabel()->getDeclContext())
4668 return false;
4669 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4670 return true;
4671 }
4672
4673 // All the following cases expect both operands to be an integer
4674 if (!LHSVal.isInt() || !RHSVal.isInt())
4675 return Error(E);
4676
4677 const APSInt &LHS = LHSVal.getInt();
4678 APSInt RHS = RHSVal.getInt();
4679
4680 switch (E->getOpcode()) {
4681 default:
4682 return Error(E);
4683 case BO_Mul:
4684 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4685 LHS.getBitWidth() * 2,
4686 std::multiplies<APSInt>()), E,
4687 Result);
4688 case BO_Add:
4689 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4690 LHS.getBitWidth() + 1,
4691 std::plus<APSInt>()), E, Result);
4692 case BO_Sub:
4693 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4694 LHS.getBitWidth() + 1,
4695 std::minus<APSInt>()), E, Result);
4696 case BO_And: return Success(LHS & RHS, E, Result);
4697 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4698 case BO_Or: return Success(LHS | RHS, E, Result);
4699 case BO_Div:
4700 case BO_Rem:
4701 if (RHS == 0)
4702 return Error(E, diag::note_expr_divide_by_zero);
4703 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4704 // not actually undefined behavior in C++11 due to a language defect.
4705 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4706 LHS.isSigned() && LHS.isMinSignedValue())
4707 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4708 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4709 Result);
4710 case BO_Shl: {
David Tweed7a834212013-01-07 16:43:27 +00004711 if (Info.getLangOpts().OpenCL)
4712 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Goulya52d2782013-01-29 15:09:40 +00004713 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed7a834212013-01-07 16:43:27 +00004714 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
4715 RHS.isUnsigned());
4716 else if (RHS.isSigned() && RHS.isNegative()) {
4717 // During constant-folding, a negative shift is an opposite shift. Such
4718 // a shift is not a constant expression.
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004719 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4720 RHS = -RHS;
4721 goto shift_right;
4722 }
4723
4724 shift_left:
4725 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4726 // the shifted type.
4727 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4728 if (SA != RHS) {
4729 CCEDiag(E, diag::note_constexpr_large_shift)
4730 << RHS << E->getType() << LHS.getBitWidth();
4731 } else if (LHS.isSigned()) {
4732 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4733 // operand, and must not overflow the corresponding unsigned type.
4734 if (LHS.isNegative())
4735 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4736 else if (LHS.countLeadingZeros() < SA)
4737 CCEDiag(E, diag::note_constexpr_lshift_discards);
4738 }
4739
4740 return Success(LHS << SA, E, Result);
4741 }
4742 case BO_Shr: {
David Tweed7a834212013-01-07 16:43:27 +00004743 if (Info.getLangOpts().OpenCL)
4744 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Goulya52d2782013-01-29 15:09:40 +00004745 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed7a834212013-01-07 16:43:27 +00004746 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
4747 RHS.isUnsigned());
4748 else if (RHS.isSigned() && RHS.isNegative()) {
4749 // During constant-folding, a negative shift is an opposite shift. Such a
4750 // shift is not a constant expression.
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004751 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4752 RHS = -RHS;
4753 goto shift_left;
4754 }
4755
4756 shift_right:
4757 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4758 // shifted type.
4759 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4760 if (SA != RHS)
4761 CCEDiag(E, diag::note_constexpr_large_shift)
4762 << RHS << E->getType() << LHS.getBitWidth();
4763
4764 return Success(LHS >> SA, E, Result);
4765 }
4766
4767 case BO_LT: return Success(LHS < RHS, E, Result);
4768 case BO_GT: return Success(LHS > RHS, E, Result);
4769 case BO_LE: return Success(LHS <= RHS, E, Result);
4770 case BO_GE: return Success(LHS >= RHS, E, Result);
4771 case BO_EQ: return Success(LHS == RHS, E, Result);
4772 case BO_NE: return Success(LHS != RHS, E, Result);
4773 }
4774}
4775
Richard Trieub7783052012-03-21 23:30:30 +00004776void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004777 Job &job = Queue.back();
4778
4779 switch (job.Kind) {
4780 case Job::AnyExprKind: {
4781 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4782 if (shouldEnqueue(Bop)) {
4783 job.Kind = Job::BinOpKind;
4784 enqueue(Bop->getLHS());
Richard Trieub7783052012-03-21 23:30:30 +00004785 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004786 }
4787 }
4788
4789 EvaluateExpr(job.E, Result);
4790 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004791 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004792 }
4793
4794 case Job::BinOpKind: {
4795 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004796 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004797 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004798 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004799 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004800 }
4801 if (SuppressRHSDiags)
4802 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis9293fff2012-03-22 02:13:06 +00004803 job.LHSResult.swap(Result);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004804 job.Kind = Job::BinOpVisitedLHSKind;
4805 enqueue(Bop->getRHS());
Richard Trieub7783052012-03-21 23:30:30 +00004806 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004807 }
4808
4809 case Job::BinOpVisitedLHSKind: {
4810 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4811 EvalResult RHS;
4812 RHS.swap(Result);
Richard Trieub7783052012-03-21 23:30:30 +00004813 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004814 Queue.pop_back();
Richard Trieub7783052012-03-21 23:30:30 +00004815 return;
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00004816 }
4817 }
4818
4819 llvm_unreachable("Invalid Job::Kind!");
4820}
4821
4822bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4823 if (E->isAssignmentOp())
4824 return Error(E);
4825
4826 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4827 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedmana6afa762008-11-13 06:09:17 +00004828
Anders Carlsson286f85e2008-11-16 07:17:21 +00004829 QualType LHSTy = E->getLHS()->getType();
4830 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar4087e242009-01-29 06:43:41 +00004831
4832 if (LHSTy->isAnyComplexType()) {
4833 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCallf4cf1a12010-05-07 17:22:02 +00004834 ComplexValue LHS, RHS;
Daniel Dunbar4087e242009-01-29 06:43:41 +00004835
Richard Smith745f5142012-01-27 01:14:48 +00004836 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4837 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar4087e242009-01-29 06:43:41 +00004838 return false;
4839
Richard Smith745f5142012-01-27 01:14:48 +00004840 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar4087e242009-01-29 06:43:41 +00004841 return false;
4842
4843 if (LHS.isComplexFloat()) {
Mike Stump1eb44332009-09-09 15:08:12 +00004844 APFloat::cmpResult CR_r =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004845 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump1eb44332009-09-09 15:08:12 +00004846 APFloat::cmpResult CR_i =
Daniel Dunbar4087e242009-01-29 06:43:41 +00004847 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4848
John McCall2de56d12010-08-25 11:45:40 +00004849 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004850 return Success((CR_r == APFloat::cmpEqual &&
4851 CR_i == APFloat::cmpEqual), E);
4852 else {
John McCall2de56d12010-08-25 11:45:40 +00004853 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004854 "Invalid complex comparison.");
Mike Stump1eb44332009-09-09 15:08:12 +00004855 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004856 CR_r == APFloat::cmpLessThan ||
4857 CR_r == APFloat::cmpUnordered) ||
Mike Stump1eb44332009-09-09 15:08:12 +00004858 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wangfc39dc42010-04-29 05:53:29 +00004859 CR_i == APFloat::cmpLessThan ||
4860 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar131eb432009-02-19 09:06:44 +00004861 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004862 } else {
John McCall2de56d12010-08-25 11:45:40 +00004863 if (E->getOpcode() == BO_EQ)
Daniel Dunbar131eb432009-02-19 09:06:44 +00004864 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4865 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4866 else {
John McCall2de56d12010-08-25 11:45:40 +00004867 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar131eb432009-02-19 09:06:44 +00004868 "Invalid compex comparison.");
4869 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4870 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4871 }
Daniel Dunbar4087e242009-01-29 06:43:41 +00004872 }
4873 }
Mike Stump1eb44332009-09-09 15:08:12 +00004874
Anders Carlsson286f85e2008-11-16 07:17:21 +00004875 if (LHSTy->isRealFloatingType() &&
4876 RHSTy->isRealFloatingType()) {
4877 APFloat RHS(0.0), LHS(0.0);
Mike Stump1eb44332009-09-09 15:08:12 +00004878
Richard Smith745f5142012-01-27 01:14:48 +00004879 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4880 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlsson286f85e2008-11-16 07:17:21 +00004881 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004882
Richard Smith745f5142012-01-27 01:14:48 +00004883 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlsson286f85e2008-11-16 07:17:21 +00004884 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00004885
Anders Carlsson286f85e2008-11-16 07:17:21 +00004886 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson529569e2008-11-16 22:46:56 +00004887
Anders Carlsson286f85e2008-11-16 07:17:21 +00004888 switch (E->getOpcode()) {
4889 default:
David Blaikieb219cfc2011-09-23 05:06:16 +00004890 llvm_unreachable("Invalid binary operator!");
John McCall2de56d12010-08-25 11:45:40 +00004891 case BO_LT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004892 return Success(CR == APFloat::cmpLessThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004893 case BO_GT:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004894 return Success(CR == APFloat::cmpGreaterThan, E);
John McCall2de56d12010-08-25 11:45:40 +00004895 case BO_LE:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004896 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004897 case BO_GE:
Mike Stump1eb44332009-09-09 15:08:12 +00004898 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar131eb432009-02-19 09:06:44 +00004899 E);
John McCall2de56d12010-08-25 11:45:40 +00004900 case BO_EQ:
Daniel Dunbar131eb432009-02-19 09:06:44 +00004901 return Success(CR == APFloat::cmpEqual, E);
John McCall2de56d12010-08-25 11:45:40 +00004902 case BO_NE:
Mike Stump1eb44332009-09-09 15:08:12 +00004903 return Success(CR == APFloat::cmpGreaterThan
Mon P Wangfc39dc42010-04-29 05:53:29 +00004904 || CR == APFloat::cmpLessThan
4905 || CR == APFloat::cmpUnordered, E);
Anders Carlsson286f85e2008-11-16 07:17:21 +00004906 }
Anders Carlsson286f85e2008-11-16 07:17:21 +00004907 }
Mike Stump1eb44332009-09-09 15:08:12 +00004908
Eli Friedmanad02d7d2009-04-28 19:17:36 +00004909 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith625b8072011-10-31 01:37:14 +00004910 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith745f5142012-01-27 01:14:48 +00004911 LValue LHSValue, RHSValue;
4912
4913 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4914 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson3068d112008-11-16 19:01:22 +00004915 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004916
Richard Smith745f5142012-01-27 01:14:48 +00004917 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson3068d112008-11-16 19:01:22 +00004918 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004919
Richard Smith625b8072011-10-31 01:37:14 +00004920 // Reject differing bases from the normal codepath; we special-case
4921 // comparisons to null.
4922 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedman65639282012-01-04 23:13:47 +00004923 if (E->getOpcode() == BO_Sub) {
4924 // Handle &&A - &&B.
Eli Friedman65639282012-01-04 23:13:47 +00004925 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4926 return false;
4927 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramer7b2f93c2012-10-03 14:15:39 +00004928 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedman65639282012-01-04 23:13:47 +00004929 if (!LHSExpr || !RHSExpr)
4930 return false;
4931 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4932 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4933 if (!LHSAddrExpr || !RHSAddrExpr)
4934 return false;
Eli Friedman5930a4c2012-01-05 23:59:40 +00004935 // Make sure both labels come from the same function.
4936 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4937 RHSAddrExpr->getLabel()->getDeclContext())
4938 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00004939 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedman65639282012-01-04 23:13:47 +00004940 return true;
4941 }
Richard Smith9e36b532011-10-31 05:11:32 +00004942 // Inequalities and subtractions between unrelated pointers have
4943 // unspecified or undefined behavior.
Eli Friedman5bc86102009-06-14 02:17:33 +00004944 if (!E->isEqualityOp())
Richard Smithf48fdb02011-12-09 22:58:01 +00004945 return Error(E);
Eli Friedmanffbda402011-10-31 22:28:05 +00004946 // A constant address may compare equal to the address of a symbol.
4947 // The one exception is that address of an object cannot compare equal
Eli Friedmanc45061b2011-10-31 22:54:30 +00004948 // to a null pointer constant.
Eli Friedmanffbda402011-10-31 22:28:05 +00004949 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4950 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf48fdb02011-12-09 22:58:01 +00004951 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004952 // It's implementation-defined whether distinct literals will have
Richard Smithb02e4622012-02-01 01:42:44 +00004953 // distinct addresses. In clang, the result of such a comparison is
4954 // unspecified, so it is not a constant expression. However, we do know
4955 // that the address of a literal will be non-null.
Richard Smith74f46342011-11-04 01:10:57 +00004956 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4957 LHSValue.Base && RHSValue.Base)
Richard Smithf48fdb02011-12-09 22:58:01 +00004958 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004959 // We can't tell whether weak symbols will end up pointing to the same
4960 // object.
4961 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf48fdb02011-12-09 22:58:01 +00004962 return Error(E);
Richard Smith9e36b532011-10-31 05:11:32 +00004963 // Pointers with different bases cannot represent the same object.
Eli Friedmanc45061b2011-10-31 22:54:30 +00004964 // (Note that clang defaults to -fmerge-all-constants, which can
4965 // lead to inconsistent results for comparisons involving the address
4966 // of a constant; this generally doesn't matter in practice.)
Richard Smith9e36b532011-10-31 05:11:32 +00004967 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman5bc86102009-06-14 02:17:33 +00004968 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00004969
Richard Smith15efc4d2012-02-01 08:10:20 +00004970 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4971 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4972
Richard Smithf15fda02012-02-02 01:16:57 +00004973 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4974 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4975
John McCall2de56d12010-08-25 11:45:40 +00004976 if (E->getOpcode() == BO_Sub) {
Richard Smithf15fda02012-02-02 01:16:57 +00004977 // C++11 [expr.add]p6:
4978 // Unless both pointers point to elements of the same array object, or
4979 // one past the last element of the array object, the behavior is
4980 // undefined.
4981 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4982 !AreElementsOfSameArray(getType(LHSValue.Base),
4983 LHSDesignator, RHSDesignator))
4984 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4985
Chris Lattner4992bdd2010-04-20 17:13:14 +00004986 QualType Type = E->getLHS()->getType();
4987 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson3068d112008-11-16 19:01:22 +00004988
Richard Smith180f4792011-11-10 06:34:14 +00004989 CharUnits ElementSize;
Richard Smith74e1ad92012-02-16 02:46:34 +00004990 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smith180f4792011-11-10 06:34:14 +00004991 return false;
Eli Friedmana1f47c42009-03-23 04:38:34 +00004992
Richard Smith15efc4d2012-02-01 08:10:20 +00004993 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
4994 // and produce incorrect results when it overflows. Such behavior
4995 // appears to be non-conforming, but is common, so perhaps we should
4996 // assume the standard intended for such cases to be undefined behavior
4997 // and check for them.
Richard Smith625b8072011-10-31 01:37:14 +00004998
Richard Smith15efc4d2012-02-01 08:10:20 +00004999 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5000 // overflow in the final conversion to ptrdiff_t.
5001 APSInt LHS(
5002 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5003 APSInt RHS(
5004 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5005 APSInt ElemSize(
5006 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5007 APSInt TrueResult = (LHS - RHS) / ElemSize;
5008 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5009
5010 if (Result.extend(65) != TrueResult)
5011 HandleOverflow(Info, E, TrueResult, E->getType());
5012 return Success(Result, E);
5013 }
Richard Smith82f28582012-01-31 06:41:30 +00005014
5015 // C++11 [expr.rel]p3:
5016 // Pointers to void (after pointer conversions) can be compared, with a
5017 // result defined as follows: If both pointers represent the same
5018 // address or are both the null pointer value, the result is true if the
5019 // operator is <= or >= and false otherwise; otherwise the result is
5020 // unspecified.
5021 // We interpret this as applying to pointers to *cv* void.
5022 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smithf15fda02012-02-02 01:16:57 +00005023 E->isRelationalOp())
Richard Smith82f28582012-01-31 06:41:30 +00005024 CCEDiag(E, diag::note_constexpr_void_comparison);
5025
Richard Smithf15fda02012-02-02 01:16:57 +00005026 // C++11 [expr.rel]p2:
5027 // - If two pointers point to non-static data members of the same object,
5028 // or to subobjects or array elements fo such members, recursively, the
5029 // pointer to the later declared member compares greater provided the
5030 // two members have the same access control and provided their class is
5031 // not a union.
5032 // [...]
5033 // - Otherwise pointer comparisons are unspecified.
5034 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5035 E->isRelationalOp()) {
5036 bool WasArrayIndex;
5037 unsigned Mismatch =
5038 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5039 RHSDesignator, WasArrayIndex);
5040 // At the point where the designators diverge, the comparison has a
5041 // specified value if:
5042 // - we are comparing array indices
5043 // - we are comparing fields of a union, or fields with the same access
5044 // Otherwise, the result is unspecified and thus the comparison is not a
5045 // constant expression.
5046 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5047 Mismatch < RHSDesignator.Entries.size()) {
5048 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5049 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5050 if (!LF && !RF)
5051 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5052 else if (!LF)
5053 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5054 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5055 << RF->getParent() << RF;
5056 else if (!RF)
5057 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5058 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5059 << LF->getParent() << LF;
5060 else if (!LF->getParent()->isUnion() &&
5061 LF->getAccess() != RF->getAccess())
5062 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5063 << LF << LF->getAccess() << RF << RF->getAccess()
5064 << LF->getParent();
5065 }
5066 }
5067
Eli Friedmana3169882012-04-16 04:30:08 +00005068 // The comparison here must be unsigned, and performed with the same
5069 // width as the pointer.
Eli Friedmana3169882012-04-16 04:30:08 +00005070 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5071 uint64_t CompareLHS = LHSOffset.getQuantity();
5072 uint64_t CompareRHS = RHSOffset.getQuantity();
5073 assert(PtrSize <= 64 && "Unexpected pointer width");
5074 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5075 CompareLHS &= Mask;
5076 CompareRHS &= Mask;
5077
Eli Friedman28503762012-04-16 19:23:57 +00005078 // If there is a base and this is a relational operator, we can only
5079 // compare pointers within the object in question; otherwise, the result
5080 // depends on where the object is located in memory.
5081 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5082 QualType BaseTy = getType(LHSValue.Base);
5083 if (BaseTy->isIncompleteType())
5084 return Error(E);
5085 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5086 uint64_t OffsetLimit = Size.getQuantity();
5087 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5088 return Error(E);
5089 }
5090
Richard Smith625b8072011-10-31 01:37:14 +00005091 switch (E->getOpcode()) {
5092 default: llvm_unreachable("missing comparison operator");
Eli Friedmana3169882012-04-16 04:30:08 +00005093 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5094 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5095 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5096 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5097 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5098 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmanad02d7d2009-04-28 19:17:36 +00005099 }
Anders Carlsson3068d112008-11-16 19:01:22 +00005100 }
5101 }
Richard Smithb02e4622012-02-01 01:42:44 +00005102
5103 if (LHSTy->isMemberPointerType()) {
5104 assert(E->isEqualityOp() && "unexpected member pointer operation");
5105 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5106
5107 MemberPtr LHSValue, RHSValue;
5108
5109 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5110 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5111 return false;
5112
5113 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5114 return false;
5115
5116 // C++11 [expr.eq]p2:
5117 // If both operands are null, they compare equal. Otherwise if only one is
5118 // null, they compare unequal.
5119 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5120 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5121 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5122 }
5123
5124 // Otherwise if either is a pointer to a virtual member function, the
5125 // result is unspecified.
5126 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5127 if (MD->isVirtual())
5128 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5129 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5130 if (MD->isVirtual())
5131 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5132
5133 // Otherwise they compare equal if and only if they would refer to the
5134 // same member of the same most derived object or the same subobject if
5135 // they were dereferenced with a hypothetical object of the associated
5136 // class type.
5137 bool Equal = LHSValue == RHSValue;
5138 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5139 }
5140
Richard Smith26f2cac2012-02-14 22:35:28 +00005141 if (LHSTy->isNullPtrType()) {
5142 assert(E->isComparisonOp() && "unexpected nullptr operation");
5143 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5144 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5145 // are compared, the result is true of the operator is <=, >= or ==, and
5146 // false otherwise.
5147 BinaryOperator::Opcode Opcode = E->getOpcode();
5148 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5149 }
5150
Argyrios Kyrtzidiscc2f77a2012-03-15 18:07:16 +00005151 assert((!LHSTy->isIntegralOrEnumerationType() ||
5152 !RHSTy->isIntegralOrEnumerationType()) &&
5153 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5154 // We can't continue from here for non-integral types.
5155 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005156}
5157
Ken Dyck8b752f12010-01-27 17:10:57 +00005158CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl5d484e82009-11-23 17:18:46 +00005159 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5160 // result shall be the alignment of the referenced type."
5161 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5162 T = Ref->getPointeeType();
Chad Rosier9f1210c2011-07-26 07:03:04 +00005163
5164 // __alignof is defined to return the preferred alignment.
5165 return Info.Ctx.toCharUnitsFromBits(
5166 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattnere9feb472009-01-24 21:09:06 +00005167}
5168
Ken Dyck8b752f12010-01-27 17:10:57 +00005169CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattneraf707ab2009-01-24 21:53:27 +00005170 E = E->IgnoreParens();
5171
5172 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump1eb44332009-09-09 15:08:12 +00005173 // to 1 in those cases.
Chris Lattneraf707ab2009-01-24 21:53:27 +00005174 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005175 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5176 /*RefAsPointee*/true);
Eli Friedmana1f47c42009-03-23 04:38:34 +00005177
Chris Lattneraf707ab2009-01-24 21:53:27 +00005178 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck8b752f12010-01-27 17:10:57 +00005179 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5180 /*RefAsPointee*/true);
Chris Lattneraf707ab2009-01-24 21:53:27 +00005181
Chris Lattnere9feb472009-01-24 21:09:06 +00005182 return GetAlignOfType(E->getType());
5183}
5184
5185
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005186/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5187/// a result as the expression's type.
5188bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5189 const UnaryExprOrTypeTraitExpr *E) {
5190 switch(E->getKind()) {
5191 case UETT_AlignOf: {
Chris Lattnere9feb472009-01-24 21:09:06 +00005192 if (E->isArgumentType())
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005193 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005194 else
Ken Dyck4f3bc8f2011-03-11 02:13:43 +00005195 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattnere9feb472009-01-24 21:09:06 +00005196 }
Eli Friedmana1f47c42009-03-23 04:38:34 +00005197
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005198 case UETT_VecStep: {
5199 QualType Ty = E->getTypeOfArgument();
Sebastian Redl05189992008-11-11 17:56:53 +00005200
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005201 if (Ty->isVectorType()) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00005202 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedmana1f47c42009-03-23 04:38:34 +00005203
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005204 // The vec_step built-in functions that take a 3-component
5205 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5206 if (n == 3)
5207 n = 4;
Eli Friedmanf2da9df2009-01-24 22:19:05 +00005208
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005209 return Success(n, E);
5210 } else
5211 return Success(1, E);
5212 }
5213
5214 case UETT_SizeOf: {
5215 QualType SrcTy = E->getTypeOfArgument();
5216 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5217 // the result is the size of the referenced type."
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005218 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5219 SrcTy = Ref->getPointeeType();
5220
Richard Smith180f4792011-11-10 06:34:14 +00005221 CharUnits Sizeof;
Richard Smith74e1ad92012-02-16 02:46:34 +00005222 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005223 return false;
Richard Smith180f4792011-11-10 06:34:14 +00005224 return Success(Sizeof, E);
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00005225 }
5226 }
5227
5228 llvm_unreachable("unknown expr/type trait");
Chris Lattnerfcee0012008-07-11 21:24:13 +00005229}
5230
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005231bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005232 CharUnits Result;
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005233 unsigned n = OOE->getNumComponents();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005234 if (n == 0)
Richard Smithf48fdb02011-12-09 22:58:01 +00005235 return Error(OOE);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005236 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005237 for (unsigned i = 0; i != n; ++i) {
5238 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5239 switch (ON.getKind()) {
5240 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005241 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005242 APSInt IdxResult;
5243 if (!EvaluateInteger(Idx, IdxResult, Info))
5244 return false;
5245 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5246 if (!AT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005247 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005248 CurrentType = AT->getElementType();
5249 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5250 Result += IdxResult.getSExtValue() * ElementSize;
5251 break;
5252 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005253
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005254 case OffsetOfExpr::OffsetOfNode::Field: {
5255 FieldDecl *MemberDecl = ON.getField();
5256 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005257 if (!RT)
5258 return Error(OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005259 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005260 if (RD->isInvalidDecl()) return false;
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005261 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCallba4f5d52011-01-20 07:57:12 +00005262 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005263 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyckfb1e3bc2011-01-18 01:56:16 +00005264 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005265 CurrentType = MemberDecl->getType().getNonReferenceType();
5266 break;
5267 }
Richard Smithf48fdb02011-12-09 22:58:01 +00005268
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005269 case OffsetOfExpr::OffsetOfNode::Identifier:
5270 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf48fdb02011-12-09 22:58:01 +00005271
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005272 case OffsetOfExpr::OffsetOfNode::Base: {
5273 CXXBaseSpecifier *BaseSpec = ON.getBase();
5274 if (BaseSpec->isVirtual())
Richard Smithf48fdb02011-12-09 22:58:01 +00005275 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005276
5277 // Find the layout of the class whose base we are looking into.
5278 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf48fdb02011-12-09 22:58:01 +00005279 if (!RT)
5280 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005281 RecordDecl *RD = RT->getDecl();
John McCall8d59dee2012-05-01 00:38:49 +00005282 if (RD->isInvalidDecl()) return false;
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005283 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5284
5285 // Find the base class itself.
5286 CurrentType = BaseSpec->getType();
5287 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5288 if (!BaseRT)
Richard Smithf48fdb02011-12-09 22:58:01 +00005289 return Error(OOE);
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005290
5291 // Add the offset to the base.
Ken Dyck7c7f8202011-01-26 02:17:08 +00005292 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregorcc8a5d52010-04-29 00:18:15 +00005293 break;
5294 }
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005295 }
5296 }
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005297 return Success(Result, OOE);
Douglas Gregor8ecdb652010-04-28 22:16:22 +00005298}
5299
Chris Lattnerb542afe2008-07-11 19:10:17 +00005300bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005301 switch (E->getOpcode()) {
5302 default:
5303 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5304 // See C99 6.6p3.
5305 return Error(E);
5306 case UO_Extension:
5307 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5308 // If so, we could clear the diagnostic ID.
5309 return Visit(E->getSubExpr());
5310 case UO_Plus:
5311 // The result is just the value.
5312 return Visit(E->getSubExpr());
5313 case UO_Minus: {
5314 if (!Visit(E->getSubExpr()))
5315 return false;
5316 if (!Result.isInt()) return Error(E);
Richard Smith789f9b62012-01-31 04:08:20 +00005317 const APSInt &Value = Result.getInt();
5318 if (Value.isSigned() && Value.isMinSignedValue())
5319 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5320 E->getType());
5321 return Success(-Value, E);
Richard Smithf48fdb02011-12-09 22:58:01 +00005322 }
5323 case UO_Not: {
5324 if (!Visit(E->getSubExpr()))
5325 return false;
5326 if (!Result.isInt()) return Error(E);
5327 return Success(~Result.getInt(), E);
5328 }
5329 case UO_LNot: {
Eli Friedmana6afa762008-11-13 06:09:17 +00005330 bool bres;
Richard Smithc49bd112011-10-28 17:51:58 +00005331 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedmana6afa762008-11-13 06:09:17 +00005332 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005333 return Success(!bres, E);
Eli Friedmana6afa762008-11-13 06:09:17 +00005334 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005335 }
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005336}
Mike Stump1eb44332009-09-09 15:08:12 +00005337
Chris Lattner732b2232008-07-12 01:15:53 +00005338/// HandleCast - This is used to evaluate implicit or explicit casts where the
5339/// result type is integer.
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005340bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5341 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson82206e22008-11-30 18:14:57 +00005342 QualType DestType = E->getType();
Daniel Dunbarb92dac82009-02-19 22:16:29 +00005343 QualType SrcType = SubExpr->getType();
Anders Carlsson82206e22008-11-30 18:14:57 +00005344
Eli Friedman46a52322011-03-25 00:43:55 +00005345 switch (E->getCastKind()) {
Eli Friedman46a52322011-03-25 00:43:55 +00005346 case CK_BaseToDerived:
5347 case CK_DerivedToBase:
5348 case CK_UncheckedDerivedToBase:
5349 case CK_Dynamic:
5350 case CK_ToUnion:
5351 case CK_ArrayToPointerDecay:
5352 case CK_FunctionToPointerDecay:
5353 case CK_NullToPointer:
5354 case CK_NullToMemberPointer:
5355 case CK_BaseToDerivedMemberPointer:
5356 case CK_DerivedToBaseMemberPointer:
John McCall4d4e5c12012-02-15 01:22:51 +00005357 case CK_ReinterpretMemberPointer:
Eli Friedman46a52322011-03-25 00:43:55 +00005358 case CK_ConstructorConversion:
5359 case CK_IntegralToPointer:
5360 case CK_ToVoid:
5361 case CK_VectorSplat:
5362 case CK_IntegralToFloating:
5363 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005364 case CK_CPointerToObjCPointerCast:
5365 case CK_BlockPointerToObjCPointerCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005366 case CK_AnyPointerToBlockPointerCast:
5367 case CK_ObjCObjectLValueCast:
5368 case CK_FloatingRealToComplex:
5369 case CK_FloatingComplexToReal:
5370 case CK_FloatingComplexCast:
5371 case CK_FloatingComplexToIntegralComplex:
5372 case CK_IntegralRealToComplex:
5373 case CK_IntegralComplexCast:
5374 case CK_IntegralComplexToFloatingComplex:
Eli Friedmana6c66ce2012-08-31 00:14:07 +00005375 case CK_BuiltinFnToFnPtr:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005376 case CK_ZeroToOCLEvent:
Eli Friedman46a52322011-03-25 00:43:55 +00005377 llvm_unreachable("invalid cast kind for integral value");
5378
Eli Friedmane50c2972011-03-25 19:07:11 +00005379 case CK_BitCast:
Eli Friedman46a52322011-03-25 00:43:55 +00005380 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005381 case CK_LValueBitCast:
John McCall33e56f32011-09-10 06:18:15 +00005382 case CK_ARCProduceObject:
5383 case CK_ARCConsumeObject:
5384 case CK_ARCReclaimReturnedObject:
5385 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005386 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf48fdb02011-12-09 22:58:01 +00005387 return Error(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005388
Richard Smith7d580a42012-01-17 21:17:26 +00005389 case CK_UserDefinedConversion:
Eli Friedman46a52322011-03-25 00:43:55 +00005390 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005391 case CK_AtomicToNonAtomic:
5392 case CK_NonAtomicToAtomic:
Eli Friedman46a52322011-03-25 00:43:55 +00005393 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005394 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman46a52322011-03-25 00:43:55 +00005395
5396 case CK_MemberPointerToBoolean:
5397 case CK_PointerToBoolean:
5398 case CK_IntegralToBoolean:
5399 case CK_FloatingToBoolean:
5400 case CK_FloatingComplexToBoolean:
5401 case CK_IntegralComplexToBoolean: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005402 bool BoolResult;
Richard Smithc49bd112011-10-28 17:51:58 +00005403 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman4efaa272008-11-12 09:44:48 +00005404 return false;
Daniel Dunbar131eb432009-02-19 09:06:44 +00005405 return Success(BoolResult, E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005406 }
5407
Eli Friedman46a52322011-03-25 00:43:55 +00005408 case CK_IntegralCast: {
Chris Lattner732b2232008-07-12 01:15:53 +00005409 if (!Visit(SubExpr))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005410 return false;
Daniel Dunbara2cfd342009-01-29 06:16:07 +00005411
Eli Friedmanbe265702009-02-20 01:15:07 +00005412 if (!Result.isInt()) {
Eli Friedman65639282012-01-04 23:13:47 +00005413 // Allow casts of address-of-label differences if they are no-ops
5414 // or narrowing. (The narrowing case isn't actually guaranteed to
5415 // be constant-evaluatable except in some narrow cases which are hard
5416 // to detect here. We let it through on the assumption the user knows
5417 // what they are doing.)
5418 if (Result.isAddrLabelDiff())
5419 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedmanbe265702009-02-20 01:15:07 +00005420 // Only allow casts of lvalues if they are lossless.
5421 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5422 }
Daniel Dunbar30c37f42009-02-19 20:17:33 +00005423
Richard Smithf72fccf2012-01-30 22:27:01 +00005424 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5425 Result.getInt()), E);
Chris Lattner732b2232008-07-12 01:15:53 +00005426 }
Mike Stump1eb44332009-09-09 15:08:12 +00005427
Eli Friedman46a52322011-03-25 00:43:55 +00005428 case CK_PointerToIntegral: {
Richard Smithc216a012011-12-12 12:46:16 +00005429 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5430
John McCallefdb83e2010-05-07 21:00:08 +00005431 LValue LV;
Chris Lattner87eae5e2008-07-11 22:52:41 +00005432 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnerb542afe2008-07-11 19:10:17 +00005433 return false;
Eli Friedman4efaa272008-11-12 09:44:48 +00005434
Daniel Dunbardd211642009-02-19 22:24:01 +00005435 if (LV.getLValueBase()) {
5436 // Only allow based lvalue casts if they are lossless.
Richard Smithf72fccf2012-01-30 22:27:01 +00005437 // FIXME: Allow a larger integer size than the pointer size, and allow
5438 // narrowing back down to pointer width in subsequent integral casts.
5439 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbardd211642009-02-19 22:24:01 +00005440 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf48fdb02011-12-09 22:58:01 +00005441 return Error(E);
Eli Friedman4efaa272008-11-12 09:44:48 +00005442
Richard Smithb755a9d2011-11-16 07:18:12 +00005443 LV.Designator.setInvalid();
John McCallefdb83e2010-05-07 21:00:08 +00005444 LV.moveInto(Result);
Daniel Dunbardd211642009-02-19 22:24:01 +00005445 return true;
5446 }
5447
Ken Dycka7305832010-01-15 12:37:54 +00005448 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5449 SrcType);
Richard Smithf72fccf2012-01-30 22:27:01 +00005450 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlsson2bad1682008-07-08 14:30:00 +00005451 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005452
Eli Friedman46a52322011-03-25 00:43:55 +00005453 case CK_IntegralComplexToReal: {
John McCallf4cf1a12010-05-07 17:22:02 +00005454 ComplexValue C;
Eli Friedman1725f682009-04-22 19:23:09 +00005455 if (!EvaluateComplex(SubExpr, C, Info))
5456 return false;
Eli Friedman46a52322011-03-25 00:43:55 +00005457 return Success(C.getComplexIntReal(), E);
Eli Friedman1725f682009-04-22 19:23:09 +00005458 }
Eli Friedman2217c872009-02-22 11:46:18 +00005459
Eli Friedman46a52322011-03-25 00:43:55 +00005460 case CK_FloatingToIntegral: {
5461 APFloat F(0.0);
5462 if (!EvaluateFloat(SubExpr, F, Info))
5463 return false;
Chris Lattner732b2232008-07-12 01:15:53 +00005464
Richard Smithc1c5f272011-12-13 06:39:58 +00005465 APSInt Value;
5466 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5467 return false;
5468 return Success(Value, E);
Eli Friedman46a52322011-03-25 00:43:55 +00005469 }
5470 }
Mike Stump1eb44332009-09-09 15:08:12 +00005471
Eli Friedman46a52322011-03-25 00:43:55 +00005472 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlssona25ae3d2008-07-08 14:35:21 +00005473}
Anders Carlsson2bad1682008-07-08 14:30:00 +00005474
Eli Friedman722c7172009-02-28 03:59:05 +00005475bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5476 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005477 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005478 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5479 return false;
5480 if (!LV.isComplexInt())
5481 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005482 return Success(LV.getComplexIntReal(), E);
5483 }
5484
5485 return Visit(E->getSubExpr());
5486}
5487
Eli Friedman664a1042009-02-27 04:45:43 +00005488bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman722c7172009-02-28 03:59:05 +00005489 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005490 ComplexValue LV;
Richard Smithf48fdb02011-12-09 22:58:01 +00005491 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5492 return false;
5493 if (!LV.isComplexInt())
5494 return Error(E);
Eli Friedman722c7172009-02-28 03:59:05 +00005495 return Success(LV.getComplexIntImag(), E);
5496 }
5497
Richard Smith8327fad2011-10-24 18:44:57 +00005498 VisitIgnoredValue(E->getSubExpr());
Eli Friedman664a1042009-02-27 04:45:43 +00005499 return Success(0, E);
5500}
5501
Douglas Gregoree8aff02011-01-04 17:33:58 +00005502bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5503 return Success(E->getPackLength(), E);
5504}
5505
Sebastian Redl295995c2010-09-10 20:55:47 +00005506bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5507 return Success(E->getValue(), E);
5508}
5509
Chris Lattnerf5eeb052008-07-11 18:11:29 +00005510//===----------------------------------------------------------------------===//
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005511// Float Evaluation
5512//===----------------------------------------------------------------------===//
5513
5514namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005515class FloatExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005516 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005517 APFloat &Result;
5518public:
5519 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005520 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005521
Richard Smith1aa0be82012-03-03 22:46:17 +00005522 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005523 Result = V.getFloat();
5524 return true;
5525 }
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005526
Richard Smith51201882011-12-30 21:15:51 +00005527 bool ZeroInitialization(const Expr *E) {
Richard Smithf10d9172011-10-11 21:43:33 +00005528 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5529 return true;
5530 }
5531
Chris Lattner019f4e82008-10-06 05:28:25 +00005532 bool VisitCallExpr(const CallExpr *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005533
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005534 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005535 bool VisitBinaryOperator(const BinaryOperator *E);
5536 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005537 bool VisitCastExpr(const CastExpr *E);
Eli Friedman2217c872009-02-22 11:46:18 +00005538
John McCallabd3a852010-05-07 22:08:54 +00005539 bool VisitUnaryReal(const UnaryOperator *E);
5540 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedmanba98d6b2009-03-23 04:56:01 +00005541
Richard Smith51201882011-12-30 21:15:51 +00005542 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005543};
5544} // end anonymous namespace
5545
5546static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005547 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005548 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005549}
5550
Jay Foad4ba2a172011-01-12 09:06:06 +00005551static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCalldb7b72a2010-02-28 13:00:19 +00005552 QualType ResultTy,
5553 const Expr *Arg,
5554 bool SNaN,
5555 llvm::APFloat &Result) {
5556 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5557 if (!S) return false;
5558
5559 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5560
5561 llvm::APInt fill;
5562
5563 // Treat empty strings as if they were zero.
5564 if (S->getString().empty())
5565 fill = llvm::APInt(32, 0);
5566 else if (S->getString().getAsInteger(0, fill))
5567 return false;
5568
5569 if (SNaN)
5570 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5571 else
5572 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5573 return true;
5574}
5575
Chris Lattner019f4e82008-10-06 05:28:25 +00005576bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith180f4792011-11-10 06:34:14 +00005577 switch (E->isBuiltinCall()) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005578 default:
5579 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5580
Chris Lattner019f4e82008-10-06 05:28:25 +00005581 case Builtin::BI__builtin_huge_val:
5582 case Builtin::BI__builtin_huge_valf:
5583 case Builtin::BI__builtin_huge_vall:
5584 case Builtin::BI__builtin_inf:
5585 case Builtin::BI__builtin_inff:
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005586 case Builtin::BI__builtin_infl: {
5587 const llvm::fltSemantics &Sem =
5588 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner34a74ab2008-10-06 05:53:16 +00005589 Result = llvm::APFloat::getInf(Sem);
5590 return true;
Daniel Dunbar7cbed032008-10-14 05:41:12 +00005591 }
Mike Stump1eb44332009-09-09 15:08:12 +00005592
John McCalldb7b72a2010-02-28 13:00:19 +00005593 case Builtin::BI__builtin_nans:
5594 case Builtin::BI__builtin_nansf:
5595 case Builtin::BI__builtin_nansl:
Richard Smithf48fdb02011-12-09 22:58:01 +00005596 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5597 true, Result))
5598 return Error(E);
5599 return true;
John McCalldb7b72a2010-02-28 13:00:19 +00005600
Chris Lattner9e621712008-10-06 06:31:58 +00005601 case Builtin::BI__builtin_nan:
5602 case Builtin::BI__builtin_nanf:
5603 case Builtin::BI__builtin_nanl:
Mike Stump4572bab2009-05-30 03:56:50 +00005604 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner9e621712008-10-06 06:31:58 +00005605 // can't constant fold it.
Richard Smithf48fdb02011-12-09 22:58:01 +00005606 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5607 false, Result))
5608 return Error(E);
5609 return true;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005610
5611 case Builtin::BI__builtin_fabs:
5612 case Builtin::BI__builtin_fabsf:
5613 case Builtin::BI__builtin_fabsl:
5614 if (!EvaluateFloat(E->getArg(0), Result, Info))
5615 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005616
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005617 if (Result.isNegative())
5618 Result.changeSign();
5619 return true;
5620
Mike Stump1eb44332009-09-09 15:08:12 +00005621 case Builtin::BI__builtin_copysign:
5622 case Builtin::BI__builtin_copysignf:
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005623 case Builtin::BI__builtin_copysignl: {
5624 APFloat RHS(0.);
5625 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5626 !EvaluateFloat(E->getArg(1), RHS, Info))
5627 return false;
5628 Result.copySign(RHS);
5629 return true;
5630 }
Chris Lattner019f4e82008-10-06 05:28:25 +00005631 }
5632}
5633
John McCallabd3a852010-05-07 22:08:54 +00005634bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005635 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5636 ComplexValue CV;
5637 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5638 return false;
5639 Result = CV.FloatReal;
5640 return true;
5641 }
5642
5643 return Visit(E->getSubExpr());
John McCallabd3a852010-05-07 22:08:54 +00005644}
5645
5646bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman43efa312010-08-14 20:52:13 +00005647 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5648 ComplexValue CV;
5649 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5650 return false;
5651 Result = CV.FloatImag;
5652 return true;
5653 }
5654
Richard Smith8327fad2011-10-24 18:44:57 +00005655 VisitIgnoredValue(E->getSubExpr());
Eli Friedman43efa312010-08-14 20:52:13 +00005656 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5657 Result = llvm::APFloat::getZero(Sem);
John McCallabd3a852010-05-07 22:08:54 +00005658 return true;
5659}
5660
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005661bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005662 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005663 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005664 case UO_Plus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005665 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCall2de56d12010-08-25 11:45:40 +00005666 case UO_Minus:
Richard Smith7993e8a2011-10-30 23:17:09 +00005667 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5668 return false;
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005669 Result.changeSign();
5670 return true;
5671 }
5672}
Chris Lattner019f4e82008-10-06 05:28:25 +00005673
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005674bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005675 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5676 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman7f92f032009-11-16 04:25:37 +00005677
Daniel Dunbar5db4b3f2008-10-16 03:51:50 +00005678 APFloat RHS(0.0);
Richard Smith745f5142012-01-27 01:14:48 +00005679 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5680 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005681 return false;
Richard Smith745f5142012-01-27 01:14:48 +00005682 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005683 return false;
5684
5685 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005686 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005687 case BO_Mul:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005688 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005689 break;
John McCall2de56d12010-08-25 11:45:40 +00005690 case BO_Add:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005691 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005692 break;
John McCall2de56d12010-08-25 11:45:40 +00005693 case BO_Sub:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005694 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005695 break;
John McCall2de56d12010-08-25 11:45:40 +00005696 case BO_Div:
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005697 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smith7b48a292012-02-01 05:53:12 +00005698 break;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005699 }
Richard Smith7b48a292012-02-01 05:53:12 +00005700
5701 if (Result.isInfinity() || Result.isNaN())
5702 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5703 return true;
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005704}
5705
5706bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5707 Result = E->getValue();
5708 return true;
5709}
5710
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005711bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5712 const Expr* SubExpr = E->getSubExpr();
Mike Stump1eb44332009-09-09 15:08:12 +00005713
Eli Friedman2a523ee2011-03-25 00:54:52 +00005714 switch (E->getCastKind()) {
5715 default:
Richard Smithc49bd112011-10-28 17:51:58 +00005716 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman2a523ee2011-03-25 00:54:52 +00005717
5718 case CK_IntegralToFloating: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005719 APSInt IntResult;
Richard Smithc1c5f272011-12-13 06:39:58 +00005720 return EvaluateInteger(SubExpr, IntResult, Info) &&
5721 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5722 E->getType(), Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005723 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005724
5725 case CK_FloatingCast: {
Eli Friedman4efaa272008-11-12 09:44:48 +00005726 if (!Visit(SubExpr))
5727 return false;
Richard Smithc1c5f272011-12-13 06:39:58 +00005728 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5729 Result);
Eli Friedman4efaa272008-11-12 09:44:48 +00005730 }
John McCallf3ea8cf2010-11-14 08:17:51 +00005731
Eli Friedman2a523ee2011-03-25 00:54:52 +00005732 case CK_FloatingComplexToReal: {
John McCallf3ea8cf2010-11-14 08:17:51 +00005733 ComplexValue V;
5734 if (!EvaluateComplex(SubExpr, V, Info))
5735 return false;
5736 Result = V.getComplexFloatReal();
5737 return true;
5738 }
Eli Friedman2a523ee2011-03-25 00:54:52 +00005739 }
Eli Friedman4efaa272008-11-12 09:44:48 +00005740}
5741
Eli Friedmand8bfe7f2008-08-22 00:06:13 +00005742//===----------------------------------------------------------------------===//
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005743// Complex Evaluation (for float and integer)
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005744//===----------------------------------------------------------------------===//
5745
5746namespace {
Benjamin Kramer770b4a82009-11-28 19:03:38 +00005747class ComplexExprEvaluator
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005748 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCallf4cf1a12010-05-07 17:22:02 +00005749 ComplexValue &Result;
Mike Stump1eb44332009-09-09 15:08:12 +00005750
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005751public:
John McCallf4cf1a12010-05-07 17:22:02 +00005752 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005753 : ExprEvaluatorBaseTy(info), Result(Result) {}
5754
Richard Smith1aa0be82012-03-03 22:46:17 +00005755 bool Success(const APValue &V, const Expr *e) {
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005756 Result.setFrom(V);
5757 return true;
5758 }
Mike Stump1eb44332009-09-09 15:08:12 +00005759
Eli Friedman7ead5c72012-01-10 04:58:17 +00005760 bool ZeroInitialization(const Expr *E);
5761
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005762 //===--------------------------------------------------------------------===//
5763 // Visitor Methods
5764 //===--------------------------------------------------------------------===//
5765
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005766 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005767 bool VisitCastExpr(const CastExpr *E);
John McCallf4cf1a12010-05-07 17:22:02 +00005768 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00005769 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman7ead5c72012-01-10 04:58:17 +00005770 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005771};
5772} // end anonymous namespace
5773
John McCallf4cf1a12010-05-07 17:22:02 +00005774static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5775 EvalInfo &Info) {
Richard Smithc49bd112011-10-28 17:51:58 +00005776 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005777 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00005778}
5779
Eli Friedman7ead5c72012-01-10 04:58:17 +00005780bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek890f0f12012-08-23 20:46:57 +00005781 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedman7ead5c72012-01-10 04:58:17 +00005782 if (ElemTy->isRealFloatingType()) {
5783 Result.makeComplexFloat();
5784 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5785 Result.FloatReal = Zero;
5786 Result.FloatImag = Zero;
5787 } else {
5788 Result.makeComplexInt();
5789 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5790 Result.IntReal = Zero;
5791 Result.IntImag = Zero;
5792 }
5793 return true;
5794}
5795
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005796bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5797 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005798
5799 if (SubExpr->getType()->isRealFloatingType()) {
5800 Result.makeComplexFloat();
5801 APFloat &Imag = Result.FloatImag;
5802 if (!EvaluateFloat(SubExpr, Imag, Info))
5803 return false;
5804
5805 Result.FloatReal = APFloat(Imag.getSemantics());
5806 return true;
5807 } else {
5808 assert(SubExpr->getType()->isIntegerType() &&
5809 "Unexpected imaginary literal.");
5810
5811 Result.makeComplexInt();
5812 APSInt &Imag = Result.IntImag;
5813 if (!EvaluateInteger(SubExpr, Imag, Info))
5814 return false;
5815
5816 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5817 return true;
5818 }
5819}
5820
Peter Collingbourne8cad3042011-05-13 03:29:01 +00005821bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005822
John McCall8786da72010-12-14 17:51:41 +00005823 switch (E->getCastKind()) {
5824 case CK_BitCast:
John McCall8786da72010-12-14 17:51:41 +00005825 case CK_BaseToDerived:
5826 case CK_DerivedToBase:
5827 case CK_UncheckedDerivedToBase:
5828 case CK_Dynamic:
5829 case CK_ToUnion:
5830 case CK_ArrayToPointerDecay:
5831 case CK_FunctionToPointerDecay:
5832 case CK_NullToPointer:
5833 case CK_NullToMemberPointer:
5834 case CK_BaseToDerivedMemberPointer:
5835 case CK_DerivedToBaseMemberPointer:
5836 case CK_MemberPointerToBoolean:
John McCall4d4e5c12012-02-15 01:22:51 +00005837 case CK_ReinterpretMemberPointer:
John McCall8786da72010-12-14 17:51:41 +00005838 case CK_ConstructorConversion:
5839 case CK_IntegralToPointer:
5840 case CK_PointerToIntegral:
5841 case CK_PointerToBoolean:
5842 case CK_ToVoid:
5843 case CK_VectorSplat:
5844 case CK_IntegralCast:
5845 case CK_IntegralToBoolean:
5846 case CK_IntegralToFloating:
5847 case CK_FloatingToIntegral:
5848 case CK_FloatingToBoolean:
5849 case CK_FloatingCast:
John McCall1d9b3b22011-09-09 05:25:32 +00005850 case CK_CPointerToObjCPointerCast:
5851 case CK_BlockPointerToObjCPointerCast:
John McCall8786da72010-12-14 17:51:41 +00005852 case CK_AnyPointerToBlockPointerCast:
5853 case CK_ObjCObjectLValueCast:
5854 case CK_FloatingComplexToReal:
5855 case CK_FloatingComplexToBoolean:
5856 case CK_IntegralComplexToReal:
5857 case CK_IntegralComplexToBoolean:
John McCall33e56f32011-09-10 06:18:15 +00005858 case CK_ARCProduceObject:
5859 case CK_ARCConsumeObject:
5860 case CK_ARCReclaimReturnedObject:
5861 case CK_ARCExtendBlockObject:
Douglas Gregorac1303e2012-02-22 05:02:47 +00005862 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedmana6c66ce2012-08-31 00:14:07 +00005863 case CK_BuiltinFnToFnPtr:
Guy Benyeie6b9d802013-01-20 12:31:11 +00005864 case CK_ZeroToOCLEvent:
John McCall8786da72010-12-14 17:51:41 +00005865 llvm_unreachable("invalid cast kind for complex value");
John McCall2bb5d002010-11-13 09:02:35 +00005866
John McCall8786da72010-12-14 17:51:41 +00005867 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00005868 case CK_AtomicToNonAtomic:
5869 case CK_NonAtomicToAtomic:
John McCall8786da72010-12-14 17:51:41 +00005870 case CK_NoOp:
Richard Smithc49bd112011-10-28 17:51:58 +00005871 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCall8786da72010-12-14 17:51:41 +00005872
5873 case CK_Dependent:
Eli Friedman46a52322011-03-25 00:43:55 +00005874 case CK_LValueBitCast:
John McCall8786da72010-12-14 17:51:41 +00005875 case CK_UserDefinedConversion:
Richard Smithf48fdb02011-12-09 22:58:01 +00005876 return Error(E);
John McCall8786da72010-12-14 17:51:41 +00005877
5878 case CK_FloatingRealToComplex: {
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005879 APFloat &Real = Result.FloatReal;
John McCall8786da72010-12-14 17:51:41 +00005880 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005881 return false;
5882
John McCall8786da72010-12-14 17:51:41 +00005883 Result.makeComplexFloat();
5884 Result.FloatImag = APFloat(Real.getSemantics());
5885 return true;
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005886 }
5887
John McCall8786da72010-12-14 17:51:41 +00005888 case CK_FloatingComplexCast: {
5889 if (!Visit(E->getSubExpr()))
5890 return false;
5891
5892 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5893 QualType From
5894 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5895
Richard Smithc1c5f272011-12-13 06:39:58 +00005896 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5897 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005898 }
5899
5900 case CK_FloatingComplexToIntegralComplex: {
5901 if (!Visit(E->getSubExpr()))
5902 return false;
5903
5904 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5905 QualType From
5906 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5907 Result.makeComplexInt();
Richard Smithc1c5f272011-12-13 06:39:58 +00005908 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5909 To, Result.IntReal) &&
5910 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5911 To, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005912 }
5913
5914 case CK_IntegralRealToComplex: {
5915 APSInt &Real = Result.IntReal;
5916 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5917 return false;
5918
5919 Result.makeComplexInt();
5920 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5921 return true;
5922 }
5923
5924 case CK_IntegralComplexCast: {
5925 if (!Visit(E->getSubExpr()))
5926 return false;
5927
5928 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5929 QualType From
5930 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5931
Richard Smithf72fccf2012-01-30 22:27:01 +00005932 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5933 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCall8786da72010-12-14 17:51:41 +00005934 return true;
5935 }
5936
5937 case CK_IntegralComplexToFloatingComplex: {
5938 if (!Visit(E->getSubExpr()))
5939 return false;
5940
Ted Kremenek890f0f12012-08-23 20:46:57 +00005941 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005942 QualType From
Ted Kremenek890f0f12012-08-23 20:46:57 +00005943 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCall8786da72010-12-14 17:51:41 +00005944 Result.makeComplexFloat();
Richard Smithc1c5f272011-12-13 06:39:58 +00005945 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5946 To, Result.FloatReal) &&
5947 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5948 To, Result.FloatImag);
John McCall8786da72010-12-14 17:51:41 +00005949 }
5950 }
5951
5952 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanb2dc7f52010-08-16 23:27:44 +00005953}
5954
John McCallf4cf1a12010-05-07 17:22:02 +00005955bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00005956 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith2ad226b2011-11-16 17:22:48 +00005957 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5958
Richard Smith745f5142012-01-27 01:14:48 +00005959 bool LHSOK = Visit(E->getLHS());
5960 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCallf4cf1a12010-05-07 17:22:02 +00005961 return false;
Mike Stump1eb44332009-09-09 15:08:12 +00005962
John McCallf4cf1a12010-05-07 17:22:02 +00005963 ComplexValue RHS;
Richard Smith745f5142012-01-27 01:14:48 +00005964 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCallf4cf1a12010-05-07 17:22:02 +00005965 return false;
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005966
Daniel Dunbar3f279872009-01-29 01:32:56 +00005967 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5968 "Invalid operands to binary operator.");
Anders Carlssonccc3fce2008-11-16 21:51:21 +00005969 switch (E->getOpcode()) {
Richard Smithf48fdb02011-12-09 22:58:01 +00005970 default: return Error(E);
John McCall2de56d12010-08-25 11:45:40 +00005971 case BO_Add:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005972 if (Result.isComplexFloat()) {
5973 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5974 APFloat::rmNearestTiesToEven);
5975 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5976 APFloat::rmNearestTiesToEven);
5977 } else {
5978 Result.getComplexIntReal() += RHS.getComplexIntReal();
5979 Result.getComplexIntImag() += RHS.getComplexIntImag();
5980 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005981 break;
John McCall2de56d12010-08-25 11:45:40 +00005982 case BO_Sub:
Daniel Dunbara5fd07b2009-01-28 22:24:07 +00005983 if (Result.isComplexFloat()) {
5984 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5985 APFloat::rmNearestTiesToEven);
5986 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
5987 APFloat::rmNearestTiesToEven);
5988 } else {
5989 Result.getComplexIntReal() -= RHS.getComplexIntReal();
5990 Result.getComplexIntImag() -= RHS.getComplexIntImag();
5991 }
Daniel Dunbar3f279872009-01-29 01:32:56 +00005992 break;
John McCall2de56d12010-08-25 11:45:40 +00005993 case BO_Mul:
Daniel Dunbar3f279872009-01-29 01:32:56 +00005994 if (Result.isComplexFloat()) {
John McCallf4cf1a12010-05-07 17:22:02 +00005995 ComplexValue LHS = Result;
Daniel Dunbar3f279872009-01-29 01:32:56 +00005996 APFloat &LHS_r = LHS.getComplexFloatReal();
5997 APFloat &LHS_i = LHS.getComplexFloatImag();
5998 APFloat &RHS_r = RHS.getComplexFloatReal();
5999 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump1eb44332009-09-09 15:08:12 +00006000
Daniel Dunbar3f279872009-01-29 01:32:56 +00006001 APFloat Tmp = LHS_r;
6002 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6003 Result.getComplexFloatReal() = Tmp;
6004 Tmp = LHS_i;
6005 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6006 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6007
6008 Tmp = LHS_r;
6009 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6010 Result.getComplexFloatImag() = Tmp;
6011 Tmp = LHS_i;
6012 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6013 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6014 } else {
John McCallf4cf1a12010-05-07 17:22:02 +00006015 ComplexValue LHS = Result;
Mike Stump1eb44332009-09-09 15:08:12 +00006016 Result.getComplexIntReal() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006017 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6018 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump1eb44332009-09-09 15:08:12 +00006019 Result.getComplexIntImag() =
Daniel Dunbar3f279872009-01-29 01:32:56 +00006020 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6021 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6022 }
6023 break;
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006024 case BO_Div:
6025 if (Result.isComplexFloat()) {
6026 ComplexValue LHS = Result;
6027 APFloat &LHS_r = LHS.getComplexFloatReal();
6028 APFloat &LHS_i = LHS.getComplexFloatImag();
6029 APFloat &RHS_r = RHS.getComplexFloatReal();
6030 APFloat &RHS_i = RHS.getComplexFloatImag();
6031 APFloat &Res_r = Result.getComplexFloatReal();
6032 APFloat &Res_i = Result.getComplexFloatImag();
6033
6034 APFloat Den = RHS_r;
6035 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6036 APFloat Tmp = RHS_i;
6037 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6038 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6039
6040 Res_r = LHS_r;
6041 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6042 Tmp = LHS_i;
6043 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6044 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6045 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6046
6047 Res_i = LHS_i;
6048 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6049 Tmp = LHS_r;
6050 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6051 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6052 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6053 } else {
Richard Smithf48fdb02011-12-09 22:58:01 +00006054 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6055 return Error(E, diag::note_expr_divide_by_zero);
6056
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006057 ComplexValue LHS = Result;
6058 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6059 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6060 Result.getComplexIntReal() =
6061 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6062 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6063 Result.getComplexIntImag() =
6064 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6065 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6066 }
6067 break;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006068 }
6069
John McCallf4cf1a12010-05-07 17:22:02 +00006070 return true;
Anders Carlssonccc3fce2008-11-16 21:51:21 +00006071}
6072
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006073bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6074 // Get the operand value into 'Result'.
6075 if (!Visit(E->getSubExpr()))
6076 return false;
6077
6078 switch (E->getOpcode()) {
6079 default:
Richard Smithf48fdb02011-12-09 22:58:01 +00006080 return Error(E);
Abramo Bagnara96fc8e42010-12-11 16:05:48 +00006081 case UO_Extension:
6082 return true;
6083 case UO_Plus:
6084 // The result is always just the subexpr.
6085 return true;
6086 case UO_Minus:
6087 if (Result.isComplexFloat()) {
6088 Result.getComplexFloatReal().changeSign();
6089 Result.getComplexFloatImag().changeSign();
6090 }
6091 else {
6092 Result.getComplexIntReal() = -Result.getComplexIntReal();
6093 Result.getComplexIntImag() = -Result.getComplexIntImag();
6094 }
6095 return true;
6096 case UO_Not:
6097 if (Result.isComplexFloat())
6098 Result.getComplexFloatImag().changeSign();
6099 else
6100 Result.getComplexIntImag() = -Result.getComplexIntImag();
6101 return true;
6102 }
6103}
6104
Eli Friedman7ead5c72012-01-10 04:58:17 +00006105bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6106 if (E->getNumInits() == 2) {
6107 if (E->getType()->isComplexType()) {
6108 Result.makeComplexFloat();
6109 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6110 return false;
6111 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6112 return false;
6113 } else {
6114 Result.makeComplexInt();
6115 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6116 return false;
6117 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6118 return false;
6119 }
6120 return true;
6121 }
6122 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6123}
6124
Anders Carlsson9ad16ae2008-11-16 20:27:53 +00006125//===----------------------------------------------------------------------===//
Richard Smithaa9c3502011-12-07 00:43:50 +00006126// Void expression evaluation, primarily for a cast to void on the LHS of a
6127// comma operator
6128//===----------------------------------------------------------------------===//
6129
6130namespace {
6131class VoidExprEvaluator
6132 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6133public:
6134 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6135
Richard Smith1aa0be82012-03-03 22:46:17 +00006136 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smithaa9c3502011-12-07 00:43:50 +00006137
6138 bool VisitCastExpr(const CastExpr *E) {
6139 switch (E->getCastKind()) {
6140 default:
6141 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6142 case CK_ToVoid:
6143 VisitIgnoredValue(E->getSubExpr());
6144 return true;
6145 }
6146 }
6147};
6148} // end anonymous namespace
6149
6150static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6151 assert(E->isRValue() && E->getType()->isVoidType());
6152 return VoidExprEvaluator(Info).Visit(E);
6153}
6154
6155//===----------------------------------------------------------------------===//
Richard Smith51f47082011-10-29 00:50:52 +00006156// Top level Expr::EvaluateAsRValue method.
Chris Lattnerf5eeb052008-07-11 18:11:29 +00006157//===----------------------------------------------------------------------===//
6158
Richard Smith1aa0be82012-03-03 22:46:17 +00006159static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smithc49bd112011-10-28 17:51:58 +00006160 // In C, function designators are not lvalues, but we evaluate them as if they
6161 // are.
6162 if (E->isGLValue() || E->getType()->isFunctionType()) {
6163 LValue LV;
6164 if (!EvaluateLValue(E, LV, Info))
6165 return false;
6166 LV.moveInto(Result);
6167 } else if (E->getType()->isVectorType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006168 if (!EvaluateVector(E, Result, Info))
Nate Begeman59b5da62009-01-18 03:20:47 +00006169 return false;
Douglas Gregor575a1c92011-05-20 16:38:50 +00006170 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith1e12c592011-10-16 21:26:27 +00006171 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006172 return false;
John McCallefdb83e2010-05-07 21:00:08 +00006173 } else if (E->getType()->hasPointerRepresentation()) {
6174 LValue LV;
6175 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006176 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006177 LV.moveInto(Result);
John McCallefdb83e2010-05-07 21:00:08 +00006178 } else if (E->getType()->isRealFloatingType()) {
6179 llvm::APFloat F(0.0);
6180 if (!EvaluateFloat(E, F, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006181 return false;
Richard Smith1aa0be82012-03-03 22:46:17 +00006182 Result = APValue(F);
John McCallefdb83e2010-05-07 21:00:08 +00006183 } else if (E->getType()->isAnyComplexType()) {
6184 ComplexValue C;
6185 if (!EvaluateComplex(E, C, Info))
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006186 return false;
Richard Smith1e12c592011-10-16 21:26:27 +00006187 C.moveInto(Result);
Richard Smith69c2c502011-11-04 05:33:44 +00006188 } else if (E->getType()->isMemberPointerType()) {
Richard Smithe24f5fc2011-11-17 22:56:20 +00006189 MemberPtr P;
6190 if (!EvaluateMemberPointer(E, P, Info))
6191 return false;
6192 P.moveInto(Result);
6193 return true;
Richard Smith51201882011-12-30 21:15:51 +00006194 } else if (E->getType()->isArrayType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006195 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006196 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006197 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithcc5d4f62011-11-07 09:22:26 +00006198 return false;
Richard Smith180f4792011-11-10 06:34:14 +00006199 Result = Info.CurrentCall->Temporaries[E];
Richard Smith51201882011-12-30 21:15:51 +00006200 } else if (E->getType()->isRecordType()) {
Richard Smith180f4792011-11-10 06:34:14 +00006201 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006202 LV.set(E, Info.CurrentCall->Index);
Richard Smith180f4792011-11-10 06:34:14 +00006203 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6204 return false;
6205 Result = Info.CurrentCall->Temporaries[E];
Richard Smithaa9c3502011-12-07 00:43:50 +00006206 } else if (E->getType()->isVoidType()) {
Richard Smith80ad52f2013-01-02 11:42:31 +00006207 if (!Info.getLangOpts().CPlusPlus11)
Richard Smith5cfc7d82012-03-15 04:53:45 +00006208 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smithc1c5f272011-12-13 06:39:58 +00006209 << E->getType();
Richard Smithaa9c3502011-12-07 00:43:50 +00006210 if (!EvaluateVoid(E, Info))
6211 return false;
Richard Smith80ad52f2013-01-02 11:42:31 +00006212 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006213 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smithc1c5f272011-12-13 06:39:58 +00006214 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006215 } else {
Richard Smith5cfc7d82012-03-15 04:53:45 +00006216 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson9d4c1572008-11-22 22:56:32 +00006217 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006218 }
Anders Carlsson6dde0d52008-11-22 21:50:49 +00006219
Anders Carlsson5b45d4e2008-11-30 16:58:53 +00006220 return true;
6221}
6222
Richard Smith83587db2012-02-15 02:18:13 +00006223/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6224/// cases, the in-place evaluation is essential, since later initializers for
6225/// an object can indirectly refer to subobjects which were initialized earlier.
6226static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6227 const Expr *E, CheckConstantExpressionKind CCEK,
6228 bool AllowNonLiteralTypes) {
Richard Smith7ca48502012-02-13 22:16:19 +00006229 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smith51201882011-12-30 21:15:51 +00006230 return false;
6231
6232 if (E->isRValue()) {
Richard Smith69c2c502011-11-04 05:33:44 +00006233 // Evaluate arrays and record types in-place, so that later initializers can
6234 // refer to earlier-initialized members of the object.
Richard Smith180f4792011-11-10 06:34:14 +00006235 if (E->getType()->isArrayType())
6236 return EvaluateArray(E, This, Result, Info);
6237 else if (E->getType()->isRecordType())
6238 return EvaluateRecord(E, This, Result, Info);
Richard Smith69c2c502011-11-04 05:33:44 +00006239 }
6240
6241 // For any other type, in-place evaluation is unimportant.
Richard Smith1aa0be82012-03-03 22:46:17 +00006242 return Evaluate(Result, Info, E);
Richard Smith69c2c502011-11-04 05:33:44 +00006243}
6244
Richard Smithf48fdb02011-12-09 22:58:01 +00006245/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6246/// lvalue-to-rvalue cast if it is an lvalue.
6247static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smith51201882011-12-30 21:15:51 +00006248 if (!CheckLiteralType(Info, E))
6249 return false;
6250
Richard Smith1aa0be82012-03-03 22:46:17 +00006251 if (!::Evaluate(Result, Info, E))
Richard Smithf48fdb02011-12-09 22:58:01 +00006252 return false;
6253
6254 if (E->isGLValue()) {
6255 LValue LV;
Richard Smith1aa0be82012-03-03 22:46:17 +00006256 LV.setFrom(Info.Ctx, Result);
6257 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf48fdb02011-12-09 22:58:01 +00006258 return false;
6259 }
6260
Richard Smith1aa0be82012-03-03 22:46:17 +00006261 // Check this core constant expression is a constant expression.
Richard Smith83587db2012-02-15 02:18:13 +00006262 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf48fdb02011-12-09 22:58:01 +00006263}
Richard Smithc49bd112011-10-28 17:51:58 +00006264
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006265static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
6266 const ASTContext &Ctx, bool &IsConst) {
6267 // Fast-path evaluations of integer literals, since we sometimes see files
6268 // containing vast quantities of these.
6269 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
6270 Result.Val = APValue(APSInt(L->getValue(),
6271 L->getType()->isUnsignedIntegerType()));
6272 IsConst = true;
6273 return true;
6274 }
6275
6276 // FIXME: Evaluating values of large array and record types can cause
6277 // performance problems. Only do so in C++11 for now.
6278 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
6279 Exp->getType()->isRecordType()) &&
6280 !Ctx.getLangOpts().CPlusPlus11) {
6281 IsConst = false;
6282 return true;
6283 }
6284 return false;
6285}
6286
6287
Richard Smith51f47082011-10-29 00:50:52 +00006288/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCall56ca35d2011-02-17 10:25:35 +00006289/// any crazy technique (that has nothing to do with language standards) that
6290/// we want to. If this function returns true, it returns the folded constant
Richard Smithc49bd112011-10-28 17:51:58 +00006291/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6292/// will be applied to the result.
Richard Smith51f47082011-10-29 00:50:52 +00006293bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006294 bool IsConst;
6295 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
6296 return IsConst;
6297
Richard Smithf48fdb02011-12-09 22:58:01 +00006298 EvalInfo Info(Ctx, Result);
6299 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCall56ca35d2011-02-17 10:25:35 +00006300}
6301
Jay Foad4ba2a172011-01-12 09:06:06 +00006302bool Expr::EvaluateAsBooleanCondition(bool &Result,
6303 const ASTContext &Ctx) const {
Richard Smithc49bd112011-10-28 17:51:58 +00006304 EvalResult Scratch;
Richard Smith51f47082011-10-29 00:50:52 +00006305 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith1aa0be82012-03-03 22:46:17 +00006306 HandleConversionToBool(Scratch.Val, Result);
John McCallcd7a4452010-01-05 23:42:56 +00006307}
6308
Richard Smith80d4b552011-12-28 19:48:30 +00006309bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6310 SideEffectsKind AllowSideEffects) const {
6311 if (!getType()->isIntegralOrEnumerationType())
6312 return false;
6313
Richard Smithc49bd112011-10-28 17:51:58 +00006314 EvalResult ExprResult;
Richard Smith80d4b552011-12-28 19:48:30 +00006315 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6316 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smithc49bd112011-10-28 17:51:58 +00006317 return false;
Richard Smithf48fdb02011-12-09 22:58:01 +00006318
Richard Smithc49bd112011-10-28 17:51:58 +00006319 Result = ExprResult.Val.getInt();
6320 return true;
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006321}
6322
Jay Foad4ba2a172011-01-12 09:06:06 +00006323bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson1b782762009-04-10 04:54:13 +00006324 EvalInfo Info(Ctx, Result);
6325
John McCallefdb83e2010-05-07 21:00:08 +00006326 LValue LV;
Richard Smith83587db2012-02-15 02:18:13 +00006327 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6328 !CheckLValueConstantExpression(Info, getExprLoc(),
6329 Ctx.getLValueReferenceType(getType()), LV))
6330 return false;
6331
Richard Smith1aa0be82012-03-03 22:46:17 +00006332 LV.moveInto(Result.Val);
Richard Smith83587db2012-02-15 02:18:13 +00006333 return true;
Eli Friedmanb2f295c2009-09-13 10:17:44 +00006334}
6335
Richard Smith099e7f62011-12-19 06:19:21 +00006336bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6337 const VarDecl *VD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006338 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smith2d6a5672012-01-14 04:30:29 +00006339 // FIXME: Evaluating initializers for large array and record types can cause
6340 // performance problems. Only do so in C++11 for now.
6341 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith80ad52f2013-01-02 11:42:31 +00006342 !Ctx.getLangOpts().CPlusPlus11)
Richard Smith2d6a5672012-01-14 04:30:29 +00006343 return false;
6344
Richard Smith099e7f62011-12-19 06:19:21 +00006345 Expr::EvalStatus EStatus;
6346 EStatus.Diag = &Notes;
6347
6348 EvalInfo InitInfo(Ctx, EStatus);
6349 InitInfo.setEvaluatingDecl(VD, Value);
6350
6351 LValue LVal;
6352 LVal.set(VD);
6353
Richard Smith51201882011-12-30 21:15:51 +00006354 // C++11 [basic.start.init]p2:
6355 // Variables with static storage duration or thread storage duration shall be
6356 // zero-initialized before any other initialization takes place.
6357 // This behavior is not present in C.
David Blaikie4e4d0842012-03-11 07:00:24 +00006358 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smith51201882011-12-30 21:15:51 +00006359 !VD->getType()->isReferenceType()) {
6360 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith83587db2012-02-15 02:18:13 +00006361 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6362 /*AllowNonLiteralTypes=*/true))
Richard Smith51201882011-12-30 21:15:51 +00006363 return false;
6364 }
6365
Richard Smith83587db2012-02-15 02:18:13 +00006366 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6367 /*AllowNonLiteralTypes=*/true) ||
6368 EStatus.HasSideEffects)
6369 return false;
6370
6371 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6372 Value);
Richard Smith099e7f62011-12-19 06:19:21 +00006373}
6374
Richard Smith51f47082011-10-29 00:50:52 +00006375/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6376/// constant folded, but discard the result.
Jay Foad4ba2a172011-01-12 09:06:06 +00006377bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson4fdfb092008-12-01 06:44:05 +00006378 EvalResult Result;
Richard Smith51f47082011-10-29 00:50:52 +00006379 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattner45b6b9d2008-10-06 06:49:02 +00006380}
Anders Carlsson51fe9962008-11-22 21:04:56 +00006381
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +00006382APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006383 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006384 EvalResult EvalResult;
Fariborz Jahaniana18e70b2013-01-09 23:04:56 +00006385 EvalResult.Diag = Diag;
Richard Smith51f47082011-10-29 00:50:52 +00006386 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinc6ed7292010-12-23 01:01:28 +00006387 (void)Result;
Anders Carlsson51fe9962008-11-22 21:04:56 +00006388 assert(Result && "Could not evaluate expression");
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006389 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson51fe9962008-11-22 21:04:56 +00006390
Anders Carlsson1c0cfd42008-12-19 20:58:05 +00006391 return EvalResult.Val.getInt();
Anders Carlsson51fe9962008-11-22 21:04:56 +00006392}
John McCalld905f5a2010-05-07 05:32:02 +00006393
Fariborz Jahanianad48a502013-01-24 22:11:45 +00006394void Expr::EvaluateForOverflow(const ASTContext &Ctx,
6395 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
6396 bool IsConst;
6397 EvalResult EvalResult;
6398 EvalResult.Diag = Diags;
6399 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
6400 EvalInfo Info(Ctx, EvalResult, true);
6401 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
6402 }
6403}
6404
Abramo Bagnarae17a6432010-05-14 17:07:14 +00006405 bool Expr::EvalResult::isGlobalLValue() const {
6406 assert(Val.isLValue());
6407 return IsGlobalLValue(Val.getLValueBase());
6408 }
6409
6410
John McCalld905f5a2010-05-07 05:32:02 +00006411/// isIntegerConstantExpr - this recursive routine will test if an expression is
6412/// an integer constant expression.
6413
6414/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6415/// comma, etc
John McCalld905f5a2010-05-07 05:32:02 +00006416
6417// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smithceb59d92012-12-28 13:25:52 +00006418// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
6419// and a (possibly null) SourceLocation indicating the location of the problem.
6420//
John McCalld905f5a2010-05-07 05:32:02 +00006421// Note that to reduce code duplication, this helper does no evaluation
6422// itself; the caller checks whether the expression is evaluatable, and
6423// in the rare cases where CheckICE actually cares about the evaluated
6424// value, it calls into Evalute.
John McCalld905f5a2010-05-07 05:32:02 +00006425
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006426namespace {
6427
Richard Smithceb59d92012-12-28 13:25:52 +00006428enum ICEKind {
6429 /// This expression is an ICE.
6430 IK_ICE,
6431 /// This expression is not an ICE, but if it isn't evaluated, it's
6432 /// a legal subexpression for an ICE. This return value is used to handle
6433 /// the comma operator in C99 mode, and non-constant subexpressions.
6434 IK_ICEIfUnevaluated,
6435 /// This expression is not an ICE, and is not a legal subexpression for one.
6436 IK_NotICE
6437};
6438
John McCalld905f5a2010-05-07 05:32:02 +00006439struct ICEDiag {
Richard Smithceb59d92012-12-28 13:25:52 +00006440 ICEKind Kind;
John McCalld905f5a2010-05-07 05:32:02 +00006441 SourceLocation Loc;
6442
Richard Smithceb59d92012-12-28 13:25:52 +00006443 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCalld905f5a2010-05-07 05:32:02 +00006444};
6445
Dan Gohman3c46e8d2010-07-26 21:25:24 +00006446}
6447
Richard Smithceb59d92012-12-28 13:25:52 +00006448static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
6449
6450static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCalld905f5a2010-05-07 05:32:02 +00006451
6452static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6453 Expr::EvalResult EVResult;
Richard Smith51f47082011-10-29 00:50:52 +00006454 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smithceb59d92012-12-28 13:25:52 +00006455 !EVResult.Val.isInt())
6456 return ICEDiag(IK_NotICE, E->getLocStart());
6457
John McCalld905f5a2010-05-07 05:32:02 +00006458 return NoDiag();
6459}
6460
6461static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6462 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smithceb59d92012-12-28 13:25:52 +00006463 if (!E->getType()->isIntegralOrEnumerationType())
6464 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006465
6466 switch (E->getStmtClass()) {
John McCall63c00d72011-02-09 08:16:59 +00006467#define ABSTRACT_STMT(Node)
John McCalld905f5a2010-05-07 05:32:02 +00006468#define STMT(Node, Base) case Expr::Node##Class:
6469#define EXPR(Node, Base)
6470#include "clang/AST/StmtNodes.inc"
6471 case Expr::PredefinedExprClass:
6472 case Expr::FloatingLiteralClass:
6473 case Expr::ImaginaryLiteralClass:
6474 case Expr::StringLiteralClass:
6475 case Expr::ArraySubscriptExprClass:
6476 case Expr::MemberExprClass:
6477 case Expr::CompoundAssignOperatorClass:
6478 case Expr::CompoundLiteralExprClass:
6479 case Expr::ExtVectorElementExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006480 case Expr::DesignatedInitExprClass:
6481 case Expr::ImplicitValueInitExprClass:
6482 case Expr::ParenListExprClass:
6483 case Expr::VAArgExprClass:
6484 case Expr::AddrLabelExprClass:
6485 case Expr::StmtExprClass:
6486 case Expr::CXXMemberCallExprClass:
Peter Collingbournee08ce652011-02-09 21:07:24 +00006487 case Expr::CUDAKernelCallExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006488 case Expr::CXXDynamicCastExprClass:
6489 case Expr::CXXTypeidExprClass:
Francois Pichet9be88402010-09-08 23:47:05 +00006490 case Expr::CXXUuidofExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006491 case Expr::CXXNullPtrLiteralExprClass:
Richard Smith9fcce652012-03-07 08:35:16 +00006492 case Expr::UserDefinedLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006493 case Expr::CXXThisExprClass:
6494 case Expr::CXXThrowExprClass:
6495 case Expr::CXXNewExprClass:
6496 case Expr::CXXDeleteExprClass:
6497 case Expr::CXXPseudoDestructorExprClass:
6498 case Expr::UnresolvedLookupExprClass:
6499 case Expr::DependentScopeDeclRefExprClass:
6500 case Expr::CXXConstructExprClass:
6501 case Expr::CXXBindTemporaryExprClass:
John McCall4765fa02010-12-06 08:20:24 +00006502 case Expr::ExprWithCleanupsClass:
John McCalld905f5a2010-05-07 05:32:02 +00006503 case Expr::CXXTemporaryObjectExprClass:
6504 case Expr::CXXUnresolvedConstructExprClass:
6505 case Expr::CXXDependentScopeMemberExprClass:
6506 case Expr::UnresolvedMemberExprClass:
6507 case Expr::ObjCStringLiteralClass:
Patrick Beardeb382ec2012-04-19 00:25:12 +00006508 case Expr::ObjCBoxedExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006509 case Expr::ObjCArrayLiteralClass:
6510 case Expr::ObjCDictionaryLiteralClass:
John McCalld905f5a2010-05-07 05:32:02 +00006511 case Expr::ObjCEncodeExprClass:
6512 case Expr::ObjCMessageExprClass:
6513 case Expr::ObjCSelectorExprClass:
6514 case Expr::ObjCProtocolExprClass:
6515 case Expr::ObjCIvarRefExprClass:
6516 case Expr::ObjCPropertyRefExprClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006517 case Expr::ObjCSubscriptRefExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006518 case Expr::ObjCIsaExprClass:
6519 case Expr::ShuffleVectorExprClass:
6520 case Expr::BlockExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006521 case Expr::NoStmtClass:
John McCall7cd7d1a2010-11-15 23:31:06 +00006522 case Expr::OpaqueValueExprClass:
Douglas Gregorbe230c32011-01-03 17:17:50 +00006523 case Expr::PackExpansionExprClass:
Douglas Gregorc7793c72011-01-15 01:15:58 +00006524 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smith9a4db032012-09-12 00:56:43 +00006525 case Expr::FunctionParmPackExprClass:
Tanya Lattner61eee0c2011-06-04 00:47:47 +00006526 case Expr::AsTypeExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006527 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregor03e80032011-06-21 17:03:29 +00006528 case Expr::MaterializeTemporaryExprClass:
John McCall4b9c2d22011-11-06 09:01:30 +00006529 case Expr::PseudoObjectExprClass:
Eli Friedman276b0612011-10-11 02:20:01 +00006530 case Expr::AtomicExprClass:
Sebastian Redlcea8d962011-09-24 17:48:14 +00006531 case Expr::InitListExprClass:
Douglas Gregor01d08012012-02-07 10:09:13 +00006532 case Expr::LambdaExprClass:
Richard Smithceb59d92012-12-28 13:25:52 +00006533 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redlcea8d962011-09-24 17:48:14 +00006534
Douglas Gregoree8aff02011-01-04 17:33:58 +00006535 case Expr::SizeOfPackExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006536 case Expr::GNUNullExprClass:
6537 // GCC considers the GNU __null value to be an integral constant expression.
6538 return NoDiag();
6539
John McCall91a57552011-07-15 05:09:51 +00006540 case Expr::SubstNonTypeTemplateParmExprClass:
6541 return
6542 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6543
John McCalld905f5a2010-05-07 05:32:02 +00006544 case Expr::ParenExprClass:
6545 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbournef111d932011-04-15 00:35:48 +00006546 case Expr::GenericSelectionExprClass:
6547 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006548 case Expr::IntegerLiteralClass:
6549 case Expr::CharacterLiteralClass:
Ted Kremenekebcb57a2012-03-06 20:05:56 +00006550 case Expr::ObjCBoolLiteralExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006551 case Expr::CXXBoolLiteralExprClass:
Douglas Gregored8abf12010-07-08 06:14:04 +00006552 case Expr::CXXScalarValueInitExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006553 case Expr::UnaryTypeTraitExprClass:
Francois Pichet6ad6f282010-12-07 00:08:36 +00006554 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor4ca8ac22012-02-24 07:38:34 +00006555 case Expr::TypeTraitExprClass:
John Wiegley21ff2e52011-04-28 00:16:57 +00006556 case Expr::ArrayTypeTraitExprClass:
John Wiegley55262202011-04-25 06:54:41 +00006557 case Expr::ExpressionTraitExprClass:
Sebastian Redl2e156222010-09-10 20:55:43 +00006558 case Expr::CXXNoexceptExprClass:
John McCalld905f5a2010-05-07 05:32:02 +00006559 return NoDiag();
6560 case Expr::CallExprClass:
Sean Hunt6cf75022010-08-30 17:47:05 +00006561 case Expr::CXXOperatorCallExprClass: {
Richard Smith05830142011-10-24 22:35:48 +00006562 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6563 // constant expressions, but they can never be ICEs because an ICE cannot
6564 // contain an operand of (pointer to) function type.
John McCalld905f5a2010-05-07 05:32:02 +00006565 const CallExpr *CE = cast<CallExpr>(E);
Richard Smith180f4792011-11-10 06:34:14 +00006566 if (CE->isBuiltinCall())
John McCalld905f5a2010-05-07 05:32:02 +00006567 return CheckEvalInICE(E, Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006568 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006569 }
Richard Smith359c89d2012-02-24 22:12:32 +00006570 case Expr::DeclRefExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006571 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6572 return NoDiag();
Richard Smith359c89d2012-02-24 22:12:32 +00006573 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikie4e4d0842012-03-11 07:00:24 +00006574 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith359c89d2012-02-24 22:12:32 +00006575 D && IsConstNonVolatile(D->getType())) {
John McCalld905f5a2010-05-07 05:32:02 +00006576 // Parameter variables are never constants. Without this check,
6577 // getAnyInitializer() can find a default argument, which leads
6578 // to chaos.
6579 if (isa<ParmVarDecl>(D))
Richard Smithceb59d92012-12-28 13:25:52 +00006580 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006581
6582 // C++ 7.1.5.1p2
6583 // A variable of non-volatile const-qualified integral or enumeration
6584 // type initialized by an ICE can be used in ICEs.
6585 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithdb1822c2011-11-08 01:31:09 +00006586 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smithceb59d92012-12-28 13:25:52 +00006587 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithdb1822c2011-11-08 01:31:09 +00006588
Richard Smith099e7f62011-12-19 06:19:21 +00006589 const VarDecl *VD;
6590 // Look for a declaration of this variable that has an initializer, and
6591 // check whether it is an ICE.
6592 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6593 return NoDiag();
6594 else
Richard Smithceb59d92012-12-28 13:25:52 +00006595 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCalld905f5a2010-05-07 05:32:02 +00006596 }
6597 }
Richard Smithceb59d92012-12-28 13:25:52 +00006598 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith359c89d2012-02-24 22:12:32 +00006599 }
John McCalld905f5a2010-05-07 05:32:02 +00006600 case Expr::UnaryOperatorClass: {
6601 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6602 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006603 case UO_PostInc:
6604 case UO_PostDec:
6605 case UO_PreInc:
6606 case UO_PreDec:
6607 case UO_AddrOf:
6608 case UO_Deref:
Richard Smith05830142011-10-24 22:35:48 +00006609 // C99 6.6/3 allows increment and decrement within unevaluated
6610 // subexpressions of constant expressions, but they can never be ICEs
6611 // because an ICE cannot contain an lvalue operand.
Richard Smithceb59d92012-12-28 13:25:52 +00006612 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall2de56d12010-08-25 11:45:40 +00006613 case UO_Extension:
6614 case UO_LNot:
6615 case UO_Plus:
6616 case UO_Minus:
6617 case UO_Not:
6618 case UO_Real:
6619 case UO_Imag:
John McCalld905f5a2010-05-07 05:32:02 +00006620 return CheckICE(Exp->getSubExpr(), Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006621 }
Richard Smithceb59d92012-12-28 13:25:52 +00006622
John McCalld905f5a2010-05-07 05:32:02 +00006623 // OffsetOf falls through here.
6624 }
6625 case Expr::OffsetOfExprClass: {
Richard Smithceb59d92012-12-28 13:25:52 +00006626 // Note that per C99, offsetof must be an ICE. And AFAIK, using
6627 // EvaluateAsRValue matches the proposed gcc behavior for cases like
6628 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
6629 // compliance: we should warn earlier for offsetof expressions with
6630 // array subscripts that aren't ICEs, and if the array subscripts
6631 // are ICEs, the value of the offsetof must be an integer constant.
6632 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006633 }
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00006634 case Expr::UnaryExprOrTypeTraitExprClass: {
6635 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6636 if ((Exp->getKind() == UETT_SizeOf) &&
6637 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smithceb59d92012-12-28 13:25:52 +00006638 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006639 return NoDiag();
6640 }
6641 case Expr::BinaryOperatorClass: {
6642 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6643 switch (Exp->getOpcode()) {
John McCall2de56d12010-08-25 11:45:40 +00006644 case BO_PtrMemD:
6645 case BO_PtrMemI:
6646 case BO_Assign:
6647 case BO_MulAssign:
6648 case BO_DivAssign:
6649 case BO_RemAssign:
6650 case BO_AddAssign:
6651 case BO_SubAssign:
6652 case BO_ShlAssign:
6653 case BO_ShrAssign:
6654 case BO_AndAssign:
6655 case BO_XorAssign:
6656 case BO_OrAssign:
Richard Smith05830142011-10-24 22:35:48 +00006657 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6658 // constant expressions, but they can never be ICEs because an ICE cannot
6659 // contain an lvalue operand.
Richard Smithceb59d92012-12-28 13:25:52 +00006660 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006661
John McCall2de56d12010-08-25 11:45:40 +00006662 case BO_Mul:
6663 case BO_Div:
6664 case BO_Rem:
6665 case BO_Add:
6666 case BO_Sub:
6667 case BO_Shl:
6668 case BO_Shr:
6669 case BO_LT:
6670 case BO_GT:
6671 case BO_LE:
6672 case BO_GE:
6673 case BO_EQ:
6674 case BO_NE:
6675 case BO_And:
6676 case BO_Xor:
6677 case BO_Or:
6678 case BO_Comma: {
John McCalld905f5a2010-05-07 05:32:02 +00006679 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6680 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCall2de56d12010-08-25 11:45:40 +00006681 if (Exp->getOpcode() == BO_Div ||
6682 Exp->getOpcode() == BO_Rem) {
Richard Smith51f47082011-10-29 00:50:52 +00006683 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCalld905f5a2010-05-07 05:32:02 +00006684 // we don't evaluate one.
Richard Smithceb59d92012-12-28 13:25:52 +00006685 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006686 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006687 if (REval == 0)
Richard Smithceb59d92012-12-28 13:25:52 +00006688 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006689 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006690 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006691 if (LEval.isMinSignedValue())
Richard Smithceb59d92012-12-28 13:25:52 +00006692 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006693 }
6694 }
6695 }
John McCall2de56d12010-08-25 11:45:40 +00006696 if (Exp->getOpcode() == BO_Comma) {
David Blaikie4e4d0842012-03-11 07:00:24 +00006697 if (Ctx.getLangOpts().C99) {
John McCalld905f5a2010-05-07 05:32:02 +00006698 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6699 // if it isn't evaluated.
Richard Smithceb59d92012-12-28 13:25:52 +00006700 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
6701 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006702 } else {
6703 // In both C89 and C++, commas in ICEs are illegal.
Richard Smithceb59d92012-12-28 13:25:52 +00006704 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalld905f5a2010-05-07 05:32:02 +00006705 }
6706 }
Richard Smithceb59d92012-12-28 13:25:52 +00006707 return Worst(LHSResult, RHSResult);
John McCalld905f5a2010-05-07 05:32:02 +00006708 }
John McCall2de56d12010-08-25 11:45:40 +00006709 case BO_LAnd:
6710 case BO_LOr: {
John McCalld905f5a2010-05-07 05:32:02 +00006711 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6712 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006713 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCalld905f5a2010-05-07 05:32:02 +00006714 // Rare case where the RHS has a comma "side-effect"; we need
6715 // to actually check the condition to see whether the side
6716 // with the comma is evaluated.
John McCall2de56d12010-08-25 11:45:40 +00006717 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smitha6b8b2c2011-10-10 18:28:20 +00006718 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCalld905f5a2010-05-07 05:32:02 +00006719 return RHSResult;
6720 return NoDiag();
6721 }
6722
Richard Smithceb59d92012-12-28 13:25:52 +00006723 return Worst(LHSResult, RHSResult);
John McCalld905f5a2010-05-07 05:32:02 +00006724 }
6725 }
6726 }
6727 case Expr::ImplicitCastExprClass:
6728 case Expr::CStyleCastExprClass:
6729 case Expr::CXXFunctionalCastExprClass:
6730 case Expr::CXXStaticCastExprClass:
6731 case Expr::CXXReinterpretCastExprClass:
Richard Smith32cb4712011-10-24 18:26:35 +00006732 case Expr::CXXConstCastExprClass:
John McCallf85e1932011-06-15 23:02:42 +00006733 case Expr::ObjCBridgedCastExprClass: {
John McCalld905f5a2010-05-07 05:32:02 +00006734 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith2116b142011-12-18 02:33:09 +00006735 if (isa<ExplicitCastExpr>(E)) {
6736 if (const FloatingLiteral *FL
6737 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6738 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6739 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6740 APSInt IgnoredVal(DestWidth, !DestSigned);
6741 bool Ignored;
6742 // If the value does not fit in the destination type, the behavior is
6743 // undefined, so we are not required to treat it as a constant
6744 // expression.
6745 if (FL->getValue().convertToInteger(IgnoredVal,
6746 llvm::APFloat::rmTowardZero,
6747 &Ignored) & APFloat::opInvalidOp)
Richard Smithceb59d92012-12-28 13:25:52 +00006748 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith2116b142011-12-18 02:33:09 +00006749 return NoDiag();
6750 }
6751 }
Eli Friedmaneea0e812011-09-29 21:49:34 +00006752 switch (cast<CastExpr>(E)->getCastKind()) {
6753 case CK_LValueToRValue:
David Chisnall7a7ee302012-01-16 17:27:18 +00006754 case CK_AtomicToNonAtomic:
6755 case CK_NonAtomicToAtomic:
Eli Friedmaneea0e812011-09-29 21:49:34 +00006756 case CK_NoOp:
6757 case CK_IntegralToBoolean:
6758 case CK_IntegralCast:
John McCalld905f5a2010-05-07 05:32:02 +00006759 return CheckICE(SubExpr, Ctx);
Eli Friedmaneea0e812011-09-29 21:49:34 +00006760 default:
Richard Smithceb59d92012-12-28 13:25:52 +00006761 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedmaneea0e812011-09-29 21:49:34 +00006762 }
John McCalld905f5a2010-05-07 05:32:02 +00006763 }
John McCall56ca35d2011-02-17 10:25:35 +00006764 case Expr::BinaryConditionalOperatorClass: {
6765 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6766 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006767 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCall56ca35d2011-02-17 10:25:35 +00006768 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006769 if (FalseResult.Kind == IK_NotICE) return FalseResult;
6770 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
6771 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith9b403c52012-12-28 12:53:55 +00006772 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCall56ca35d2011-02-17 10:25:35 +00006773 return FalseResult;
6774 }
John McCalld905f5a2010-05-07 05:32:02 +00006775 case Expr::ConditionalOperatorClass: {
6776 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6777 // If the condition (ignoring parens) is a __builtin_constant_p call,
6778 // then only the true side is actually considered in an integer constant
6779 // expression, and it is fully evaluated. This is an important GNU
6780 // extension. See GCC PR38377 for discussion.
6781 if (const CallExpr *CallCE
6782 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith80d4b552011-12-28 19:48:30 +00006783 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6784 return CheckEvalInICE(E, Ctx);
John McCalld905f5a2010-05-07 05:32:02 +00006785 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smithceb59d92012-12-28 13:25:52 +00006786 if (CondResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00006787 return CondResult;
Douglas Gregor63fe6812011-05-24 16:02:01 +00006788
Richard Smithf48fdb02011-12-09 22:58:01 +00006789 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6790 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregor63fe6812011-05-24 16:02:01 +00006791
Richard Smithceb59d92012-12-28 13:25:52 +00006792 if (TrueResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00006793 return TrueResult;
Richard Smithceb59d92012-12-28 13:25:52 +00006794 if (FalseResult.Kind == IK_NotICE)
John McCalld905f5a2010-05-07 05:32:02 +00006795 return FalseResult;
Richard Smithceb59d92012-12-28 13:25:52 +00006796 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCalld905f5a2010-05-07 05:32:02 +00006797 return CondResult;
Richard Smithceb59d92012-12-28 13:25:52 +00006798 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCalld905f5a2010-05-07 05:32:02 +00006799 return NoDiag();
6800 // Rare case where the diagnostics depend on which side is evaluated
6801 // Note that if we get here, CondResult is 0, and at least one of
6802 // TrueResult and FalseResult is non-zero.
Richard Smithceb59d92012-12-28 13:25:52 +00006803 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCalld905f5a2010-05-07 05:32:02 +00006804 return FalseResult;
John McCalld905f5a2010-05-07 05:32:02 +00006805 return TrueResult;
6806 }
6807 case Expr::CXXDefaultArgExprClass:
6808 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6809 case Expr::ChooseExprClass: {
6810 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6811 }
6812 }
6813
David Blaikie30263482012-01-20 21:50:17 +00006814 llvm_unreachable("Invalid StmtClass!");
John McCalld905f5a2010-05-07 05:32:02 +00006815}
6816
Richard Smithf48fdb02011-12-09 22:58:01 +00006817/// Evaluate an expression as a C++11 integral constant expression.
6818static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6819 const Expr *E,
6820 llvm::APSInt *Value,
6821 SourceLocation *Loc) {
6822 if (!E->getType()->isIntegralOrEnumerationType()) {
6823 if (Loc) *Loc = E->getExprLoc();
6824 return false;
6825 }
6826
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006827 APValue Result;
6828 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smithdd1f29b2011-12-12 09:28:41 +00006829 return false;
6830
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006831 assert(Result.isInt() && "pointer cast to int is not an ICE");
6832 if (Value) *Value = Result.getInt();
Richard Smithdd1f29b2011-12-12 09:28:41 +00006833 return true;
Richard Smithf48fdb02011-12-09 22:58:01 +00006834}
6835
Richard Smithdd1f29b2011-12-12 09:28:41 +00006836bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith80ad52f2013-01-02 11:42:31 +00006837 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf48fdb02011-12-09 22:58:01 +00006838 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6839
Richard Smithceb59d92012-12-28 13:25:52 +00006840 ICEDiag D = CheckICE(this, Ctx);
6841 if (D.Kind != IK_ICE) {
6842 if (Loc) *Loc = D.Loc;
John McCalld905f5a2010-05-07 05:32:02 +00006843 return false;
6844 }
Richard Smithf48fdb02011-12-09 22:58:01 +00006845 return true;
6846}
6847
6848bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6849 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith80ad52f2013-01-02 11:42:31 +00006850 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf48fdb02011-12-09 22:58:01 +00006851 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6852
6853 if (!isIntegerConstantExpr(Ctx, Loc))
6854 return false;
6855 if (!EvaluateAsInt(Value, Ctx))
John McCalld905f5a2010-05-07 05:32:02 +00006856 llvm_unreachable("ICE cannot be evaluated!");
John McCalld905f5a2010-05-07 05:32:02 +00006857 return true;
6858}
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006859
Richard Smith70488e22012-02-14 21:38:30 +00006860bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smithceb59d92012-12-28 13:25:52 +00006861 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith70488e22012-02-14 21:38:30 +00006862}
6863
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006864bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6865 SourceLocation *Loc) const {
6866 // We support this checking in C++98 mode in order to diagnose compatibility
6867 // issues.
David Blaikie4e4d0842012-03-11 07:00:24 +00006868 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006869
Richard Smith70488e22012-02-14 21:38:30 +00006870 // Build evaluation settings.
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006871 Expr::EvalStatus Status;
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006872 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith4c3fc9b2012-01-18 05:21:49 +00006873 Status.Diag = &Diags;
6874 EvalInfo Info(Ctx, Status);
6875
6876 APValue Scratch;
6877 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6878
6879 if (!Diags.empty()) {
6880 IsConstExpr = false;
6881 if (Loc) *Loc = Diags[0].first;
6882 } else if (!IsConstExpr) {
6883 // FIXME: This shouldn't happen.
6884 if (Loc) *Loc = getExprLoc();
6885 }
6886
6887 return IsConstExpr;
6888}
Richard Smith745f5142012-01-27 01:14:48 +00006889
6890bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00006891 SmallVectorImpl<
Richard Smith745f5142012-01-27 01:14:48 +00006892 PartialDiagnosticAt> &Diags) {
6893 // FIXME: It would be useful to check constexpr function templates, but at the
6894 // moment the constant expression evaluator cannot cope with the non-rigorous
6895 // ASTs which we build for dependent expressions.
6896 if (FD->isDependentContext())
6897 return true;
6898
6899 Expr::EvalStatus Status;
6900 Status.Diag = &Diags;
6901
6902 EvalInfo Info(FD->getASTContext(), Status);
6903 Info.CheckingPotentialConstantExpression = true;
6904
6905 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6906 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6907
6908 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6909 // is a temporary being used as the 'this' pointer.
6910 LValue This;
6911 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smith83587db2012-02-15 02:18:13 +00006912 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith745f5142012-01-27 01:14:48 +00006913
Richard Smith745f5142012-01-27 01:14:48 +00006914 ArrayRef<const Expr*> Args;
6915
6916 SourceLocation Loc = FD->getLocation();
6917
Richard Smith1aa0be82012-03-03 22:46:17 +00006918 APValue Scratch;
6919 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith745f5142012-01-27 01:14:48 +00006920 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith1aa0be82012-03-03 22:46:17 +00006921 else
Richard Smith745f5142012-01-27 01:14:48 +00006922 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6923 Args, FD->getBody(), Info, Scratch);
6924
6925 return Diags.empty();
6926}