blob: 881182bba85284cd2a01cdf799ba4bfd063e631b [file] [log] [blame]
Chris Lattnere13042c2008-07-11 19:10:17 +00001//===--- ExprConstant.cpp - Expression Constant Evaluator -----------------===//
Anders Carlsson7a241ba2008-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 Smith253c2a32012-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 Carlsson7a241ba2008-07-03 04:20:39 +000034//===----------------------------------------------------------------------===//
35
36#include "clang/AST/APValue.h"
37#include "clang/AST/ASTContext.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000038#include "clang/AST/ASTDiagnostic.h"
Ken Dyck40775002010-01-11 17:06:35 +000039#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000040#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000041#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000042#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000043#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000044#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000045#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000046#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-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 Smithd62306a2011-11-10 06:34:14 +000069 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000070 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000071 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000072 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000073 APValue::BaseOrMemberType Value;
74 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-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 Smithb228a862012-02-15 02:18:13 +000080 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000081 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-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 Smithb228a862012-02-15 02:18:13 +000085 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000086 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +000087 }
88 /// Determine whether this LValue path entry for a base class names a virtual
89 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +000090 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000091 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +000092 }
93
Richard Smitha8105bc2012-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 Smith80815602011-11-07 05:07:52 +0000102 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-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 Smith66c96992012-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 Smitha8105bc2012-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 Smith80815602011-11-07 05:07:52 +0000119 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000120 ArraySize = 0;
121 }
Richard Smith80815602011-11-07 05:07:52 +0000122 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000123 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000124 }
125
Richard Smitha8105bc2012-01-06 16:39:00 +0000126 // The order of this enum is important for diagnostics.
127 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000128 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000129 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000130 };
131
Richard Smith96e0c102011-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 Smitha8105bc2012-01-06 16:39:00 +0000139 /// Is this a pointer one past the end of an object?
140 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000141
Richard Smitha8105bc2012-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 Smith96e0c102011-11-04 02:25:55 +0000152
Richard Smith80815602011-11-07 05:07:52 +0000153 typedef APValue::LValuePathEntry PathEntry;
154
Richard Smith96e0c102011-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 Smitha8105bc2012-01-06 16:39:00 +0000158 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000159
Richard Smitha8105bc2012-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 Smith80815602011-11-07 05:07:52 +0000167 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000168 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-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 Smitha8105bc2012-01-06 16:39:00 +0000172 MostDerivedPathLength =
173 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
174 V.getLValuePath(), MostDerivedArraySize,
175 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000176 }
177 }
178
Richard Smith96e0c102011-11-04 02:25:55 +0000179 void setInvalid() {
180 Invalid = true;
181 Entries.clear();
182 }
Richard Smitha8105bc2012-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 Smith96e0c102011-11-04 02:25:55 +0000206 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000207 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000208 Entries.push_back(Entry);
Richard Smitha8105bc2012-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 Smith96e0c102011-11-04 02:25:55 +0000214 }
215 /// Update this designator to refer to the given base or member of this
216 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000217 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000218 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000219 APValue::BaseOrMemberType Value(D, Virtual);
220 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000221 Entries.push_back(Entry);
Richard Smitha8105bc2012-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 Smith96e0c102011-11-04 02:25:55 +0000229 }
Richard Smith66c96992012-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 Smitha8105bc2012-01-06 16:39:00 +0000242 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000243 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000244 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000245 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000246 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000247 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000248 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
249 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
250 setInvalid();
251 }
Richard Smith96e0c102011-11-04 02:25:55 +0000252 return;
253 }
Richard Smitha8105bc2012-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 Smith96e0c102011-11-04 02:25:55 +0000263 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000264 }
Richard Smith96e0c102011-11-04 02:25:55 +0000265 }
266 };
267
Richard Smith254a73d2011-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 Smith4e4c78ff2011-10-31 05:52:43 +0000273 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000274
Richard Smithf6f003a2011-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 Smithb228a862012-02-15 02:18:13 +0000281 /// Index - The call index of this call.
282 unsigned Index;
283
Richard Smithd62306a2011-11-10 06:34:14 +0000284 /// This - The binding for the this pointer in this call, if any.
285 const LValue *This;
286
Richard Smith254a73d2011-10-28 22:34:42 +0000287 /// ParmBindings - Parameter bindings for this function call, indexed by
288 /// parameters' function scope indices.
Richard Smith2e312c82012-03-03 22:46:17 +0000289 const APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000290
Eli Friedman4830ec82012-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 Smith4e4c78ff2011-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 Smithf6f003a2011-12-16 19:06:07 +0000298 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
299 const FunctionDecl *Callee, const LValue *This,
Richard Smith2e312c82012-03-03 22:46:17 +0000300 const APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000301 ~CallStackFrame();
Richard Smith254a73d2011-10-28 22:34:42 +0000302 };
303
Richard Smith92b1ce02011-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 Smithfe800032012-01-31 04:08:20 +0000318
319 OptionalDiagnostic &operator<<(const APSInt &I) {
320 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000321 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-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 Gribenkof8579502013-01-12 19:30:44 +0000330 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000331 F.toString(Buffer);
332 *Diag << StringRef(Buffer.data(), Buffer.size());
333 }
334 return *this;
335 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000336 };
337
Richard Smithb228a862012-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 Smith4e4c78ff2011-10-31 05:52:43 +0000352 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000353 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000354
Richard Smith4e4c78ff2011-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 Smith4e4c78ff2011-10-31 05:52:43 +0000361 /// CallStackDepth - The number of calls in the call stack right now.
362 unsigned CallStackDepth;
363
Richard Smithb228a862012-02-15 02:18:13 +0000364 /// NextCallIndex - The next call index to assign.
365 unsigned NextCallIndex;
366
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000367 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000368 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000369 CallStackFrame BottomFrame;
370
Richard Smithd62306a2011-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 Smith357362d2011-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 Smith253c2a32012-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 Jahaniane735ff92013-01-24 22:11:45 +0000387
388 bool IntOverflowCheckMode;
Richard Smith253c2a32012-01-27 01:14:48 +0000389
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000390 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
391 bool OverflowCheckMode=false)
Richard Smith92b1ce02011-12-12 09:28:41 +0000392 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000393 CallStackDepth(0), NextCallIndex(1),
394 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith253c2a32012-01-27 01:14:48 +0000395 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000396 CheckingPotentialConstantExpression(false),
397 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000398
Richard Smithd62306a2011-11-10 06:34:14 +0000399 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
400 EvaluatingDecl = VD;
401 EvaluatingDeclValue = &Value;
402 }
403
David Blaikiebbafb8a2012-03-11 07:00:24 +0000404 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000405
Richard Smith357362d2011-12-13 06:39:58 +0000406 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-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 Smithb228a862012-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 Smith357362d2011-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 Smith9a568822011-11-21 19:36:32 +0000421 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000422
Richard Smithb228a862012-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 Smith357362d2011-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 Smithf6f003a2011-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 Smith357362d2011-12-13 06:39:58 +0000444 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000445 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000446 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
447 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000448 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-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 Smith92b1ce02011-12-12 09:28:41 +0000452 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-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 Smith253c2a32012-01-27 01:14:48 +0000457 if (CheckingPotentialConstantExpression)
458 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000459
Richard Smith357362d2011-12-13 06:39:58 +0000460 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000461 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000462 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
463 addDiag(Loc, DiagId);
Richard Smith253c2a32012-01-27 01:14:48 +0000464 if (!CheckingPotentialConstantExpression)
465 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000466 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000467 }
Richard Smith357362d2011-12-13 06:39:58 +0000468 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000469 return OptionalDiagnostic();
470 }
471
Richard Smithce1ec5e2012-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 Jahaniane735ff92013-01-24 22:11:45 +0000481 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
482
Richard Smith92b1ce02011-12-12 09:28:41 +0000483 /// Diagnose that the evaluation does not produce a C++11 core constant
484 /// expression.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000485 template<typename LocArg>
486 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000487 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000488 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000489 // Don't override a previous diagnostic.
Eli Friedmanebea9af2012-02-21 22:41:33 +0000490 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
491 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000492 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000493 }
Richard Smith357362d2011-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 Smithf57d8cb2011-12-09 22:58:01 +0000502 }
Richard Smithd0b4dd62011-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 Smith253c2a32012-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 Jahaniane735ff92013-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.
517 // subexpressions can't be evaluated as constants.
518 return IntOverflowCheckMode ||
519 (CheckingPotentialConstantExpression &&
520 EvalStatus.Diag && EvalStatus.Diag->empty());
Richard Smith253c2a32012-01-27 01:14:48 +0000521 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000522 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000523
524 /// Object used to treat all foldable expressions as constant expressions.
525 struct FoldConstant {
526 bool Enabled;
527
528 explicit FoldConstant(EvalInfo &Info)
529 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
530 !Info.EvalStatus.HasSideEffects) {
531 }
532 // Treat the value we've computed since this object was created as constant.
533 void Fold(EvalInfo &Info) {
534 if (Enabled && !Info.EvalStatus.Diag->empty() &&
535 !Info.EvalStatus.HasSideEffects)
536 Info.EvalStatus.Diag->clear();
537 }
538 };
Richard Smith17100ba2012-02-16 02:46:34 +0000539
540 /// RAII object used to suppress diagnostics and side-effects from a
541 /// speculative evaluation.
542 class SpeculativeEvaluationRAII {
543 EvalInfo &Info;
544 Expr::EvalStatus Old;
545
546 public:
547 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000548 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000549 : Info(Info), Old(Info.EvalStatus) {
550 Info.EvalStatus.Diag = NewDiag;
551 }
552 ~SpeculativeEvaluationRAII() {
553 Info.EvalStatus = Old;
554 }
555 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000556}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000557
Richard Smitha8105bc2012-01-06 16:39:00 +0000558bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
559 CheckSubobjectKind CSK) {
560 if (Invalid)
561 return false;
562 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000563 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000564 << CSK;
565 setInvalid();
566 return false;
567 }
568 return true;
569}
570
571void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
572 const Expr *E, uint64_t N) {
573 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000574 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000575 << static_cast<int>(N) << /*array*/ 0
576 << static_cast<unsigned>(MostDerivedArraySize);
577 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000578 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000579 << static_cast<int>(N) << /*non-array*/ 1;
580 setInvalid();
581}
582
Richard Smithf6f003a2011-12-16 19:06:07 +0000583CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
584 const FunctionDecl *Callee, const LValue *This,
Richard Smith2e312c82012-03-03 22:46:17 +0000585 const APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000586 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000587 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000588 Info.CurrentCall = this;
589 ++Info.CallStackDepth;
590}
591
592CallStackFrame::~CallStackFrame() {
593 assert(Info.CurrentCall == this && "calls retired out of order");
594 --Info.CallStackDepth;
595 Info.CurrentCall = Caller;
596}
597
598/// Produce a string describing the given constexpr call.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000599static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000600 unsigned ArgIndex = 0;
601 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith74388b42012-02-04 00:33:54 +0000602 !isa<CXXConstructorDecl>(Frame->Callee) &&
603 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smithf6f003a2011-12-16 19:06:07 +0000604
605 if (!IsMemberCall)
606 Out << *Frame->Callee << '(';
607
608 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
609 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumib8efa1e2012-01-26 09:37:36 +0000610 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smithf6f003a2011-12-16 19:06:07 +0000611 Out << ", ";
612
613 const ParmVarDecl *Param = *I;
Richard Smith2e312c82012-03-03 22:46:17 +0000614 const APValue &Arg = Frame->Arguments[ArgIndex];
615 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smithf6f003a2011-12-16 19:06:07 +0000616
617 if (ArgIndex == 0 && IsMemberCall)
618 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000619 }
620
Richard Smithf6f003a2011-12-16 19:06:07 +0000621 Out << ')';
622}
623
624void EvalInfo::addCallStack(unsigned Limit) {
625 // Determine which calls to skip, if any.
626 unsigned ActiveCalls = CallStackDepth - 1;
627 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
628 if (Limit && Limit < ActiveCalls) {
629 SkipStart = Limit / 2 + Limit % 2;
630 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000631 }
632
Richard Smithf6f003a2011-12-16 19:06:07 +0000633 // Walk the call stack and add the diagnostics.
634 unsigned CallIdx = 0;
635 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
636 Frame = Frame->Caller, ++CallIdx) {
637 // Skip this call?
638 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
639 if (CallIdx == SkipStart) {
640 // Note that we're skipping calls.
641 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
642 << unsigned(ActiveCalls - Limit);
643 }
644 continue;
645 }
646
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000647 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000648 llvm::raw_svector_ostream Out(Buffer);
649 describeCall(Frame, Out);
650 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
651 }
652}
653
654namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000655 struct ComplexValue {
656 private:
657 bool IsInt;
658
659 public:
660 APSInt IntReal, IntImag;
661 APFloat FloatReal, FloatImag;
662
663 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
664
665 void makeComplexFloat() { IsInt = false; }
666 bool isComplexFloat() const { return !IsInt; }
667 APFloat &getComplexFloatReal() { return FloatReal; }
668 APFloat &getComplexFloatImag() { return FloatImag; }
669
670 void makeComplexInt() { IsInt = true; }
671 bool isComplexInt() const { return IsInt; }
672 APSInt &getComplexIntReal() { return IntReal; }
673 APSInt &getComplexIntImag() { return IntImag; }
674
Richard Smith2e312c82012-03-03 22:46:17 +0000675 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000676 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000677 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000678 else
Richard Smith2e312c82012-03-03 22:46:17 +0000679 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000680 }
Richard Smith2e312c82012-03-03 22:46:17 +0000681 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000682 assert(v.isComplexFloat() || v.isComplexInt());
683 if (v.isComplexFloat()) {
684 makeComplexFloat();
685 FloatReal = v.getComplexFloatReal();
686 FloatImag = v.getComplexFloatImag();
687 } else {
688 makeComplexInt();
689 IntReal = v.getComplexIntReal();
690 IntImag = v.getComplexIntImag();
691 }
692 }
John McCall93d91dc2010-05-07 17:22:02 +0000693 };
John McCall45d55e42010-05-07 21:00:08 +0000694
695 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000696 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000697 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000698 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000699 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000700
Richard Smithce40ad62011-11-12 22:28:03 +0000701 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000702 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000703 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000704 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000705 SubobjectDesignator &getLValueDesignator() { return Designator; }
706 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000707
Richard Smith2e312c82012-03-03 22:46:17 +0000708 void moveInto(APValue &V) const {
709 if (Designator.Invalid)
710 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
711 else
712 V = APValue(Base, Offset, Designator.Entries,
713 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000714 }
Richard Smith2e312c82012-03-03 22:46:17 +0000715 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000716 assert(V.isLValue());
717 Base = V.getLValueBase();
718 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000719 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000720 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000721 }
722
Richard Smithb228a862012-02-15 02:18:13 +0000723 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000724 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000725 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000726 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000727 Designator = SubobjectDesignator(getType(B));
728 }
729
730 // Check that this LValue is not based on a null pointer. If it is, produce
731 // a diagnostic and mark the designator as invalid.
732 bool checkNullPointer(EvalInfo &Info, const Expr *E,
733 CheckSubobjectKind CSK) {
734 if (Designator.Invalid)
735 return false;
736 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000737 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000738 << CSK;
739 Designator.setInvalid();
740 return false;
741 }
742 return true;
743 }
744
745 // Check this LValue refers to an object. If not, set the designator to be
746 // invalid and emit a diagnostic.
747 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000748 // Outside C++11, do not build a designator referring to a subobject of
749 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000750 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000751 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000752 return checkNullPointer(Info, E, CSK) &&
753 Designator.checkSubobject(Info, E, CSK);
754 }
755
756 void addDecl(EvalInfo &Info, const Expr *E,
757 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000758 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
759 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000760 }
761 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000762 if (checkSubobject(Info, E, CSK_ArrayToPointer))
763 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000764 }
Richard Smith66c96992012-02-18 22:04:06 +0000765 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000766 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
767 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000768 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000769 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000770 if (checkNullPointer(Info, E, CSK_ArrayIndex))
771 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000772 }
John McCall45d55e42010-05-07 21:00:08 +0000773 };
Richard Smith027bf112011-11-17 22:56:20 +0000774
775 struct MemberPtr {
776 MemberPtr() {}
777 explicit MemberPtr(const ValueDecl *Decl) :
778 DeclAndIsDerivedMember(Decl, false), Path() {}
779
780 /// The member or (direct or indirect) field referred to by this member
781 /// pointer, or 0 if this is a null member pointer.
782 const ValueDecl *getDecl() const {
783 return DeclAndIsDerivedMember.getPointer();
784 }
785 /// Is this actually a member of some type derived from the relevant class?
786 bool isDerivedMember() const {
787 return DeclAndIsDerivedMember.getInt();
788 }
789 /// Get the class which the declaration actually lives in.
790 const CXXRecordDecl *getContainingRecord() const {
791 return cast<CXXRecordDecl>(
792 DeclAndIsDerivedMember.getPointer()->getDeclContext());
793 }
794
Richard Smith2e312c82012-03-03 22:46:17 +0000795 void moveInto(APValue &V) const {
796 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000797 }
Richard Smith2e312c82012-03-03 22:46:17 +0000798 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000799 assert(V.isMemberPointer());
800 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
801 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
802 Path.clear();
803 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
804 Path.insert(Path.end(), P.begin(), P.end());
805 }
806
807 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
808 /// whether the member is a member of some class derived from the class type
809 /// of the member pointer.
810 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
811 /// Path - The path of base/derived classes from the member declaration's
812 /// class (exclusive) to the class type of the member pointer (inclusive).
813 SmallVector<const CXXRecordDecl*, 4> Path;
814
815 /// Perform a cast towards the class of the Decl (either up or down the
816 /// hierarchy).
817 bool castBack(const CXXRecordDecl *Class) {
818 assert(!Path.empty());
819 const CXXRecordDecl *Expected;
820 if (Path.size() >= 2)
821 Expected = Path[Path.size() - 2];
822 else
823 Expected = getContainingRecord();
824 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
825 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
826 // if B does not contain the original member and is not a base or
827 // derived class of the class containing the original member, the result
828 // of the cast is undefined.
829 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
830 // (D::*). We consider that to be a language defect.
831 return false;
832 }
833 Path.pop_back();
834 return true;
835 }
836 /// Perform a base-to-derived member pointer cast.
837 bool castToDerived(const CXXRecordDecl *Derived) {
838 if (!getDecl())
839 return true;
840 if (!isDerivedMember()) {
841 Path.push_back(Derived);
842 return true;
843 }
844 if (!castBack(Derived))
845 return false;
846 if (Path.empty())
847 DeclAndIsDerivedMember.setInt(false);
848 return true;
849 }
850 /// Perform a derived-to-base member pointer cast.
851 bool castToBase(const CXXRecordDecl *Base) {
852 if (!getDecl())
853 return true;
854 if (Path.empty())
855 DeclAndIsDerivedMember.setInt(true);
856 if (isDerivedMember()) {
857 Path.push_back(Base);
858 return true;
859 }
860 return castBack(Base);
861 }
862 };
Richard Smith357362d2011-12-13 06:39:58 +0000863
Richard Smith7bb00672012-02-01 01:42:44 +0000864 /// Compare two member pointers, which are assumed to be of the same type.
865 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
866 if (!LHS.getDecl() || !RHS.getDecl())
867 return !LHS.getDecl() && !RHS.getDecl();
868 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
869 return false;
870 return LHS.Path == RHS.Path;
871 }
872
Richard Smith357362d2011-12-13 06:39:58 +0000873 /// Kinds of constant expression checking, for diagnostics.
874 enum CheckConstantExpressionKind {
875 CCEK_Constant, ///< A normal constant.
876 CCEK_ReturnValue, ///< A constexpr function return value.
877 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
878 };
John McCall93d91dc2010-05-07 17:22:02 +0000879}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000880
Richard Smith2e312c82012-03-03 22:46:17 +0000881static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000882static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
883 const LValue &This, const Expr *E,
884 CheckConstantExpressionKind CCEK = CCEK_Constant,
885 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000886static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
887static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000888static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
889 EvalInfo &Info);
890static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000891static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000892static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000893 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000894static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000895static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000896
897//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000898// Misc utilities
899//===----------------------------------------------------------------------===//
900
Richard Smithd62306a2011-11-10 06:34:14 +0000901/// Should this call expression be treated as a string literal?
902static bool IsStringLiteralCall(const CallExpr *E) {
903 unsigned Builtin = E->isBuiltinCall();
904 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
905 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
906}
907
Richard Smithce40ad62011-11-12 22:28:03 +0000908static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000909 // C++11 [expr.const]p3 An address constant expression is a prvalue core
910 // constant expression of pointer type that evaluates to...
911
912 // ... a null pointer value, or a prvalue core constant expression of type
913 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000914 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000915
Richard Smithce40ad62011-11-12 22:28:03 +0000916 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
917 // ... the address of an object with static storage duration,
918 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
919 return VD->hasGlobalStorage();
920 // ... the address of a function,
921 return isa<FunctionDecl>(D);
922 }
923
924 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000925 switch (E->getStmtClass()) {
926 default:
927 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +0000928 case Expr::CompoundLiteralExprClass: {
929 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
930 return CLE->isFileScope() && CLE->isLValue();
931 }
Richard Smithd62306a2011-11-10 06:34:14 +0000932 // A string literal has static storage duration.
933 case Expr::StringLiteralClass:
934 case Expr::PredefinedExprClass:
935 case Expr::ObjCStringLiteralClass:
936 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000937 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +0000938 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000939 return true;
940 case Expr::CallExprClass:
941 return IsStringLiteralCall(cast<CallExpr>(E));
942 // For GCC compatibility, &&label has static storage duration.
943 case Expr::AddrLabelExprClass:
944 return true;
945 // A Block literal expression may be used as the initialization value for
946 // Block variables at global or local static scope.
947 case Expr::BlockExprClass:
948 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +0000949 case Expr::ImplicitValueInitExprClass:
950 // FIXME:
951 // We can never form an lvalue with an implicit value initialization as its
952 // base through expression evaluation, so these only appear in one case: the
953 // implicit variable declaration we invent when checking whether a constexpr
954 // constructor can produce a constant expression. We must assume that such
955 // an expression might be a global lvalue.
956 return true;
Richard Smithd62306a2011-11-10 06:34:14 +0000957 }
John McCall95007602010-05-10 23:27:23 +0000958}
959
Richard Smithb228a862012-02-15 02:18:13 +0000960static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
961 assert(Base && "no location for a null lvalue");
962 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
963 if (VD)
964 Info.Note(VD->getLocation(), diag::note_declared_at);
965 else
Ted Kremenek28831752012-08-23 20:46:57 +0000966 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +0000967 diag::note_constexpr_temporary_here);
968}
969
Richard Smith80815602011-11-07 05:07:52 +0000970/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +0000971/// value for an address or reference constant expression. Return true if we
972/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +0000973static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
974 QualType Type, const LValue &LVal) {
975 bool IsReferenceType = Type->isReferenceType();
976
Richard Smith357362d2011-12-13 06:39:58 +0000977 APValue::LValueBase Base = LVal.getLValueBase();
978 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
979
Richard Smith0dea49e2012-02-18 04:58:18 +0000980 // Check that the object is a global. Note that the fake 'this' object we
981 // manufacture when checking potential constant expressions is conservatively
982 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +0000983 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000984 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +0000985 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +0000986 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
987 << IsReferenceType << !Designator.Entries.empty()
988 << !!VD << VD;
989 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +0000990 } else {
Richard Smithb228a862012-02-15 02:18:13 +0000991 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +0000992 }
Richard Smith02ab9c22012-01-12 06:08:57 +0000993 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +0000994 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +0000995 }
Richard Smithb228a862012-02-15 02:18:13 +0000996 assert((Info.CheckingPotentialConstantExpression ||
997 LVal.getLValueCallIndex() == 0) &&
998 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +0000999
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001000 // Check if this is a thread-local variable.
1001 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1002 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
1003 if (Var->isThreadSpecified())
1004 return false;
1005 }
1006 }
1007
Richard Smitha8105bc2012-01-06 16:39:00 +00001008 // Allow address constant expressions to be past-the-end pointers. This is
1009 // an extension: the standard requires them to point to an object.
1010 if (!IsReferenceType)
1011 return true;
1012
1013 // A reference constant expression must refer to an object.
1014 if (!Base) {
1015 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001016 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001017 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001018 }
1019
Richard Smith357362d2011-12-13 06:39:58 +00001020 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001021 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001022 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001023 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001024 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001025 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001026 }
1027
Richard Smith80815602011-11-07 05:07:52 +00001028 return true;
1029}
1030
Richard Smithfddd3842011-12-30 21:15:51 +00001031/// Check that this core constant expression is of literal type, and if not,
1032/// produce an appropriate diagnostic.
1033static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1034 if (!E->isRValue() || E->getType()->isLiteralType())
1035 return true;
1036
1037 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001038 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001039 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001040 << E->getType();
1041 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001042 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001043 return false;
1044}
1045
Richard Smith0b0a0b62011-10-29 20:57:55 +00001046/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001047/// constant expression. If not, report an appropriate diagnostic. Does not
1048/// check that the expression is of literal type.
1049static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1050 QualType Type, const APValue &Value) {
1051 // Core issue 1454: For a literal constant expression of array or class type,
1052 // each subobject of its value shall have been initialized by a constant
1053 // expression.
1054 if (Value.isArray()) {
1055 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1056 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1057 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1058 Value.getArrayInitializedElt(I)))
1059 return false;
1060 }
1061 if (!Value.hasArrayFiller())
1062 return true;
1063 return CheckConstantExpression(Info, DiagLoc, EltTy,
1064 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001065 }
Richard Smithb228a862012-02-15 02:18:13 +00001066 if (Value.isUnion() && Value.getUnionField()) {
1067 return CheckConstantExpression(Info, DiagLoc,
1068 Value.getUnionField()->getType(),
1069 Value.getUnionValue());
1070 }
1071 if (Value.isStruct()) {
1072 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1073 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1074 unsigned BaseIndex = 0;
1075 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1076 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1077 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1078 Value.getStructBase(BaseIndex)))
1079 return false;
1080 }
1081 }
1082 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1083 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001084 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1085 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001086 return false;
1087 }
1088 }
1089
1090 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001091 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001092 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001093 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1094 }
1095
1096 // Everything else is fine.
1097 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001098}
1099
Richard Smith83c68212011-10-31 05:11:32 +00001100const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001101 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001102}
1103
1104static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001105 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001106}
1107
Richard Smithcecf1842011-11-01 21:06:14 +00001108static bool IsWeakLValue(const LValue &Value) {
1109 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001110 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001111}
1112
Richard Smith2e312c82012-03-03 22:46:17 +00001113static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001114 // A null base expression indicates a null pointer. These are always
1115 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001116 if (!Value.getLValueBase()) {
1117 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001118 return true;
1119 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001120
Richard Smith027bf112011-11-17 22:56:20 +00001121 // We have a non-null base. These are generally known to be true, but if it's
1122 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001123 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001124 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001125 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001126}
1127
Richard Smith2e312c82012-03-03 22:46:17 +00001128static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001129 switch (Val.getKind()) {
1130 case APValue::Uninitialized:
1131 return false;
1132 case APValue::Int:
1133 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001134 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001135 case APValue::Float:
1136 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001137 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001138 case APValue::ComplexInt:
1139 Result = Val.getComplexIntReal().getBoolValue() ||
1140 Val.getComplexIntImag().getBoolValue();
1141 return true;
1142 case APValue::ComplexFloat:
1143 Result = !Val.getComplexFloatReal().isZero() ||
1144 !Val.getComplexFloatImag().isZero();
1145 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001146 case APValue::LValue:
1147 return EvalPointerValueAsBool(Val, Result);
1148 case APValue::MemberPointer:
1149 Result = Val.getMemberPointerDecl();
1150 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001151 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001152 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001153 case APValue::Struct:
1154 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001155 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001156 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001157 }
1158
Richard Smith11562c52011-10-28 17:51:58 +00001159 llvm_unreachable("unknown APValue kind");
1160}
1161
1162static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1163 EvalInfo &Info) {
1164 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001165 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001166 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001167 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001168 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001169}
1170
Richard Smith357362d2011-12-13 06:39:58 +00001171template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001172static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001173 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001174 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001175 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001176}
1177
1178static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1179 QualType SrcType, const APFloat &Value,
1180 QualType DestType, APSInt &Result) {
1181 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001182 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001183 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001184
Richard Smith357362d2011-12-13 06:39:58 +00001185 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001186 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001187 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1188 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001189 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001190 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001191}
1192
Richard Smith357362d2011-12-13 06:39:58 +00001193static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1194 QualType SrcType, QualType DestType,
1195 APFloat &Result) {
1196 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001197 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001198 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1199 APFloat::rmNearestTiesToEven, &ignored)
1200 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001201 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001202 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001203}
1204
Richard Smith911e1422012-01-30 22:27:01 +00001205static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1206 QualType DestType, QualType SrcType,
1207 APSInt &Value) {
1208 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001209 APSInt Result = Value;
1210 // Figure out if this is a truncate, extend or noop cast.
1211 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001212 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001213 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001214 return Result;
1215}
1216
Richard Smith357362d2011-12-13 06:39:58 +00001217static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1218 QualType SrcType, const APSInt &Value,
1219 QualType DestType, APFloat &Result) {
1220 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1221 if (Result.convertFromAPInt(Value, Value.isSigned(),
1222 APFloat::rmNearestTiesToEven)
1223 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001224 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001225 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001226}
1227
Eli Friedman803acb32011-12-22 03:51:45 +00001228static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1229 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001230 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001231 if (!Evaluate(SVal, Info, E))
1232 return false;
1233 if (SVal.isInt()) {
1234 Res = SVal.getInt();
1235 return true;
1236 }
1237 if (SVal.isFloat()) {
1238 Res = SVal.getFloat().bitcastToAPInt();
1239 return true;
1240 }
1241 if (SVal.isVector()) {
1242 QualType VecTy = E->getType();
1243 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1244 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1245 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1246 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1247 Res = llvm::APInt::getNullValue(VecSize);
1248 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1249 APValue &Elt = SVal.getVectorElt(i);
1250 llvm::APInt EltAsInt;
1251 if (Elt.isInt()) {
1252 EltAsInt = Elt.getInt();
1253 } else if (Elt.isFloat()) {
1254 EltAsInt = Elt.getFloat().bitcastToAPInt();
1255 } else {
1256 // Don't try to handle vectors of anything other than int or float
1257 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001258 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001259 return false;
1260 }
1261 unsigned BaseEltSize = EltAsInt.getBitWidth();
1262 if (BigEndian)
1263 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1264 else
1265 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1266 }
1267 return true;
1268 }
1269 // Give up if the input isn't an int, float, or vector. For example, we
1270 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001271 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001272 return false;
1273}
1274
Richard Smitha8105bc2012-01-06 16:39:00 +00001275/// Cast an lvalue referring to a base subobject to a derived class, by
1276/// truncating the lvalue's path to the given length.
1277static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1278 const RecordDecl *TruncatedType,
1279 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001280 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001281
1282 // Check we actually point to a derived class object.
1283 if (TruncatedElements == D.Entries.size())
1284 return true;
1285 assert(TruncatedElements >= D.MostDerivedPathLength &&
1286 "not casting to a derived class");
1287 if (!Result.checkSubobject(Info, E, CSK_Derived))
1288 return false;
1289
1290 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001291 const RecordDecl *RD = TruncatedType;
1292 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001293 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001294 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1295 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001296 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001297 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001298 else
Richard Smithd62306a2011-11-10 06:34:14 +00001299 Result.Offset -= Layout.getBaseClassOffset(Base);
1300 RD = Base;
1301 }
Richard Smith027bf112011-11-17 22:56:20 +00001302 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001303 return true;
1304}
1305
John McCalld7bca762012-05-01 00:38:49 +00001306static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001307 const CXXRecordDecl *Derived,
1308 const CXXRecordDecl *Base,
1309 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001310 if (!RL) {
1311 if (Derived->isInvalidDecl()) return false;
1312 RL = &Info.Ctx.getASTRecordLayout(Derived);
1313 }
1314
Richard Smithd62306a2011-11-10 06:34:14 +00001315 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001316 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001317 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001318}
1319
Richard Smitha8105bc2012-01-06 16:39:00 +00001320static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001321 const CXXRecordDecl *DerivedDecl,
1322 const CXXBaseSpecifier *Base) {
1323 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1324
John McCalld7bca762012-05-01 00:38:49 +00001325 if (!Base->isVirtual())
1326 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001327
Richard Smitha8105bc2012-01-06 16:39:00 +00001328 SubobjectDesignator &D = Obj.Designator;
1329 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001330 return false;
1331
Richard Smitha8105bc2012-01-06 16:39:00 +00001332 // Extract most-derived object and corresponding type.
1333 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1334 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1335 return false;
1336
1337 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001338 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001339 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1340 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001341 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001342 return true;
1343}
1344
1345/// Update LVal to refer to the given field, which must be a member of the type
1346/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001347static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001348 const FieldDecl *FD,
1349 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001350 if (!RL) {
1351 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001352 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001353 }
Richard Smithd62306a2011-11-10 06:34:14 +00001354
1355 unsigned I = FD->getFieldIndex();
1356 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001357 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001358 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001359}
1360
Richard Smith1b78b3d2012-01-25 22:15:11 +00001361/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001362static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001363 LValue &LVal,
1364 const IndirectFieldDecl *IFD) {
1365 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1366 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001367 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1368 return false;
1369 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001370}
1371
Richard Smithd62306a2011-11-10 06:34:14 +00001372/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001373static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1374 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001375 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1376 // extension.
1377 if (Type->isVoidType() || Type->isFunctionType()) {
1378 Size = CharUnits::One();
1379 return true;
1380 }
1381
1382 if (!Type->isConstantSizeType()) {
1383 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001384 // FIXME: Better diagnostic.
1385 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001386 return false;
1387 }
1388
1389 Size = Info.Ctx.getTypeSizeInChars(Type);
1390 return true;
1391}
1392
1393/// Update a pointer value to model pointer arithmetic.
1394/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001395/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001396/// \param LVal - The pointer value to be updated.
1397/// \param EltTy - The pointee type represented by LVal.
1398/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001399static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1400 LValue &LVal, QualType EltTy,
1401 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001402 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001403 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001404 return false;
1405
1406 // Compute the new offset in the appropriate width.
1407 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001408 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001409 return true;
1410}
1411
Richard Smith66c96992012-02-18 22:04:06 +00001412/// Update an lvalue to refer to a component of a complex number.
1413/// \param Info - Information about the ongoing evaluation.
1414/// \param LVal - The lvalue to be updated.
1415/// \param EltTy - The complex number's component type.
1416/// \param Imag - False for the real component, true for the imaginary.
1417static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1418 LValue &LVal, QualType EltTy,
1419 bool Imag) {
1420 if (Imag) {
1421 CharUnits SizeOfComponent;
1422 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1423 return false;
1424 LVal.Offset += SizeOfComponent;
1425 }
1426 LVal.addComplex(Info, E, EltTy, Imag);
1427 return true;
1428}
1429
Richard Smith27908702011-10-24 17:54:18 +00001430/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001431static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1432 const VarDecl *VD,
Richard Smith2e312c82012-03-03 22:46:17 +00001433 CallStackFrame *Frame, APValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001434 // If this is a parameter to an active constexpr function call, perform
1435 // argument substitution.
1436 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001437 // Assume arguments of a potential constant expression are unknown
1438 // constant expressions.
1439 if (Info.CheckingPotentialConstantExpression)
1440 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001441 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001442 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001443 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001444 }
Richard Smithfec09922011-11-01 16:57:24 +00001445 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1446 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001447 }
Richard Smith27908702011-10-24 17:54:18 +00001448
Richard Smithd0b4dd62011-12-19 06:19:21 +00001449 // Dig out the initializer, and use the declaration which it's attached to.
1450 const Expr *Init = VD->getAnyInitializer(VD);
1451 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001452 // If we're checking a potential constant expression, the variable could be
1453 // initialized later.
1454 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001455 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001456 return false;
1457 }
1458
Richard Smithd62306a2011-11-10 06:34:14 +00001459 // If we're currently evaluating the initializer of this declaration, use that
1460 // in-flight value.
1461 if (Info.EvaluatingDecl == VD) {
Richard Smith2e312c82012-03-03 22:46:17 +00001462 Result = *Info.EvaluatingDeclValue;
Richard Smithd62306a2011-11-10 06:34:14 +00001463 return !Result.isUninit();
1464 }
1465
Richard Smithcecf1842011-11-01 21:06:14 +00001466 // Never evaluate the initializer of a weak variable. We can't be sure that
1467 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001468 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001469 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001470 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001471 }
Richard Smithcecf1842011-11-01 21:06:14 +00001472
Richard Smithd0b4dd62011-12-19 06:19:21 +00001473 // Check that we can fold the initializer. In C++, we will have already done
1474 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001475 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001476 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001477 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001478 Notes.size() + 1) << VD;
1479 Info.Note(VD->getLocation(), diag::note_declared_at);
1480 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001481 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001482 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001483 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001484 Notes.size() + 1) << VD;
1485 Info.Note(VD->getLocation(), diag::note_declared_at);
1486 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001487 }
Richard Smith27908702011-10-24 17:54:18 +00001488
Richard Smith2e312c82012-03-03 22:46:17 +00001489 Result = *VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001490 return true;
Richard Smith27908702011-10-24 17:54:18 +00001491}
1492
Richard Smith11562c52011-10-28 17:51:58 +00001493static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001494 Qualifiers Quals = T.getQualifiers();
1495 return Quals.hasConst() && !Quals.hasVolatile();
1496}
1497
Richard Smithe97cbd72011-11-11 04:05:33 +00001498/// Get the base index of the given base class within an APValue representing
1499/// the given derived class.
1500static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1501 const CXXRecordDecl *Base) {
1502 Base = Base->getCanonicalDecl();
1503 unsigned Index = 0;
1504 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1505 E = Derived->bases_end(); I != E; ++I, ++Index) {
1506 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1507 return Index;
1508 }
1509
1510 llvm_unreachable("base class missing from derived class's bases list");
1511}
1512
Richard Smith9ec1e482012-04-15 02:50:59 +00001513/// Extract the value of a character from a string literal. CharType is used to
1514/// determine the expected signedness of the result -- a string literal used to
1515/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1516/// of the wrong signedness.
Richard Smith14a94132012-02-17 03:35:37 +00001517static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smith9ec1e482012-04-15 02:50:59 +00001518 uint64_t Index, QualType CharType) {
Richard Smith14a94132012-02-17 03:35:37 +00001519 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1520 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1521 assert(S && "unexpected string literal expression kind");
Richard Smith9ec1e482012-04-15 02:50:59 +00001522 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001523
1524 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001525 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001526 if (Index < S->getLength())
1527 Value = S->getCodeUnit(Index);
1528 return Value;
1529}
1530
Richard Smithf3e9e432011-11-07 09:22:26 +00001531/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001532static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith2e312c82012-03-03 22:46:17 +00001533 APValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001534 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001535 if (Sub.Invalid)
1536 // A diagnostic will have already been produced.
Richard Smithf3e9e432011-11-07 09:22:26 +00001537 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00001538 if (Sub.isOnePastTheEnd()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001539 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001540 (unsigned)diag::note_constexpr_read_past_end :
1541 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001542 return false;
1543 }
Richard Smith6804be52011-11-11 08:28:03 +00001544 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001545 return true;
Richard Smith253c2a32012-01-27 01:14:48 +00001546 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1547 // This object might be initialized later.
1548 return false;
Richard Smithf3e9e432011-11-07 09:22:26 +00001549
Richard Smith4e9e5232012-03-10 00:28:11 +00001550 APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001551 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001552 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001553 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001554 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001555 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001556 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001557 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001558 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001559 // Note, it should not be possible to form a pointer with a valid
1560 // designator which points more than one past the end of the array.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001561 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001562 (unsigned)diag::note_constexpr_read_past_end :
1563 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001564 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001565 }
Richard Smith14a94132012-02-17 03:35:37 +00001566 // An array object is represented as either an Array APValue or as an
1567 // LValue which refers to a string literal.
1568 if (O->isLValue()) {
1569 assert(I == N - 1 && "extracting subobject of character?");
1570 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith2e312c82012-03-03 22:46:17 +00001571 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smith9ec1e482012-04-15 02:50:59 +00001572 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smith14a94132012-02-17 03:35:37 +00001573 return true;
1574 } else if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001575 O = &O->getArrayInitializedElt(Index);
1576 else
1577 O = &O->getArrayFiller();
1578 ObjType = CAT->getElementType();
Richard Smith66c96992012-02-18 22:04:06 +00001579 } else if (ObjType->isAnyComplexType()) {
1580 // Next subobject is a complex number.
1581 uint64_t Index = Sub.Entries[I].ArrayIndex;
1582 if (Index > 1) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001583 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Richard Smith66c96992012-02-18 22:04:06 +00001584 (unsigned)diag::note_constexpr_read_past_end :
1585 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1586 return false;
1587 }
1588 assert(I == N - 1 && "extracting subobject of scalar?");
1589 if (O->isComplexInt()) {
Richard Smith2e312c82012-03-03 22:46:17 +00001590 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith66c96992012-02-18 22:04:06 +00001591 : O->getComplexIntReal());
1592 } else {
1593 assert(O->isComplexFloat());
Richard Smith2e312c82012-03-03 22:46:17 +00001594 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith66c96992012-02-18 22:04:06 +00001595 : O->getComplexFloatReal());
1596 }
1597 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001598 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith5a294e62012-02-09 03:29:58 +00001599 if (Field->isMutable()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001600 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001601 << Field;
1602 Info.Note(Field->getLocation(), diag::note_declared_at);
1603 return false;
1604 }
1605
Richard Smithd62306a2011-11-10 06:34:14 +00001606 // Next subobject is a class, struct or union field.
1607 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1608 if (RD->isUnion()) {
1609 const FieldDecl *UnionField = O->getUnionField();
1610 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001611 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001612 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smithf2b681b2011-12-21 05:04:46 +00001613 << Field << !UnionField << UnionField;
Richard Smithd62306a2011-11-10 06:34:14 +00001614 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001615 }
Richard Smithd62306a2011-11-10 06:34:14 +00001616 O = &O->getUnionValue();
1617 } else
1618 O = &O->getStructField(Field->getFieldIndex());
1619 ObjType = Field->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001620
1621 if (ObjType.isVolatileQualified()) {
1622 if (Info.getLangOpts().CPlusPlus) {
1623 // FIXME: Include a description of the path to the volatile subobject.
Richard Smithce1ec5e2012-03-15 04:53:45 +00001624 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smithf2b681b2011-12-21 05:04:46 +00001625 << 2 << Field;
1626 Info.Note(Field->getLocation(), diag::note_declared_at);
1627 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001628 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001629 }
1630 return false;
1631 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001632 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001633 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001634 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1635 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1636 O = &O->getStructBase(getBaseIndex(Derived, Base));
1637 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001638 }
Richard Smithd62306a2011-11-10 06:34:14 +00001639
Richard Smithf57d8cb2011-12-09 22:58:01 +00001640 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001641 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001642 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smithd62306a2011-11-10 06:34:14 +00001643 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001644 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001645 }
1646
Richard Smith4e9e5232012-03-10 00:28:11 +00001647 // This may look super-stupid, but it serves an important purpose: if we just
1648 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1649 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1650 // object, which is destroyed by Tmp's destructor.
1651 APValue Tmp;
1652 O->swap(Tmp);
1653 Obj.swap(Tmp);
Richard Smithf3e9e432011-11-07 09:22:26 +00001654 return true;
1655}
1656
Richard Smith84f6dcf2012-02-02 01:16:57 +00001657/// Find the position where two subobject designators diverge, or equivalently
1658/// the length of the common initial subsequence.
1659static unsigned FindDesignatorMismatch(QualType ObjType,
1660 const SubobjectDesignator &A,
1661 const SubobjectDesignator &B,
1662 bool &WasArrayIndex) {
1663 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1664 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00001665 if (!ObjType.isNull() &&
1666 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00001667 // Next subobject is an array element.
1668 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1669 WasArrayIndex = true;
1670 return I;
1671 }
Richard Smith66c96992012-02-18 22:04:06 +00001672 if (ObjType->isAnyComplexType())
1673 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1674 else
1675 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00001676 } else {
1677 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1678 WasArrayIndex = false;
1679 return I;
1680 }
1681 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1682 // Next subobject is a field.
1683 ObjType = FD->getType();
1684 else
1685 // Next subobject is a base class.
1686 ObjType = QualType();
1687 }
1688 }
1689 WasArrayIndex = false;
1690 return I;
1691}
1692
1693/// Determine whether the given subobject designators refer to elements of the
1694/// same array object.
1695static bool AreElementsOfSameArray(QualType ObjType,
1696 const SubobjectDesignator &A,
1697 const SubobjectDesignator &B) {
1698 if (A.Entries.size() != B.Entries.size())
1699 return false;
1700
1701 bool IsArray = A.MostDerivedArraySize != 0;
1702 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1703 // A is a subobject of the array element.
1704 return false;
1705
1706 // If A (and B) designates an array element, the last entry will be the array
1707 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1708 // of length 1' case, and the entire path must match.
1709 bool WasArrayIndex;
1710 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1711 return CommonLength >= A.Entries.size() - IsArray;
1712}
1713
Richard Smithd62306a2011-11-10 06:34:14 +00001714/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1715/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1716/// for looking up the glvalue referred to by an entity of reference type.
1717///
1718/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001719/// \param Conv - The expression for which we are performing the conversion.
1720/// Used for diagnostics.
Richard Smithc82fae62012-02-05 01:23:16 +00001721/// \param Type - The type we expect this conversion to produce, before
1722/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smithd62306a2011-11-10 06:34:14 +00001723/// \param LVal - The glvalue on which we are attempting to perform this action.
1724/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001725static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1726 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00001727 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001728 if (LVal.Designator.Invalid)
1729 // A diagnostic will have already been produced.
1730 return false;
1731
Richard Smithce40ad62011-11-12 22:28:03 +00001732 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith11562c52011-10-28 17:51:58 +00001733
Richard Smithf57d8cb2011-12-09 22:58:01 +00001734 if (!LVal.Base) {
1735 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithce1ec5e2012-03-15 04:53:45 +00001736 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001737 return false;
1738 }
1739
Richard Smithb228a862012-02-15 02:18:13 +00001740 CallStackFrame *Frame = 0;
1741 if (LVal.CallIndex) {
1742 Frame = Info.getCallFrame(LVal.CallIndex);
1743 if (!Frame) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001744 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smithb228a862012-02-15 02:18:13 +00001745 NoteLValueLocation(Info, LVal.Base);
1746 return false;
1747 }
1748 }
1749
Richard Smithf2b681b2011-12-21 05:04:46 +00001750 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1751 // is not a constant expression (even if the object is non-volatile). We also
1752 // apply this rule to C++98, in order to conform to the expected 'volatile'
1753 // semantics.
1754 if (Type.isVolatileQualified()) {
1755 if (Info.getLangOpts().CPlusPlus)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001756 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smithf2b681b2011-12-21 05:04:46 +00001757 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001758 Info.Diag(Conv);
Richard Smith11562c52011-10-28 17:51:58 +00001759 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001760 }
Richard Smith11562c52011-10-28 17:51:58 +00001761
Richard Smithce40ad62011-11-12 22:28:03 +00001762 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001763 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1764 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001765 // expressions are constant expressions too. Inside constexpr functions,
1766 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001767 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001768 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001769 if (VD) {
1770 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1771 VD = VDef;
1772 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001773 if (!VD || VD->isInvalidDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001774 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00001775 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001776 }
1777
Richard Smithf2b681b2011-12-21 05:04:46 +00001778 // DR1313: If the object is volatile-qualified but the glvalue was not,
1779 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001780 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001781 if (VT.isVolatileQualified()) {
1782 if (Info.getLangOpts().CPlusPlus) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001783 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001784 Info.Note(VD->getLocation(), diag::note_declared_at);
1785 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001786 Info.Diag(Conv);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001787 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001788 return false;
1789 }
1790
1791 if (!isa<ParmVarDecl>(VD)) {
1792 if (VD->isConstexpr()) {
1793 // OK, we can read this variable.
1794 } else if (VT->isIntegralOrEnumerationType()) {
1795 if (!VT.isConstQualified()) {
1796 if (Info.getLangOpts().CPlusPlus) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001797 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001798 Info.Note(VD->getLocation(), diag::note_declared_at);
1799 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001800 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001801 }
1802 return false;
1803 }
1804 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1805 // We support folding of const floating-point types, in order to make
1806 // static const data members of such types (supported as an extension)
1807 // more useful.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001808 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001809 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001810 Info.Note(VD->getLocation(), diag::note_declared_at);
1811 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001812 Info.CCEDiag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001813 }
1814 } else {
1815 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001816 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001817 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001818 Info.Note(VD->getLocation(), diag::note_declared_at);
1819 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001820 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001821 }
Richard Smith96e0c102011-11-04 02:25:55 +00001822 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001823 }
Richard Smith96e0c102011-11-04 02:25:55 +00001824 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001825
Richard Smithf57d8cb2011-12-09 22:58:01 +00001826 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001827 return false;
1828
Richard Smith0b0a0b62011-10-29 20:57:55 +00001829 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001830 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001831
1832 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1833 // conversion. This happens when the declaration and the lvalue should be
1834 // considered synonymous, for instance when initializing an array of char
1835 // from a string literal. Continue as if the initializer lvalue was the
1836 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001837 assert(RVal.getLValueOffset().isZero() &&
1838 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001839 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithb228a862012-02-15 02:18:13 +00001840
1841 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1842 Frame = Info.getCallFrame(CallIndex);
1843 if (!Frame) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001844 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smithb228a862012-02-15 02:18:13 +00001845 NoteLValueLocation(Info, RVal.getLValueBase());
1846 return false;
1847 }
1848 } else {
1849 Frame = 0;
1850 }
Richard Smith11562c52011-10-28 17:51:58 +00001851 }
1852
Richard Smithf2b681b2011-12-21 05:04:46 +00001853 // Volatile temporary objects cannot be read in constant expressions.
1854 if (Base->getType().isVolatileQualified()) {
1855 if (Info.getLangOpts().CPlusPlus) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001856 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smithf2b681b2011-12-21 05:04:46 +00001857 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1858 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001859 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001860 }
1861 return false;
1862 }
1863
Richard Smithf3e9e432011-11-07 09:22:26 +00001864 if (Frame) {
1865 // If this is a temporary expression with a nontrivial initializer, grab the
1866 // value from the relevant stack frame.
1867 RVal = Frame->Temporaries[Base];
1868 } else if (const CompoundLiteralExpr *CLE
1869 = dyn_cast<CompoundLiteralExpr>(Base)) {
1870 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1871 // initializer until now for such expressions. Such an expression can't be
1872 // an ICE in C, so this only matters for fold.
1873 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1874 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1875 return false;
Richard Smith14a94132012-02-17 03:35:37 +00001876 } else if (isa<StringLiteral>(Base)) {
1877 // We represent a string literal array as an lvalue pointing at the
1878 // corresponding expression, rather than building an array of chars.
1879 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith2e312c82012-03-03 22:46:17 +00001880 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001881 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001882 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001883 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001884 }
Richard Smith96e0c102011-11-04 02:25:55 +00001885
Richard Smithf57d8cb2011-12-09 22:58:01 +00001886 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1887 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001888}
1889
Richard Smithe97cbd72011-11-11 04:05:33 +00001890/// Build an lvalue for the object argument of a member function call.
1891static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1892 LValue &This) {
1893 if (Object->getType()->isPointerType())
1894 return EvaluatePointer(Object, This, Info);
1895
1896 if (Object->isGLValue())
1897 return EvaluateLValue(Object, This, Info);
1898
Richard Smith027bf112011-11-17 22:56:20 +00001899 if (Object->getType()->isLiteralType())
1900 return EvaluateTemporary(Object, This, Info);
1901
1902 return false;
1903}
1904
1905/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1906/// lvalue referring to the result.
1907///
1908/// \param Info - Information about the ongoing evaluation.
1909/// \param BO - The member pointer access operation.
1910/// \param LV - Filled in with a reference to the resulting object.
1911/// \param IncludeMember - Specifies whether the member itself is included in
1912/// the resulting LValue subobject designator. This is not possible when
1913/// creating a bound member function.
1914/// \return The field or method declaration to which the member pointer refers,
1915/// or 0 if evaluation fails.
1916static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1917 const BinaryOperator *BO,
1918 LValue &LV,
1919 bool IncludeMember = true) {
1920 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1921
Richard Smith253c2a32012-01-27 01:14:48 +00001922 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1923 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00001924 return 0;
1925
1926 MemberPtr MemPtr;
1927 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1928 return 0;
1929
1930 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1931 // member value, the behavior is undefined.
1932 if (!MemPtr.getDecl())
1933 return 0;
1934
Richard Smith253c2a32012-01-27 01:14:48 +00001935 if (!EvalObjOK)
1936 return 0;
1937
Richard Smith027bf112011-11-17 22:56:20 +00001938 if (MemPtr.isDerivedMember()) {
1939 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00001940 // The end of the derived-to-base path for the base object must match the
1941 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00001942 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00001943 LV.Designator.Entries.size())
1944 return 0;
1945 unsigned PathLengthToMember =
1946 LV.Designator.Entries.size() - MemPtr.Path.size();
1947 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1948 const CXXRecordDecl *LVDecl = getAsBaseClass(
1949 LV.Designator.Entries[PathLengthToMember + I]);
1950 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1951 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1952 return 0;
1953 }
1954
1955 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00001956 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1957 PathLengthToMember))
1958 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00001959 } else if (!MemPtr.Path.empty()) {
1960 // Extend the LValue path with the member pointer's path.
1961 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1962 MemPtr.Path.size() + IncludeMember);
1963
1964 // Walk down to the appropriate base class.
1965 QualType LVType = BO->getLHS()->getType();
1966 if (const PointerType *PT = LVType->getAs<PointerType>())
1967 LVType = PT->getPointeeType();
1968 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1969 assert(RD && "member pointer access on non-class-type expression");
1970 // The first class in the path is that of the lvalue.
1971 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1972 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00001973 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1974 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00001975 RD = Base;
1976 }
1977 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00001978 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1979 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00001980 }
1981
1982 // Add the member. Note that we cannot build bound member functions here.
1983 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00001984 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
1985 if (!HandleLValueMember(Info, BO, LV, FD))
1986 return 0;
1987 } else if (const IndirectFieldDecl *IFD =
1988 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
1989 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
1990 return 0;
1991 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00001992 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00001993 }
Richard Smith027bf112011-11-17 22:56:20 +00001994 }
1995
1996 return MemPtr.getDecl();
1997}
1998
1999/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2000/// the provided lvalue, which currently refers to the base object.
2001static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2002 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002003 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002004 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002005 return false;
2006
Richard Smitha8105bc2012-01-06 16:39:00 +00002007 QualType TargetQT = E->getType();
2008 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2009 TargetQT = PT->getPointeeType();
2010
2011 // Check this cast lands within the final derived-to-base subobject path.
2012 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002013 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002014 << D.MostDerivedType << TargetQT;
2015 return false;
2016 }
2017
Richard Smith027bf112011-11-17 22:56:20 +00002018 // Check the type of the final cast. We don't need to check the path,
2019 // since a cast can only be formed if the path is unique.
2020 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002021 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2022 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002023 if (NewEntriesSize == D.MostDerivedPathLength)
2024 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2025 else
Richard Smith027bf112011-11-17 22:56:20 +00002026 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002027 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002028 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002029 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002030 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002031 }
Richard Smith027bf112011-11-17 22:56:20 +00002032
2033 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002034 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002035}
2036
Mike Stump876387b2009-10-27 22:09:17 +00002037namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002038enum EvalStmtResult {
2039 /// Evaluation failed.
2040 ESR_Failed,
2041 /// Hit a 'return' statement.
2042 ESR_Returned,
2043 /// Evaluation succeeded.
2044 ESR_Succeeded
2045};
2046}
2047
2048// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002049static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00002050 const Stmt *S) {
2051 switch (S->getStmtClass()) {
2052 default:
2053 return ESR_Failed;
2054
2055 case Stmt::NullStmtClass:
2056 case Stmt::DeclStmtClass:
2057 return ESR_Succeeded;
2058
Richard Smith357362d2011-12-13 06:39:58 +00002059 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002060 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithb228a862012-02-15 02:18:13 +00002061 if (!Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002062 return ESR_Failed;
2063 return ESR_Returned;
2064 }
Richard Smith254a73d2011-10-28 22:34:42 +00002065
2066 case Stmt::CompoundStmtClass: {
2067 const CompoundStmt *CS = cast<CompoundStmt>(S);
2068 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2069 BE = CS->body_end(); BI != BE; ++BI) {
2070 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2071 if (ESR != ESR_Succeeded)
2072 return ESR;
2073 }
2074 return ESR_Succeeded;
2075 }
2076 }
2077}
2078
Richard Smithcc36f692011-12-22 02:22:31 +00002079/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2080/// default constructor. If so, we'll fold it whether or not it's marked as
2081/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2082/// so we need special handling.
2083static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00002084 const CXXConstructorDecl *CD,
2085 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00002086 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2087 return false;
2088
Richard Smith66e05fe2012-01-18 05:21:49 +00002089 // Value-initialization does not call a trivial default constructor, so such a
2090 // call is a core constant expression whether or not the constructor is
2091 // constexpr.
2092 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002093 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00002094 // FIXME: If DiagDecl is an implicitly-declared special member function,
2095 // we should be much more explicit about why it's not constexpr.
2096 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2097 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2098 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00002099 } else {
2100 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2101 }
2102 }
2103 return true;
2104}
2105
Richard Smith357362d2011-12-13 06:39:58 +00002106/// CheckConstexprFunction - Check that a function can be called in a constant
2107/// expression.
2108static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2109 const FunctionDecl *Declaration,
2110 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00002111 // Potential constant expressions can contain calls to declared, but not yet
2112 // defined, constexpr functions.
2113 if (Info.CheckingPotentialConstantExpression && !Definition &&
2114 Declaration->isConstexpr())
2115 return false;
2116
Richard Smith357362d2011-12-13 06:39:58 +00002117 // Can we evaluate this function call?
2118 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2119 return true;
2120
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002121 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00002122 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002123 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2124 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00002125 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2126 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2127 << DiagDecl;
2128 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2129 } else {
2130 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2131 }
2132 return false;
2133}
2134
Richard Smithd62306a2011-11-10 06:34:14 +00002135namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00002136typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00002137}
2138
2139/// EvaluateArgs - Evaluate the arguments to a function call.
2140static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2141 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00002142 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002143 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00002144 I != E; ++I) {
2145 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2146 // If we're checking for a potential constant expression, evaluate all
2147 // initializers even if some of them fail.
2148 if (!Info.keepEvaluatingAfterFailure())
2149 return false;
2150 Success = false;
2151 }
2152 }
2153 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00002154}
2155
Richard Smith254a73d2011-10-28 22:34:42 +00002156/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00002157static bool HandleFunctionCall(SourceLocation CallLoc,
2158 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002159 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00002160 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002161 ArgVector ArgValues(Args.size());
2162 if (!EvaluateArgs(Args, ArgValues, Info))
2163 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00002164
Richard Smith253c2a32012-01-27 01:14:48 +00002165 if (!Info.CheckCallLimit(CallLoc))
2166 return false;
2167
2168 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00002169 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2170}
2171
Richard Smithd62306a2011-11-10 06:34:14 +00002172/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00002173static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00002174 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00002175 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00002176 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002177 ArgVector ArgValues(Args.size());
2178 if (!EvaluateArgs(Args, ArgValues, Info))
2179 return false;
2180
Richard Smith253c2a32012-01-27 01:14:48 +00002181 if (!Info.CheckCallLimit(CallLoc))
2182 return false;
2183
Richard Smith3607ffe2012-02-13 03:54:03 +00002184 const CXXRecordDecl *RD = Definition->getParent();
2185 if (RD->getNumVBases()) {
2186 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2187 return false;
2188 }
2189
Richard Smith253c2a32012-01-27 01:14:48 +00002190 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00002191
2192 // If it's a delegating constructor, just delegate.
2193 if (Definition->isDelegatingConstructor()) {
2194 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithb228a862012-02-15 02:18:13 +00002195 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smithd62306a2011-11-10 06:34:14 +00002196 }
2197
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002198 // For a trivial copy or move constructor, perform an APValue copy. This is
2199 // essential for unions, where the operations performed by the constructor
2200 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002201 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00002202 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2203 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002204 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00002205 RHS.setFrom(Info.Ctx, ArgValues[0]);
2206 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2207 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002208 }
2209
2210 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00002211 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00002212 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2213 std::distance(RD->field_begin(), RD->field_end()));
2214
John McCalld7bca762012-05-01 00:38:49 +00002215 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002216 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2217
Richard Smith253c2a32012-01-27 01:14:48 +00002218 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002219 unsigned BasesSeen = 0;
2220#ifndef NDEBUG
2221 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2222#endif
2223 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2224 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00002225 LValue Subobject = This;
2226 APValue *Value = &Result;
2227
2228 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00002229 if ((*I)->isBaseInitializer()) {
2230 QualType BaseType((*I)->getBaseClass(), 0);
2231#ifndef NDEBUG
2232 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00002233 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00002234 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2235 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2236 "base class initializers not in expected order");
2237 ++BaseIt;
2238#endif
John McCalld7bca762012-05-01 00:38:49 +00002239 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2240 BaseType->getAsCXXRecordDecl(), &Layout))
2241 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00002242 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00002243 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00002244 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2245 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002246 if (RD->isUnion()) {
2247 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00002248 Value = &Result.getUnionValue();
2249 } else {
2250 Value = &Result.getStructField(FD->getFieldIndex());
2251 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00002252 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002253 // Walk the indirect field decl's chain to find the object to initialize,
2254 // and make sure we've initialized every step along it.
2255 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2256 CE = IFD->chain_end();
2257 C != CE; ++C) {
2258 FieldDecl *FD = cast<FieldDecl>(*C);
2259 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2260 // Switch the union field if it differs. This happens if we had
2261 // preceding zero-initialization, and we're now initializing a union
2262 // subobject other than the first.
2263 // FIXME: In this case, the values of the other subobjects are
2264 // specified, since zero-initialization sets all padding bits to zero.
2265 if (Value->isUninit() ||
2266 (Value->isUnion() && Value->getUnionField() != FD)) {
2267 if (CD->isUnion())
2268 *Value = APValue(FD);
2269 else
2270 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2271 std::distance(CD->field_begin(), CD->field_end()));
2272 }
John McCalld7bca762012-05-01 00:38:49 +00002273 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2274 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002275 if (CD->isUnion())
2276 Value = &Value->getUnionValue();
2277 else
2278 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00002279 }
Richard Smithd62306a2011-11-10 06:34:14 +00002280 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002281 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00002282 }
Richard Smith253c2a32012-01-27 01:14:48 +00002283
Richard Smithb228a862012-02-15 02:18:13 +00002284 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2285 (*I)->isBaseInitializer()
Richard Smith253c2a32012-01-27 01:14:48 +00002286 ? CCEK_Constant : CCEK_MemberInit)) {
2287 // If we're checking for a potential constant expression, evaluate all
2288 // initializers even if some of them fail.
2289 if (!Info.keepEvaluatingAfterFailure())
2290 return false;
2291 Success = false;
2292 }
Richard Smithd62306a2011-11-10 06:34:14 +00002293 }
2294
Richard Smith253c2a32012-01-27 01:14:48 +00002295 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00002296}
2297
Eli Friedman9a156e52008-11-12 09:44:48 +00002298//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00002299// Generic Evaluation
2300//===----------------------------------------------------------------------===//
2301namespace {
2302
Richard Smithf57d8cb2011-12-09 22:58:01 +00002303// FIXME: RetTy is always bool. Remove it.
2304template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00002305class ExprEvaluatorBase
2306 : public ConstStmtVisitor<Derived, RetTy> {
2307private:
Richard Smith2e312c82012-03-03 22:46:17 +00002308 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002309 return static_cast<Derived*>(this)->Success(V, E);
2310 }
Richard Smithfddd3842011-12-30 21:15:51 +00002311 RetTy DerivedZeroInitialization(const Expr *E) {
2312 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002313 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002314
Richard Smith17100ba2012-02-16 02:46:34 +00002315 // Check whether a conditional operator with a non-constant condition is a
2316 // potential constant expression. If neither arm is a potential constant
2317 // expression, then the conditional operator is not either.
2318 template<typename ConditionalOperator>
2319 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2320 assert(Info.CheckingPotentialConstantExpression);
2321
2322 // Speculatively evaluate both arms.
2323 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002324 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00002325 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2326
2327 StmtVisitorTy::Visit(E->getFalseExpr());
2328 if (Diag.empty())
2329 return;
2330
2331 Diag.clear();
2332 StmtVisitorTy::Visit(E->getTrueExpr());
2333 if (Diag.empty())
2334 return;
2335 }
2336
2337 Error(E, diag::note_constexpr_conditional_never_const);
2338 }
2339
2340
2341 template<typename ConditionalOperator>
2342 bool HandleConditionalOperator(const ConditionalOperator *E) {
2343 bool BoolResult;
2344 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2345 if (Info.CheckingPotentialConstantExpression)
2346 CheckPotentialConstantConditional(E);
2347 return false;
2348 }
2349
2350 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2351 return StmtVisitorTy::Visit(EvalExpr);
2352 }
2353
Peter Collingbournee9200682011-05-13 03:29:01 +00002354protected:
2355 EvalInfo &Info;
2356 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2357 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2358
Richard Smith92b1ce02011-12-12 09:28:41 +00002359 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002360 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002361 }
2362
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00002363 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2364
2365public:
2366 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2367
2368 EvalInfo &getEvalInfo() { return Info; }
2369
Richard Smithf57d8cb2011-12-09 22:58:01 +00002370 /// Report an evaluation error. This should only be called when an error is
2371 /// first discovered. When propagating an error, just return false.
2372 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002373 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002374 return false;
2375 }
2376 bool Error(const Expr *E) {
2377 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2378 }
2379
Peter Collingbournee9200682011-05-13 03:29:01 +00002380 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00002381 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00002382 }
2383 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002384 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002385 }
2386
2387 RetTy VisitParenExpr(const ParenExpr *E)
2388 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2389 RetTy VisitUnaryExtension(const UnaryOperator *E)
2390 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2391 RetTy VisitUnaryPlus(const UnaryOperator *E)
2392 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2393 RetTy VisitChooseExpr(const ChooseExpr *E)
2394 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2395 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2396 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00002397 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2398 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00002399 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2400 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00002401 // We cannot create any objects for which cleanups are required, so there is
2402 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2403 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2404 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002405
Richard Smith6d6ecc32011-12-12 12:46:16 +00002406 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2407 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2408 return static_cast<Derived*>(this)->VisitCastExpr(E);
2409 }
2410 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2411 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2412 return static_cast<Derived*>(this)->VisitCastExpr(E);
2413 }
2414
Richard Smith027bf112011-11-17 22:56:20 +00002415 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2416 switch (E->getOpcode()) {
2417 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00002418 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002419
2420 case BO_Comma:
2421 VisitIgnoredValue(E->getLHS());
2422 return StmtVisitorTy::Visit(E->getRHS());
2423
2424 case BO_PtrMemD:
2425 case BO_PtrMemI: {
2426 LValue Obj;
2427 if (!HandleMemberPointerAccess(Info, E, Obj))
2428 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00002429 APValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002430 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00002431 return false;
2432 return DerivedSuccess(Result, E);
2433 }
2434 }
2435 }
2436
Peter Collingbournee9200682011-05-13 03:29:01 +00002437 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00002438 // Evaluate and cache the common expression. We treat it as a temporary,
2439 // even though it's not quite the same thing.
2440 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2441 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002442 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002443
Richard Smith17100ba2012-02-16 02:46:34 +00002444 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002445 }
2446
2447 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002448 bool IsBcpCall = false;
2449 // If the condition (ignoring parens) is a __builtin_constant_p call,
2450 // the result is a constant expression if it can be folded without
2451 // side-effects. This is an important GNU extension. See GCC PR38377
2452 // for discussion.
2453 if (const CallExpr *CallCE =
2454 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2455 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2456 IsBcpCall = true;
2457
2458 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2459 // constant expression; we can't check whether it's potentially foldable.
2460 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2461 return false;
2462
2463 FoldConstant Fold(Info);
2464
Richard Smith17100ba2012-02-16 02:46:34 +00002465 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00002466 return false;
2467
2468 if (IsBcpCall)
2469 Fold.Fold(Info);
2470
2471 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00002472 }
2473
2474 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00002475 APValue &Value = Info.CurrentCall->Temporaries[E];
2476 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002477 const Expr *Source = E->getSourceExpr();
2478 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002479 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002480 if (Source == E) { // sanity checking.
2481 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002482 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002483 }
2484 return StmtVisitorTy::Visit(Source);
2485 }
Richard Smith26d4cc12012-06-26 08:12:11 +00002486 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002487 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002488
Richard Smith254a73d2011-10-28 22:34:42 +00002489 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002490 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002491 QualType CalleeType = Callee->getType();
2492
Richard Smith254a73d2011-10-28 22:34:42 +00002493 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002494 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002495 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00002496 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00002497
Richard Smithe97cbd72011-11-11 04:05:33 +00002498 // Extract function decl and 'this' pointer from the callee.
2499 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002500 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002501 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2502 // Explicit bound member calls, such as x.f() or p->g();
2503 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002504 return false;
2505 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002506 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00002507 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00002508 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2509 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002510 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2511 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002512 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002513 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002514 return Error(Callee);
2515
2516 FD = dyn_cast<FunctionDecl>(Member);
2517 if (!FD)
2518 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002519 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002520 LValue Call;
2521 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002522 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002523
Richard Smitha8105bc2012-01-06 16:39:00 +00002524 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002525 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002526 FD = dyn_cast_or_null<FunctionDecl>(
2527 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002528 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002529 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002530
2531 // Overloaded operator calls to member functions are represented as normal
2532 // calls with '*this' as the first argument.
2533 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2534 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002535 // FIXME: When selecting an implicit conversion for an overloaded
2536 // operator delete, we sometimes try to evaluate calls to conversion
2537 // operators without a 'this' parameter!
2538 if (Args.empty())
2539 return Error(E);
2540
Richard Smithe97cbd72011-11-11 04:05:33 +00002541 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2542 return false;
2543 This = &ThisVal;
2544 Args = Args.slice(1);
2545 }
2546
2547 // Don't call function pointers which have been cast to some other type.
2548 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002549 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002550 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002551 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002552
Richard Smith47b34932012-02-01 02:39:43 +00002553 if (This && !This->checkSubobject(Info, E, CSK_This))
2554 return false;
2555
Richard Smith3607ffe2012-02-13 03:54:03 +00002556 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2557 // calls to such functions in constant expressions.
2558 if (This && !HasQualifier &&
2559 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2560 return Error(E, diag::note_constexpr_virtual_call);
2561
Richard Smith357362d2011-12-13 06:39:58 +00002562 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002563 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00002564 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002565
Richard Smith357362d2011-12-13 06:39:58 +00002566 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00002567 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2568 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002569 return false;
2570
Richard Smithb228a862012-02-15 02:18:13 +00002571 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00002572 }
2573
Richard Smith11562c52011-10-28 17:51:58 +00002574 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2575 return StmtVisitorTy::Visit(E->getInitializer());
2576 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002577 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00002578 if (E->getNumInits() == 0)
2579 return DerivedZeroInitialization(E);
2580 if (E->getNumInits() == 1)
2581 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00002582 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002583 }
2584 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002585 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002586 }
2587 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002588 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002589 }
Richard Smith027bf112011-11-17 22:56:20 +00002590 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002591 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002592 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002593
Richard Smithd62306a2011-11-10 06:34:14 +00002594 /// A member expression where the object is a prvalue is itself a prvalue.
2595 RetTy VisitMemberExpr(const MemberExpr *E) {
2596 assert(!E->isArrow() && "missing call to bound member function?");
2597
Richard Smith2e312c82012-03-03 22:46:17 +00002598 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00002599 if (!Evaluate(Val, Info, E->getBase()))
2600 return false;
2601
2602 QualType BaseTy = E->getBase()->getType();
2603
2604 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002605 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002606 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00002607 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00002608 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2609
Richard Smitha8105bc2012-01-06 16:39:00 +00002610 SubobjectDesignator Designator(BaseTy);
2611 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00002612
Richard Smithf57d8cb2011-12-09 22:58:01 +00002613 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002614 DerivedSuccess(Val, E);
2615 }
2616
Richard Smith11562c52011-10-28 17:51:58 +00002617 RetTy VisitCastExpr(const CastExpr *E) {
2618 switch (E->getCastKind()) {
2619 default:
2620 break;
2621
David Chisnallfa35df62012-01-16 17:27:18 +00002622 case CK_AtomicToNonAtomic:
2623 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00002624 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00002625 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00002626 return StmtVisitorTy::Visit(E->getSubExpr());
2627
2628 case CK_LValueToRValue: {
2629 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002630 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2631 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00002632 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00002633 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2634 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2635 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002636 return false;
2637 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002638 }
2639 }
2640
Richard Smithf57d8cb2011-12-09 22:58:01 +00002641 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002642 }
2643
Richard Smith4a678122011-10-24 18:44:57 +00002644 /// Visit a value which is evaluated, but whose value is ignored.
2645 void VisitIgnoredValue(const Expr *E) {
Richard Smith2e312c82012-03-03 22:46:17 +00002646 APValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002647 if (!Evaluate(Scratch, Info, E))
2648 Info.EvalStatus.HasSideEffects = true;
2649 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002650};
2651
2652}
2653
2654//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002655// Common base class for lvalue and temporary evaluation.
2656//===----------------------------------------------------------------------===//
2657namespace {
2658template<class Derived>
2659class LValueExprEvaluatorBase
2660 : public ExprEvaluatorBase<Derived, bool> {
2661protected:
2662 LValue &Result;
2663 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2664 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2665
2666 bool Success(APValue::LValueBase B) {
2667 Result.set(B);
2668 return true;
2669 }
2670
2671public:
2672 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2673 ExprEvaluatorBaseTy(Info), Result(Result) {}
2674
Richard Smith2e312c82012-03-03 22:46:17 +00002675 bool Success(const APValue &V, const Expr *E) {
2676 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00002677 return true;
2678 }
Richard Smith027bf112011-11-17 22:56:20 +00002679
Richard Smith027bf112011-11-17 22:56:20 +00002680 bool VisitMemberExpr(const MemberExpr *E) {
2681 // Handle non-static data members.
2682 QualType BaseTy;
2683 if (E->isArrow()) {
2684 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2685 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00002686 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002687 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002688 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002689 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2690 return false;
2691 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002692 } else {
2693 if (!this->Visit(E->getBase()))
2694 return false;
2695 BaseTy = E->getBase()->getType();
2696 }
Richard Smith027bf112011-11-17 22:56:20 +00002697
Richard Smith1b78b3d2012-01-25 22:15:11 +00002698 const ValueDecl *MD = E->getMemberDecl();
2699 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2700 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2701 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2702 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00002703 if (!HandleLValueMember(this->Info, E, Result, FD))
2704 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002705 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00002706 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2707 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002708 } else
2709 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002710
Richard Smith1b78b3d2012-01-25 22:15:11 +00002711 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00002712 APValue RefValue;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002713 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002714 RefValue))
2715 return false;
2716 return Success(RefValue, E);
2717 }
2718 return true;
2719 }
2720
2721 bool VisitBinaryOperator(const BinaryOperator *E) {
2722 switch (E->getOpcode()) {
2723 default:
2724 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2725
2726 case BO_PtrMemD:
2727 case BO_PtrMemI:
2728 return HandleMemberPointerAccess(this->Info, E, Result);
2729 }
2730 }
2731
2732 bool VisitCastExpr(const CastExpr *E) {
2733 switch (E->getCastKind()) {
2734 default:
2735 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2736
2737 case CK_DerivedToBase:
2738 case CK_UncheckedDerivedToBase: {
2739 if (!this->Visit(E->getSubExpr()))
2740 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002741
2742 // Now figure out the necessary offset to add to the base LV to get from
2743 // the derived class to the base class.
2744 QualType Type = E->getSubExpr()->getType();
2745
2746 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2747 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002748 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00002749 *PathI))
2750 return false;
2751 Type = (*PathI)->getType();
2752 }
2753
2754 return true;
2755 }
2756 }
2757 }
2758};
2759}
2760
2761//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002762// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002763//
2764// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2765// function designators (in C), decl references to void objects (in C), and
2766// temporaries (if building with -Wno-address-of-temporary).
2767//
2768// LValue evaluation produces values comprising a base expression of one of the
2769// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002770// - Declarations
2771// * VarDecl
2772// * FunctionDecl
2773// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002774// * CompoundLiteralExpr in C
2775// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00002776// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00002777// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002778// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002779// * ObjCEncodeExpr
2780// * AddrLabelExpr
2781// * BlockExpr
2782// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002783// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00002784// * Any Expr, with a CallIndex indicating the function in which the temporary
2785// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00002786// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002787//===----------------------------------------------------------------------===//
2788namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002789class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002790 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002791public:
Richard Smith027bf112011-11-17 22:56:20 +00002792 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2793 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002794
Richard Smith11562c52011-10-28 17:51:58 +00002795 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2796
Peter Collingbournee9200682011-05-13 03:29:01 +00002797 bool VisitDeclRefExpr(const DeclRefExpr *E);
2798 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002799 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002800 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2801 bool VisitMemberExpr(const MemberExpr *E);
2802 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2803 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00002804 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00002805 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002806 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2807 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00002808 bool VisitUnaryReal(const UnaryOperator *E);
2809 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002810
Peter Collingbournee9200682011-05-13 03:29:01 +00002811 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002812 switch (E->getCastKind()) {
2813 default:
Richard Smith027bf112011-11-17 22:56:20 +00002814 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002815
Eli Friedmance3e02a2011-10-11 00:13:24 +00002816 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002817 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002818 if (!Visit(E->getSubExpr()))
2819 return false;
2820 Result.Designator.setInvalid();
2821 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002822
Richard Smith027bf112011-11-17 22:56:20 +00002823 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002824 if (!Visit(E->getSubExpr()))
2825 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002826 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002827 }
2828 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002829};
2830} // end anonymous namespace
2831
Richard Smith11562c52011-10-28 17:51:58 +00002832/// Evaluate an expression as an lvalue. This can be legitimately called on
2833/// expressions which are not glvalues, in a few cases:
2834/// * function designators in C,
2835/// * "extern void" objects,
2836/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002837static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002838 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2839 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2840 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002841 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002842}
2843
Peter Collingbournee9200682011-05-13 03:29:01 +00002844bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002845 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2846 return Success(FD);
2847 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002848 return VisitVarDecl(E, VD);
2849 return Error(E);
2850}
Richard Smith733237d2011-10-24 23:14:33 +00002851
Richard Smith11562c52011-10-28 17:51:58 +00002852bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002853 if (!VD->getType()->isReferenceType()) {
2854 if (isa<ParmVarDecl>(VD)) {
Richard Smithb228a862012-02-15 02:18:13 +00002855 Result.set(VD, Info.CurrentCall->Index);
Richard Smithfec09922011-11-01 16:57:24 +00002856 return true;
2857 }
Richard Smithce40ad62011-11-12 22:28:03 +00002858 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002859 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002860
Richard Smith2e312c82012-03-03 22:46:17 +00002861 APValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002862 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2863 return false;
2864 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002865}
2866
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002867bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2868 const MaterializeTemporaryExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002869 if (E->GetTemporaryExpr()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002870 if (E->getType()->isRecordType())
Richard Smith027bf112011-11-17 22:56:20 +00002871 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
2872
Richard Smithb228a862012-02-15 02:18:13 +00002873 Result.set(E, Info.CurrentCall->Index);
2874 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2875 Result, E->GetTemporaryExpr());
Richard Smith027bf112011-11-17 22:56:20 +00002876 }
2877
2878 // Materialization of an lvalue temporary occurs when we need to force a copy
2879 // (for instance, if it's a bitfield).
2880 // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
2881 if (!Visit(E->GetTemporaryExpr()))
2882 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002883 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002884 Info.CurrentCall->Temporaries[E]))
2885 return false;
Richard Smithb228a862012-02-15 02:18:13 +00002886 Result.set(E, Info.CurrentCall->Index);
Richard Smith027bf112011-11-17 22:56:20 +00002887 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002888}
2889
Peter Collingbournee9200682011-05-13 03:29:01 +00002890bool
2891LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002892 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2893 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2894 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002895 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002896}
2897
Richard Smith6e525142011-12-27 12:18:28 +00002898bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00002899 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00002900 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00002901
2902 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
2903 << E->getExprOperand()->getType()
2904 << E->getExprOperand()->getSourceRange();
2905 return false;
Richard Smith6e525142011-12-27 12:18:28 +00002906}
2907
Francois Pichet0066db92012-04-16 04:08:35 +00002908bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2909 return Success(E);
2910}
2911
Peter Collingbournee9200682011-05-13 03:29:01 +00002912bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002913 // Handle static data members.
2914 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2915 VisitIgnoredValue(E->getBase());
2916 return VisitVarDecl(E, VD);
2917 }
2918
Richard Smith254a73d2011-10-28 22:34:42 +00002919 // Handle static member functions.
2920 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2921 if (MD->isStatic()) {
2922 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002923 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002924 }
2925 }
2926
Richard Smithd62306a2011-11-10 06:34:14 +00002927 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002928 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002929}
2930
Peter Collingbournee9200682011-05-13 03:29:01 +00002931bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002932 // FIXME: Deal with vectors as array subscript bases.
2933 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002934 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002935
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002936 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002937 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002938
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002939 APSInt Index;
2940 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002941 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002942 int64_t IndexValue
2943 = Index.isSigned() ? Index.getSExtValue()
2944 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002945
Richard Smitha8105bc2012-01-06 16:39:00 +00002946 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002947}
Eli Friedman9a156e52008-11-12 09:44:48 +00002948
Peter Collingbournee9200682011-05-13 03:29:01 +00002949bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00002950 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002951}
2952
Richard Smith66c96992012-02-18 22:04:06 +00002953bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2954 if (!Visit(E->getSubExpr()))
2955 return false;
2956 // __real is a no-op on scalar lvalues.
2957 if (E->getSubExpr()->getType()->isAnyComplexType())
2958 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
2959 return true;
2960}
2961
2962bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
2963 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
2964 "lvalue __imag__ on scalar?");
2965 if (!Visit(E->getSubExpr()))
2966 return false;
2967 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
2968 return true;
2969}
2970
Eli Friedman9a156e52008-11-12 09:44:48 +00002971//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002972// Pointer Evaluation
2973//===----------------------------------------------------------------------===//
2974
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002975namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002976class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002977 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002978 LValue &Result;
2979
Peter Collingbournee9200682011-05-13 03:29:01 +00002980 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002981 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002982 return true;
2983 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002984public:
Mike Stump11289f42009-09-09 15:08:12 +00002985
John McCall45d55e42010-05-07 21:00:08 +00002986 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002987 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002988
Richard Smith2e312c82012-03-03 22:46:17 +00002989 bool Success(const APValue &V, const Expr *E) {
2990 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00002991 return true;
2992 }
Richard Smithfddd3842011-12-30 21:15:51 +00002993 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002994 return Success((Expr*)0);
2995 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002996
John McCall45d55e42010-05-07 21:00:08 +00002997 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002998 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00002999 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003000 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00003001 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00003002 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00003003 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003004 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00003005 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003006 bool VisitCallExpr(const CallExpr *E);
3007 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00003008 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00003009 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003010 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00003011 }
Richard Smithd62306a2011-11-10 06:34:14 +00003012 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3013 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003014 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003015 Result = *Info.CurrentCall->This;
3016 return true;
3017 }
John McCallc07a0c72011-02-17 10:25:35 +00003018
Eli Friedman449fe542009-03-23 04:56:01 +00003019 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003020};
Chris Lattner05706e882008-07-11 18:11:29 +00003021} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003022
John McCall45d55e42010-05-07 21:00:08 +00003023static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003024 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00003025 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00003026}
3027
John McCall45d55e42010-05-07 21:00:08 +00003028bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003029 if (E->getOpcode() != BO_Add &&
3030 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00003031 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00003032
Chris Lattner05706e882008-07-11 18:11:29 +00003033 const Expr *PExp = E->getLHS();
3034 const Expr *IExp = E->getRHS();
3035 if (IExp->getType()->isPointerType())
3036 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00003037
Richard Smith253c2a32012-01-27 01:14:48 +00003038 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3039 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00003040 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003041
John McCall45d55e42010-05-07 21:00:08 +00003042 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00003043 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00003044 return false;
3045 int64_t AdditionalOffset
3046 = Offset.isSigned() ? Offset.getSExtValue()
3047 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00003048 if (E->getOpcode() == BO_Sub)
3049 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00003050
Ted Kremenek28831752012-08-23 20:46:57 +00003051 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00003052 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3053 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00003054}
Eli Friedman9a156e52008-11-12 09:44:48 +00003055
John McCall45d55e42010-05-07 21:00:08 +00003056bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3057 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003058}
Mike Stump11289f42009-09-09 15:08:12 +00003059
Peter Collingbournee9200682011-05-13 03:29:01 +00003060bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3061 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00003062
Eli Friedman847a2bc2009-12-27 05:43:15 +00003063 switch (E->getCastKind()) {
3064 default:
3065 break;
3066
John McCalle3027922010-08-25 11:45:40 +00003067 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003068 case CK_CPointerToObjCPointerCast:
3069 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00003070 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00003071 if (!Visit(SubExpr))
3072 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00003073 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3074 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3075 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00003076 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00003077 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00003078 if (SubExpr->getType()->isVoidPointerType())
3079 CCEDiag(E, diag::note_constexpr_invalid_cast)
3080 << 3 << SubExpr->getType();
3081 else
3082 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3083 }
Richard Smith96e0c102011-11-04 02:25:55 +00003084 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00003085
Anders Carlsson18275092010-10-31 20:41:46 +00003086 case CK_DerivedToBase:
3087 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003088 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00003089 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003090 if (!Result.Base && Result.Offset.isZero())
3091 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00003092
Richard Smithd62306a2011-11-10 06:34:14 +00003093 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00003094 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00003095 QualType Type =
3096 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00003097
Richard Smithd62306a2011-11-10 06:34:14 +00003098 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00003099 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003100 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3101 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00003102 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003103 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00003104 }
3105
Anders Carlsson18275092010-10-31 20:41:46 +00003106 return true;
3107 }
3108
Richard Smith027bf112011-11-17 22:56:20 +00003109 case CK_BaseToDerived:
3110 if (!Visit(E->getSubExpr()))
3111 return false;
3112 if (!Result.Base && Result.Offset.isZero())
3113 return true;
3114 return HandleBaseToDerivedCast(Info, E, Result);
3115
Richard Smith0b0a0b62011-10-29 20:57:55 +00003116 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003117 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003118 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00003119
John McCalle3027922010-08-25 11:45:40 +00003120 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003121 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3122
Richard Smith2e312c82012-03-03 22:46:17 +00003123 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00003124 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00003125 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00003126
John McCall45d55e42010-05-07 21:00:08 +00003127 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003128 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3129 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00003130 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003131 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00003132 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00003133 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00003134 return true;
3135 } else {
3136 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00003137 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00003138 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00003139 }
3140 }
John McCalle3027922010-08-25 11:45:40 +00003141 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00003142 if (SubExpr->isGLValue()) {
3143 if (!EvaluateLValue(SubExpr, Result, Info))
3144 return false;
3145 } else {
Richard Smithb228a862012-02-15 02:18:13 +00003146 Result.set(SubExpr, Info.CurrentCall->Index);
3147 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3148 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00003149 return false;
3150 }
Richard Smith96e0c102011-11-04 02:25:55 +00003151 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00003152 if (const ConstantArrayType *CAT
3153 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3154 Result.addArray(Info, E, CAT);
3155 else
3156 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00003157 return true;
Richard Smithdd785442011-10-31 20:57:44 +00003158
John McCalle3027922010-08-25 11:45:40 +00003159 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00003160 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003161 }
3162
Richard Smith11562c52011-10-28 17:51:58 +00003163 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00003164}
Chris Lattner05706e882008-07-11 18:11:29 +00003165
Peter Collingbournee9200682011-05-13 03:29:01 +00003166bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003167 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00003168 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00003169
Peter Collingbournee9200682011-05-13 03:29:01 +00003170 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003171}
Chris Lattner05706e882008-07-11 18:11:29 +00003172
3173//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003174// Member Pointer Evaluation
3175//===----------------------------------------------------------------------===//
3176
3177namespace {
3178class MemberPointerExprEvaluator
3179 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3180 MemberPtr &Result;
3181
3182 bool Success(const ValueDecl *D) {
3183 Result = MemberPtr(D);
3184 return true;
3185 }
3186public:
3187
3188 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3189 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3190
Richard Smith2e312c82012-03-03 22:46:17 +00003191 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003192 Result.setFrom(V);
3193 return true;
3194 }
Richard Smithfddd3842011-12-30 21:15:51 +00003195 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003196 return Success((const ValueDecl*)0);
3197 }
3198
3199 bool VisitCastExpr(const CastExpr *E);
3200 bool VisitUnaryAddrOf(const UnaryOperator *E);
3201};
3202} // end anonymous namespace
3203
3204static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3205 EvalInfo &Info) {
3206 assert(E->isRValue() && E->getType()->isMemberPointerType());
3207 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3208}
3209
3210bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3211 switch (E->getCastKind()) {
3212 default:
3213 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3214
3215 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003216 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003217 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003218
3219 case CK_BaseToDerivedMemberPointer: {
3220 if (!Visit(E->getSubExpr()))
3221 return false;
3222 if (E->path_empty())
3223 return true;
3224 // Base-to-derived member pointer casts store the path in derived-to-base
3225 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3226 // the wrong end of the derived->base arc, so stagger the path by one class.
3227 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3228 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3229 PathI != PathE; ++PathI) {
3230 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3231 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3232 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003233 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003234 }
3235 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3236 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003237 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003238 return true;
3239 }
3240
3241 case CK_DerivedToBaseMemberPointer:
3242 if (!Visit(E->getSubExpr()))
3243 return false;
3244 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3245 PathE = E->path_end(); PathI != PathE; ++PathI) {
3246 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3247 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3248 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003249 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003250 }
3251 return true;
3252 }
3253}
3254
3255bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3256 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3257 // member can be formed.
3258 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3259}
3260
3261//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00003262// Record Evaluation
3263//===----------------------------------------------------------------------===//
3264
3265namespace {
3266 class RecordExprEvaluator
3267 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3268 const LValue &This;
3269 APValue &Result;
3270 public:
3271
3272 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3273 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3274
Richard Smith2e312c82012-03-03 22:46:17 +00003275 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003276 Result = V;
3277 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00003278 }
Richard Smithfddd3842011-12-30 21:15:51 +00003279 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003280
Richard Smithe97cbd72011-11-11 04:05:33 +00003281 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003282 bool VisitInitListExpr(const InitListExpr *E);
3283 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3284 };
3285}
3286
Richard Smithfddd3842011-12-30 21:15:51 +00003287/// Perform zero-initialization on an object of non-union class type.
3288/// C++11 [dcl.init]p5:
3289/// To zero-initialize an object or reference of type T means:
3290/// [...]
3291/// -- if T is a (possibly cv-qualified) non-union class type,
3292/// each non-static data member and each base-class subobject is
3293/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00003294static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3295 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00003296 const LValue &This, APValue &Result) {
3297 assert(!RD->isUnion() && "Expected non-union class type");
3298 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3299 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3300 std::distance(RD->field_begin(), RD->field_end()));
3301
John McCalld7bca762012-05-01 00:38:49 +00003302 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003303 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3304
3305 if (CD) {
3306 unsigned Index = 0;
3307 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003308 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00003309 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3310 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00003311 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3312 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003313 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00003314 Result.getStructBase(Index)))
3315 return false;
3316 }
3317 }
3318
Richard Smitha8105bc2012-01-06 16:39:00 +00003319 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3320 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00003321 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00003322 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00003323 continue;
3324
3325 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00003326 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003327 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003328
David Blaikie2d7c57e2012-04-30 02:36:29 +00003329 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00003330 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00003331 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00003332 return false;
3333 }
3334
3335 return true;
3336}
3337
3338bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3339 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00003340 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003341 if (RD->isUnion()) {
3342 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3343 // object's first non-static named data member is zero-initialized
3344 RecordDecl::field_iterator I = RD->field_begin();
3345 if (I == RD->field_end()) {
3346 Result = APValue((const FieldDecl*)0);
3347 return true;
3348 }
3349
3350 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00003351 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00003352 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00003353 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00003354 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00003355 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00003356 }
3357
Richard Smith5d108602012-02-17 00:44:16 +00003358 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003359 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00003360 return false;
3361 }
3362
Richard Smitha8105bc2012-01-06 16:39:00 +00003363 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00003364}
3365
Richard Smithe97cbd72011-11-11 04:05:33 +00003366bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3367 switch (E->getCastKind()) {
3368 default:
3369 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3370
3371 case CK_ConstructorConversion:
3372 return Visit(E->getSubExpr());
3373
3374 case CK_DerivedToBase:
3375 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00003376 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003377 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00003378 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003379 if (!DerivedObject.isStruct())
3380 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00003381
3382 // Derived-to-base rvalue conversion: just slice off the derived part.
3383 APValue *Value = &DerivedObject;
3384 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3385 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3386 PathE = E->path_end(); PathI != PathE; ++PathI) {
3387 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3388 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3389 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3390 RD = Base;
3391 }
3392 Result = *Value;
3393 return true;
3394 }
3395 }
3396}
3397
Richard Smithd62306a2011-11-10 06:34:14 +00003398bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00003399 // Cannot constant-evaluate std::initializer_list inits.
3400 if (E->initializesStdInitializerList())
3401 return false;
3402
Richard Smithd62306a2011-11-10 06:34:14 +00003403 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00003404 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003405 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3406
3407 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00003408 const FieldDecl *Field = E->getInitializedFieldInUnion();
3409 Result = APValue(Field);
3410 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00003411 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00003412
3413 // If the initializer list for a union does not contain any elements, the
3414 // first element of the union is value-initialized.
3415 ImplicitValueInitExpr VIE(Field->getType());
3416 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3417
Richard Smithd62306a2011-11-10 06:34:14 +00003418 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00003419 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3420 return false;
Richard Smithb228a862012-02-15 02:18:13 +00003421 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00003422 }
3423
3424 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3425 "initializer list for class with base classes");
3426 Result = APValue(APValue::UninitStruct(), 0,
3427 std::distance(RD->field_begin(), RD->field_end()));
3428 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00003429 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003430 for (RecordDecl::field_iterator Field = RD->field_begin(),
3431 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3432 // Anonymous bit-fields are not considered members of the class for
3433 // purposes of aggregate initialization.
3434 if (Field->isUnnamedBitfield())
3435 continue;
3436
3437 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00003438
Richard Smith253c2a32012-01-27 01:14:48 +00003439 bool HaveInit = ElementNo < E->getNumInits();
3440
3441 // FIXME: Diagnostics here should point to the end of the initializer
3442 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00003443 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00003444 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003445 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003446
3447 // Perform an implicit value-initialization for members beyond the end of
3448 // the initializer list.
3449 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
3450
Richard Smithb228a862012-02-15 02:18:13 +00003451 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00003452 Result.getStructField(Field->getFieldIndex()),
Richard Smith253c2a32012-01-27 01:14:48 +00003453 Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
3454 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00003455 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003456 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00003457 }
3458 }
3459
Richard Smith253c2a32012-01-27 01:14:48 +00003460 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003461}
3462
3463bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3464 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00003465 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3466
Richard Smithfddd3842011-12-30 21:15:51 +00003467 bool ZeroInit = E->requiresZeroInitialization();
3468 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00003469 // If we've already performed zero-initialization, we're already done.
3470 if (!Result.isUninit())
3471 return true;
3472
Richard Smithfddd3842011-12-30 21:15:51 +00003473 if (ZeroInit)
3474 return ZeroInitialization(E);
3475
Richard Smithcc36f692011-12-22 02:22:31 +00003476 const CXXRecordDecl *RD = FD->getParent();
3477 if (RD->isUnion())
3478 Result = APValue((FieldDecl*)0);
3479 else
3480 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3481 std::distance(RD->field_begin(), RD->field_end()));
3482 return true;
3483 }
3484
Richard Smithd62306a2011-11-10 06:34:14 +00003485 const FunctionDecl *Definition = 0;
3486 FD->getBody(Definition);
3487
Richard Smith357362d2011-12-13 06:39:58 +00003488 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3489 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003490
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003491 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00003492 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00003493 if (const MaterializeTemporaryExpr *ME
3494 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3495 return Visit(ME->GetTemporaryExpr());
3496
Richard Smithfddd3842011-12-30 21:15:51 +00003497 if (ZeroInit && !ZeroInitialization(E))
3498 return false;
3499
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003500 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00003501 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003502 cast<CXXConstructorDecl>(Definition), Info,
3503 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00003504}
3505
3506static bool EvaluateRecord(const Expr *E, const LValue &This,
3507 APValue &Result, EvalInfo &Info) {
3508 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00003509 "can't evaluate expression as a record rvalue");
3510 return RecordExprEvaluator(Info, This, Result).Visit(E);
3511}
3512
3513//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003514// Temporary Evaluation
3515//
3516// Temporaries are represented in the AST as rvalues, but generally behave like
3517// lvalues. The full-object of which the temporary is a subobject is implicitly
3518// materialized so that a reference can bind to it.
3519//===----------------------------------------------------------------------===//
3520namespace {
3521class TemporaryExprEvaluator
3522 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3523public:
3524 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3525 LValueExprEvaluatorBaseTy(Info, Result) {}
3526
3527 /// Visit an expression which constructs the value of this temporary.
3528 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003529 Result.set(E, Info.CurrentCall->Index);
3530 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00003531 }
3532
3533 bool VisitCastExpr(const CastExpr *E) {
3534 switch (E->getCastKind()) {
3535 default:
3536 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3537
3538 case CK_ConstructorConversion:
3539 return VisitConstructExpr(E->getSubExpr());
3540 }
3541 }
3542 bool VisitInitListExpr(const InitListExpr *E) {
3543 return VisitConstructExpr(E);
3544 }
3545 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3546 return VisitConstructExpr(E);
3547 }
3548 bool VisitCallExpr(const CallExpr *E) {
3549 return VisitConstructExpr(E);
3550 }
3551};
3552} // end anonymous namespace
3553
3554/// Evaluate an expression of record type as a temporary.
3555static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003556 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00003557 return TemporaryExprEvaluator(Info, Result).Visit(E);
3558}
3559
3560//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003561// Vector Evaluation
3562//===----------------------------------------------------------------------===//
3563
3564namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003565 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00003566 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3567 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003568 public:
Mike Stump11289f42009-09-09 15:08:12 +00003569
Richard Smith2d406342011-10-22 21:10:00 +00003570 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3571 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003572
Richard Smith2d406342011-10-22 21:10:00 +00003573 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3574 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3575 // FIXME: remove this APValue copy.
3576 Result = APValue(V.data(), V.size());
3577 return true;
3578 }
Richard Smith2e312c82012-03-03 22:46:17 +00003579 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00003580 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00003581 Result = V;
3582 return true;
3583 }
Richard Smithfddd3842011-12-30 21:15:51 +00003584 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003585
Richard Smith2d406342011-10-22 21:10:00 +00003586 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00003587 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00003588 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00003589 bool VisitInitListExpr(const InitListExpr *E);
3590 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003591 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00003592 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00003593 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003594 };
3595} // end anonymous namespace
3596
3597static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003598 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00003599 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003600}
3601
Richard Smith2d406342011-10-22 21:10:00 +00003602bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3603 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003604 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003605
Richard Smith161f09a2011-12-06 22:44:34 +00003606 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00003607 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003608
Eli Friedmanc757de22011-03-25 00:43:55 +00003609 switch (E->getCastKind()) {
3610 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00003611 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00003612 if (SETy->isIntegerType()) {
3613 APSInt IntResult;
3614 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003615 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003616 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00003617 } else if (SETy->isRealFloatingType()) {
3618 APFloat F(0.0);
3619 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003620 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003621 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00003622 } else {
Richard Smith2d406342011-10-22 21:10:00 +00003623 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003624 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003625
3626 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00003627 SmallVector<APValue, 4> Elts(NElts, Val);
3628 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00003629 }
Eli Friedman803acb32011-12-22 03:51:45 +00003630 case CK_BitCast: {
3631 // Evaluate the operand into an APInt we can extract from.
3632 llvm::APInt SValInt;
3633 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3634 return false;
3635 // Extract the elements
3636 QualType EltTy = VTy->getElementType();
3637 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3638 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3639 SmallVector<APValue, 4> Elts;
3640 if (EltTy->isRealFloatingType()) {
3641 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00003642 unsigned FloatEltSize = EltSize;
3643 if (&Sem == &APFloat::x87DoubleExtended)
3644 FloatEltSize = 80;
3645 for (unsigned i = 0; i < NElts; i++) {
3646 llvm::APInt Elt;
3647 if (BigEndian)
3648 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3649 else
3650 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00003651 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00003652 }
3653 } else if (EltTy->isIntegerType()) {
3654 for (unsigned i = 0; i < NElts; i++) {
3655 llvm::APInt Elt;
3656 if (BigEndian)
3657 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3658 else
3659 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3660 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3661 }
3662 } else {
3663 return Error(E);
3664 }
3665 return Success(Elts, E);
3666 }
Eli Friedmanc757de22011-03-25 00:43:55 +00003667 default:
Richard Smith11562c52011-10-28 17:51:58 +00003668 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003669 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003670}
3671
Richard Smith2d406342011-10-22 21:10:00 +00003672bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003673VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003674 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003675 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00003676 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003677
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003678 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003679 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003680
Eli Friedmanb9c71292012-01-03 23:24:20 +00003681 // The number of initializers can be less than the number of
3682 // vector elements. For OpenCL, this can be due to nested vector
3683 // initialization. For GCC compatibility, missing trailing elements
3684 // should be initialized with zeroes.
3685 unsigned CountInits = 0, CountElts = 0;
3686 while (CountElts < NumElements) {
3687 // Handle nested vector initialization.
3688 if (CountInits < NumInits
3689 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3690 APValue v;
3691 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3692 return Error(E);
3693 unsigned vlen = v.getVectorLength();
3694 for (unsigned j = 0; j < vlen; j++)
3695 Elements.push_back(v.getVectorElt(j));
3696 CountElts += vlen;
3697 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003698 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003699 if (CountInits < NumInits) {
3700 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00003701 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00003702 } else // trailing integer zero.
3703 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3704 Elements.push_back(APValue(sInt));
3705 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003706 } else {
3707 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003708 if (CountInits < NumInits) {
3709 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00003710 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00003711 } else // trailing float zero.
3712 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3713 Elements.push_back(APValue(f));
3714 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00003715 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00003716 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003717 }
Richard Smith2d406342011-10-22 21:10:00 +00003718 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003719}
3720
Richard Smith2d406342011-10-22 21:10:00 +00003721bool
Richard Smithfddd3842011-12-30 21:15:51 +00003722VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003723 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00003724 QualType EltTy = VT->getElementType();
3725 APValue ZeroElement;
3726 if (EltTy->isIntegerType())
3727 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3728 else
3729 ZeroElement =
3730 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3731
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003732 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00003733 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003734}
3735
Richard Smith2d406342011-10-22 21:10:00 +00003736bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00003737 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003738 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003739}
3740
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003741//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00003742// Array Evaluation
3743//===----------------------------------------------------------------------===//
3744
3745namespace {
3746 class ArrayExprEvaluator
3747 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00003748 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00003749 APValue &Result;
3750 public:
3751
Richard Smithd62306a2011-11-10 06:34:14 +00003752 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3753 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00003754
3755 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00003756 assert((V.isArray() || V.isLValue()) &&
3757 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00003758 Result = V;
3759 return true;
3760 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003761
Richard Smithfddd3842011-12-30 21:15:51 +00003762 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003763 const ConstantArrayType *CAT =
3764 Info.Ctx.getAsConstantArrayType(E->getType());
3765 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003766 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003767
3768 Result = APValue(APValue::UninitArray(), 0,
3769 CAT->getSize().getZExtValue());
3770 if (!Result.hasArrayFiller()) return true;
3771
Richard Smithfddd3842011-12-30 21:15:51 +00003772 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00003773 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003774 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00003775 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00003776 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00003777 }
3778
Richard Smithf3e9e432011-11-07 09:22:26 +00003779 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00003780 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003781 };
3782} // end anonymous namespace
3783
Richard Smithd62306a2011-11-10 06:34:14 +00003784static bool EvaluateArray(const Expr *E, const LValue &This,
3785 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00003786 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00003787 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003788}
3789
3790bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3791 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3792 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003793 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003794
Richard Smithca2cfbf2011-12-22 01:07:19 +00003795 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3796 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00003797 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00003798 LValue LV;
3799 if (!EvaluateLValue(E->getInit(0), LV, Info))
3800 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003801 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00003802 LV.moveInto(Val);
3803 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00003804 }
3805
Richard Smith253c2a32012-01-27 01:14:48 +00003806 bool Success = true;
3807
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003808 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
3809 "zero-initialized array shouldn't have any initialized elts");
3810 APValue Filler;
3811 if (Result.isArray() && Result.hasArrayFiller())
3812 Filler = Result.getArrayFiller();
3813
Richard Smithf3e9e432011-11-07 09:22:26 +00003814 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3815 CAT->getSize().getZExtValue());
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003816
3817 // If the array was previously zero-initialized, preserve the
3818 // zero-initialized values.
3819 if (!Filler.isUninit()) {
3820 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
3821 Result.getArrayInitializedElt(I) = Filler;
3822 if (Result.hasArrayFiller())
3823 Result.getArrayFiller() = Filler;
3824 }
3825
Richard Smithd62306a2011-11-10 06:34:14 +00003826 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003827 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00003828 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00003829 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00003830 I != End; ++I, ++Index) {
Richard Smithb228a862012-02-15 02:18:13 +00003831 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3832 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003833 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3834 CAT->getElementType(), 1)) {
3835 if (!Info.keepEvaluatingAfterFailure())
3836 return false;
3837 Success = false;
3838 }
Richard Smithd62306a2011-11-10 06:34:14 +00003839 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003840
Richard Smith253c2a32012-01-27 01:14:48 +00003841 if (!Result.hasArrayFiller()) return Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00003842 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003843 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3844 // but sometimes does:
3845 // struct S { constexpr S() : p(&p) {} void *p; };
3846 // S s[10] = {};
Richard Smithb228a862012-02-15 02:18:13 +00003847 return EvaluateInPlace(Result.getArrayFiller(), Info,
3848 Subobject, E->getArrayFiller()) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00003849}
3850
Richard Smith027bf112011-11-17 22:56:20 +00003851bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003852 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3853 // but sometimes does:
3854 // struct S { constexpr S() : p(&p) {} void *p; };
3855 // S s[10];
3856 LValue Subobject = This;
3857
3858 APValue *Value = &Result;
3859 bool HadZeroInit = true;
Richard Smith9fce7bc2012-07-10 22:12:55 +00003860 QualType ElemTy = E->getType();
3861 while (const ConstantArrayType *CAT =
3862 Info.Ctx.getAsConstantArrayType(ElemTy)) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003863 Subobject.addArray(Info, E, CAT);
3864 HadZeroInit &= !Value->isUninit();
3865 if (!HadZeroInit)
3866 *Value = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3867 if (!Value->hasArrayFiller())
3868 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003869 Value = &Value->getArrayFiller();
Richard Smith9fce7bc2012-07-10 22:12:55 +00003870 ElemTy = CAT->getElementType();
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003871 }
Richard Smith027bf112011-11-17 22:56:20 +00003872
Richard Smith9fce7bc2012-07-10 22:12:55 +00003873 if (!ElemTy->isRecordType())
3874 return Error(E);
3875
Richard Smith027bf112011-11-17 22:56:20 +00003876 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00003877
Richard Smithfddd3842011-12-30 21:15:51 +00003878 bool ZeroInit = E->requiresZeroInitialization();
3879 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00003880 if (HadZeroInit)
3881 return true;
3882
Richard Smithfddd3842011-12-30 21:15:51 +00003883 if (ZeroInit) {
Richard Smith9fce7bc2012-07-10 22:12:55 +00003884 ImplicitValueInitExpr VIE(ElemTy);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003885 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00003886 }
3887
Richard Smithcc36f692011-12-22 02:22:31 +00003888 const CXXRecordDecl *RD = FD->getParent();
3889 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003890 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00003891 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003892 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00003893 APValue(APValue::UninitStruct(), RD->getNumBases(),
3894 std::distance(RD->field_begin(), RD->field_end()));
3895 return true;
3896 }
3897
Richard Smith027bf112011-11-17 22:56:20 +00003898 const FunctionDecl *Definition = 0;
3899 FD->getBody(Definition);
3900
Richard Smith357362d2011-12-13 06:39:58 +00003901 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3902 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003903
Richard Smith9eae7232012-01-12 18:54:33 +00003904 if (ZeroInit && !HadZeroInit) {
Richard Smith9fce7bc2012-07-10 22:12:55 +00003905 ImplicitValueInitExpr VIE(ElemTy);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003906 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00003907 return false;
3908 }
3909
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003910 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00003911 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003912 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003913 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00003914}
3915
Richard Smithf3e9e432011-11-07 09:22:26 +00003916//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003917// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003918//
3919// As a GNU extension, we support casting pointers to sufficiently-wide integer
3920// types and back in constant folding. Integer values are thus represented
3921// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003922//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003923
3924namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003925class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003926 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00003927 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003928public:
Richard Smith2e312c82012-03-03 22:46:17 +00003929 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003930 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003931
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003932 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003933 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003934 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003935 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003936 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003937 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003938 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00003939 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003940 return true;
3941 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003942 bool Success(const llvm::APSInt &SI, const Expr *E) {
3943 return Success(SI, E, Result);
3944 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003945
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003946 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003947 assert(E->getType()->isIntegralOrEnumerationType() &&
3948 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003949 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003950 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00003951 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003952 Result.getInt().setIsUnsigned(
3953 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003954 return true;
3955 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003956 bool Success(const llvm::APInt &I, const Expr *E) {
3957 return Success(I, E, Result);
3958 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003959
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003960 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003961 assert(E->getType()->isIntegralOrEnumerationType() &&
3962 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00003963 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003964 return true;
3965 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003966 bool Success(uint64_t Value, const Expr *E) {
3967 return Success(Value, E, Result);
3968 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003969
Ken Dyckdbc01912011-03-11 02:13:43 +00003970 bool Success(CharUnits Size, const Expr *E) {
3971 return Success(Size.getQuantity(), E);
3972 }
3973
Richard Smith2e312c82012-03-03 22:46:17 +00003974 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00003975 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003976 Result = V;
3977 return true;
3978 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003979 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003980 }
Mike Stump11289f42009-09-09 15:08:12 +00003981
Richard Smithfddd3842011-12-30 21:15:51 +00003982 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00003983
Peter Collingbournee9200682011-05-13 03:29:01 +00003984 //===--------------------------------------------------------------------===//
3985 // Visitor Methods
3986 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003987
Chris Lattner7174bf32008-07-12 00:38:25 +00003988 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003989 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003990 }
3991 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003992 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00003993 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00003994
3995 bool CheckReferencedDecl(const Expr *E, const Decl *D);
3996 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003997 if (CheckReferencedDecl(E, E->getDecl()))
3998 return true;
3999
4000 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004001 }
4002 bool VisitMemberExpr(const MemberExpr *E) {
4003 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00004004 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004005 return true;
4006 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004007
4008 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004009 }
4010
Peter Collingbournee9200682011-05-13 03:29:01 +00004011 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004012 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00004013 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004014 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00004015
Peter Collingbournee9200682011-05-13 03:29:01 +00004016 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004017 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00004018
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004019 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004020 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004021 }
Mike Stump11289f42009-09-09 15:08:12 +00004022
Ted Kremeneke65b0862012-03-06 20:05:56 +00004023 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4024 return Success(E->getValue(), E);
4025 }
4026
Richard Smith4ce706a2011-10-11 21:43:33 +00004027 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00004028 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004029 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004030 }
4031
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004032 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004033 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004034 }
4035
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004036 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4037 return Success(E->getValue(), E);
4038 }
4039
Douglas Gregor29c42f22012-02-24 07:38:34 +00004040 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4041 return Success(E->getValue(), E);
4042 }
4043
John Wiegley6242b6a2011-04-28 00:16:57 +00004044 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4045 return Success(E->getValue(), E);
4046 }
4047
John Wiegleyf9f65842011-04-25 06:54:41 +00004048 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4049 return Success(E->getValue(), E);
4050 }
4051
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004052 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004053 bool VisitUnaryImag(const UnaryOperator *E);
4054
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004055 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004056 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004057
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004058private:
Ken Dyck160146e2010-01-27 17:10:57 +00004059 CharUnits GetAlignOfExpr(const Expr *E);
4060 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00004061 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00004062 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004063 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00004064};
Chris Lattner05706e882008-07-11 18:11:29 +00004065} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004066
Richard Smith11562c52011-10-28 17:51:58 +00004067/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4068/// produce either the integer value or a pointer.
4069///
4070/// GCC has a heinous extension which folds casts between pointer types and
4071/// pointer-sized integral types. We support this by allowing the evaluation of
4072/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4073/// Some simple arithmetic on such values is supported (they are treated much
4074/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00004075static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00004076 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004077 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004078 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00004079}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004080
Richard Smithf57d8cb2011-12-09 22:58:01 +00004081static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00004082 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004083 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00004084 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004085 if (!Val.isInt()) {
4086 // FIXME: It would be better to produce the diagnostic for casting
4087 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00004088 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004089 return false;
4090 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004091 Result = Val.getInt();
4092 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004093}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004094
Richard Smithf57d8cb2011-12-09 22:58:01 +00004095/// Check whether the given declaration can be directly converted to an integral
4096/// rvalue. If not, no diagnostic is produced; there are other things we can
4097/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004098bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00004099 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004100 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004101 // Check for signedness/width mismatches between E type and ECD value.
4102 bool SameSign = (ECD->getInitVal().isSigned()
4103 == E->getType()->isSignedIntegerOrEnumerationType());
4104 bool SameWidth = (ECD->getInitVal().getBitWidth()
4105 == Info.Ctx.getIntWidth(E->getType()));
4106 if (SameSign && SameWidth)
4107 return Success(ECD->getInitVal(), E);
4108 else {
4109 // Get rid of mismatch (otherwise Success assertions will fail)
4110 // by computing a new value matching the type of E.
4111 llvm::APSInt Val = ECD->getInitVal();
4112 if (!SameSign)
4113 Val.setIsSigned(!ECD->getInitVal().isSigned());
4114 if (!SameWidth)
4115 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4116 return Success(Val, E);
4117 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004118 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004119 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00004120}
4121
Chris Lattner86ee2862008-10-06 06:40:35 +00004122/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4123/// as GCC.
4124static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4125 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004126 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00004127 enum gcc_type_class {
4128 no_type_class = -1,
4129 void_type_class, integer_type_class, char_type_class,
4130 enumeral_type_class, boolean_type_class,
4131 pointer_type_class, reference_type_class, offset_type_class,
4132 real_type_class, complex_type_class,
4133 function_type_class, method_type_class,
4134 record_type_class, union_type_class,
4135 array_type_class, string_type_class,
4136 lang_type_class
4137 };
Mike Stump11289f42009-09-09 15:08:12 +00004138
4139 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00004140 // ideal, however it is what gcc does.
4141 if (E->getNumArgs() == 0)
4142 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00004143
Chris Lattner86ee2862008-10-06 06:40:35 +00004144 QualType ArgTy = E->getArg(0)->getType();
4145 if (ArgTy->isVoidType())
4146 return void_type_class;
4147 else if (ArgTy->isEnumeralType())
4148 return enumeral_type_class;
4149 else if (ArgTy->isBooleanType())
4150 return boolean_type_class;
4151 else if (ArgTy->isCharType())
4152 return string_type_class; // gcc doesn't appear to use char_type_class
4153 else if (ArgTy->isIntegerType())
4154 return integer_type_class;
4155 else if (ArgTy->isPointerType())
4156 return pointer_type_class;
4157 else if (ArgTy->isReferenceType())
4158 return reference_type_class;
4159 else if (ArgTy->isRealType())
4160 return real_type_class;
4161 else if (ArgTy->isComplexType())
4162 return complex_type_class;
4163 else if (ArgTy->isFunctionType())
4164 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00004165 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00004166 return record_type_class;
4167 else if (ArgTy->isUnionType())
4168 return union_type_class;
4169 else if (ArgTy->isArrayType())
4170 return array_type_class;
4171 else if (ArgTy->isUnionType())
4172 return union_type_class;
4173 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00004174 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00004175}
4176
Richard Smith5fab0c92011-12-28 19:48:30 +00004177/// EvaluateBuiltinConstantPForLValue - Determine the result of
4178/// __builtin_constant_p when applied to the given lvalue.
4179///
4180/// An lvalue is only "constant" if it is a pointer or reference to the first
4181/// character of a string literal.
4182template<typename LValue>
4183static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00004184 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00004185 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4186}
4187
4188/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4189/// GCC as we can manage.
4190static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4191 QualType ArgType = Arg->getType();
4192
4193 // __builtin_constant_p always has one operand. The rules which gcc follows
4194 // are not precisely documented, but are as follows:
4195 //
4196 // - If the operand is of integral, floating, complex or enumeration type,
4197 // and can be folded to a known value of that type, it returns 1.
4198 // - If the operand and can be folded to a pointer to the first character
4199 // of a string literal (or such a pointer cast to an integral type), it
4200 // returns 1.
4201 //
4202 // Otherwise, it returns 0.
4203 //
4204 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4205 // its support for this does not currently work.
4206 if (ArgType->isIntegralOrEnumerationType()) {
4207 Expr::EvalResult Result;
4208 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4209 return false;
4210
4211 APValue &V = Result.Val;
4212 if (V.getKind() == APValue::Int)
4213 return true;
4214
4215 return EvaluateBuiltinConstantPForLValue(V);
4216 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4217 return Arg->isEvaluatable(Ctx);
4218 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4219 LValue LV;
4220 Expr::EvalStatus Status;
4221 EvalInfo Info(Ctx, Status);
4222 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4223 : EvaluatePointer(Arg, LV, Info)) &&
4224 !Status.HasSideEffects)
4225 return EvaluateBuiltinConstantPForLValue(LV);
4226 }
4227
4228 // Anything else isn't considered to be sufficiently constant.
4229 return false;
4230}
4231
John McCall95007602010-05-10 23:27:23 +00004232/// Retrieves the "underlying object type" of the given expression,
4233/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00004234QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4235 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4236 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00004237 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00004238 } else if (const Expr *E = B.get<const Expr*>()) {
4239 if (isa<CompoundLiteralExpr>(E))
4240 return E->getType();
John McCall95007602010-05-10 23:27:23 +00004241 }
4242
4243 return QualType();
4244}
4245
Peter Collingbournee9200682011-05-13 03:29:01 +00004246bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00004247 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00004248
4249 {
4250 // The operand of __builtin_object_size is never evaluated for side-effects.
4251 // If there are any, but we can determine the pointed-to object anyway, then
4252 // ignore the side-effects.
4253 SpeculativeEvaluationRAII SpeculativeEval(Info);
4254 if (!EvaluatePointer(E->getArg(0), Base, Info))
4255 return false;
4256 }
John McCall95007602010-05-10 23:27:23 +00004257
4258 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00004259 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00004260
Richard Smithce40ad62011-11-12 22:28:03 +00004261 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00004262 if (T.isNull() ||
4263 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00004264 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00004265 T->isVariablyModifiedType() ||
4266 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004267 return Error(E);
John McCall95007602010-05-10 23:27:23 +00004268
4269 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4270 CharUnits Offset = Base.getLValueOffset();
4271
4272 if (!Offset.isNegative() && Offset <= Size)
4273 Size -= Offset;
4274 else
4275 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00004276 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00004277}
4278
Peter Collingbournee9200682011-05-13 03:29:01 +00004279bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00004280 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004281 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00004282 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004283
4284 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00004285 if (TryEvaluateBuiltinObjectSize(E))
4286 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00004287
Richard Smith0421ce72012-08-07 04:16:51 +00004288 // If evaluating the argument has side-effects, we can't determine the size
4289 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4290 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00004291 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00004292 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00004293 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00004294 return Success(0, E);
4295 }
Mike Stump876387b2009-10-27 22:09:17 +00004296
Richard Smith01ade172012-05-23 04:13:20 +00004297 // Expression had no side effects, but we couldn't statically determine the
4298 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004299 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004300 }
4301
Benjamin Kramera801f4a2012-10-06 14:42:22 +00004302 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00004303 case Builtin::BI__builtin_bswap32:
4304 case Builtin::BI__builtin_bswap64: {
4305 APSInt Val;
4306 if (!EvaluateInteger(E->getArg(0), Val, Info))
4307 return false;
4308
4309 return Success(Val.byteSwap(), E);
4310 }
4311
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004312 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004313 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00004314
Richard Smith5fab0c92011-12-28 19:48:30 +00004315 case Builtin::BI__builtin_constant_p:
4316 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00004317
Chris Lattnerd545ad12009-09-23 06:06:36 +00004318 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00004319 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00004320 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00004321 return Success(Operand, E);
4322 }
Eli Friedmand5c93992010-02-13 00:10:10 +00004323
4324 case Builtin::BI__builtin_expect:
4325 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00004326
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004327 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00004328 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004329 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00004330 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00004331 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4332 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00004333 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00004334 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004335 case Builtin::BI__builtin_strlen:
4336 // As an extension, we support strlen() and __builtin_strlen() as constant
4337 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00004338 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004339 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4340 // The string literal may have embedded null characters. Find the first
4341 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004342 StringRef Str = S->getString();
4343 StringRef::size_type Pos = Str.find(0);
4344 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004345 Str = Str.substr(0, Pos);
4346
4347 return Success(Str.size(), E);
4348 }
4349
Richard Smithf57d8cb2011-12-09 22:58:01 +00004350 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004351
Richard Smith01ba47d2012-04-13 00:45:38 +00004352 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00004353 case Builtin::BI__atomic_is_lock_free:
4354 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00004355 APSInt SizeVal;
4356 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4357 return false;
4358
4359 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4360 // of two less than the maximum inline atomic width, we know it is
4361 // lock-free. If the size isn't a power of two, or greater than the
4362 // maximum alignment where we promote atomics, we know it is not lock-free
4363 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4364 // the answer can only be determined at runtime; for example, 16-byte
4365 // atomics have lock-free implementations on some, but not all,
4366 // x86-64 processors.
4367
4368 // Check power-of-two.
4369 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00004370 if (Size.isPowerOfTwo()) {
4371 // Check against inlining width.
4372 unsigned InlineWidthBits =
4373 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4374 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4375 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4376 Size == CharUnits::One() ||
4377 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4378 Expr::NPC_NeverValueDependent))
4379 // OK, we will inline appropriately-aligned operations of this size,
4380 // and _Atomic(T) is appropriately-aligned.
4381 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004382
Richard Smith01ba47d2012-04-13 00:45:38 +00004383 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4384 castAs<PointerType>()->getPointeeType();
4385 if (!PointeeType->isIncompleteType() &&
4386 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4387 // OK, we will inline operations on this object.
4388 return Success(1, E);
4389 }
4390 }
4391 }
Eli Friedmana4c26022011-10-17 21:44:23 +00004392
Richard Smith01ba47d2012-04-13 00:45:38 +00004393 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4394 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004395 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004396 }
Chris Lattner7174bf32008-07-12 00:38:25 +00004397}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004398
Richard Smith8b3497e2011-10-31 01:37:14 +00004399static bool HasSameBase(const LValue &A, const LValue &B) {
4400 if (!A.getLValueBase())
4401 return !B.getLValueBase();
4402 if (!B.getLValueBase())
4403 return false;
4404
Richard Smithce40ad62011-11-12 22:28:03 +00004405 if (A.getLValueBase().getOpaqueValue() !=
4406 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00004407 const Decl *ADecl = GetLValueBaseDecl(A);
4408 if (!ADecl)
4409 return false;
4410 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00004411 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00004412 return false;
4413 }
4414
4415 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00004416 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00004417}
4418
Richard Smithc8042322012-02-01 05:53:12 +00004419/// Perform the given integer operation, which is known to need at most BitWidth
4420/// bits, and check for overflow in the original type (if that type was not an
4421/// unsigned type).
4422template<typename Operation>
4423static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4424 const APSInt &LHS, const APSInt &RHS,
4425 unsigned BitWidth, Operation Op) {
4426 if (LHS.isUnsigned())
4427 return Op(LHS, RHS);
4428
4429 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4430 APSInt Result = Value.trunc(LHS.getBitWidth());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00004431 if (Result.extend(BitWidth) != Value) {
4432 if (Info.getIntOverflowCheckMode())
4433 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
4434 diag::warn_integer_constant_overflow)
4435 << Result.toString(10) << E->getType();
4436 else
4437 HandleOverflow(Info, E, Value, E->getType());
4438 }
Richard Smithc8042322012-02-01 05:53:12 +00004439 return Result;
4440}
4441
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004442namespace {
Richard Smith11562c52011-10-28 17:51:58 +00004443
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004444/// \brief Data recursive integer evaluator of certain binary operators.
4445///
4446/// We use a data recursive algorithm for binary operators so that we are able
4447/// to handle extreme cases of chained binary operators without causing stack
4448/// overflow.
4449class DataRecursiveIntBinOpEvaluator {
4450 struct EvalResult {
4451 APValue Val;
4452 bool Failed;
4453
4454 EvalResult() : Failed(false) { }
4455
4456 void swap(EvalResult &RHS) {
4457 Val.swap(RHS.Val);
4458 Failed = RHS.Failed;
4459 RHS.Failed = false;
4460 }
4461 };
4462
4463 struct Job {
4464 const Expr *E;
4465 EvalResult LHSResult; // meaningful only for binary operator expression.
4466 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4467
4468 Job() : StoredInfo(0) { }
4469 void startSpeculativeEval(EvalInfo &Info) {
4470 OldEvalStatus = Info.EvalStatus;
4471 Info.EvalStatus.Diag = 0;
4472 StoredInfo = &Info;
4473 }
4474 ~Job() {
4475 if (StoredInfo) {
4476 StoredInfo->EvalStatus = OldEvalStatus;
4477 }
4478 }
4479 private:
4480 EvalInfo *StoredInfo; // non-null if status changed.
4481 Expr::EvalStatus OldEvalStatus;
4482 };
4483
4484 SmallVector<Job, 16> Queue;
4485
4486 IntExprEvaluator &IntEval;
4487 EvalInfo &Info;
4488 APValue &FinalResult;
4489
4490public:
4491 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4492 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4493
4494 /// \brief True if \param E is a binary operator that we are going to handle
4495 /// data recursively.
4496 /// We handle binary operators that are comma, logical, or that have operands
4497 /// with integral or enumeration type.
4498 static bool shouldEnqueue(const BinaryOperator *E) {
4499 return E->getOpcode() == BO_Comma ||
4500 E->isLogicalOp() ||
4501 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4502 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00004503 }
4504
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004505 bool Traverse(const BinaryOperator *E) {
4506 enqueue(E);
4507 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00004508 while (!Queue.empty())
4509 process(PrevResult);
4510
4511 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004512
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004513 FinalResult.swap(PrevResult.Val);
4514 return true;
4515 }
4516
4517private:
4518 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4519 return IntEval.Success(Value, E, Result);
4520 }
4521 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4522 return IntEval.Success(Value, E, Result);
4523 }
4524 bool Error(const Expr *E) {
4525 return IntEval.Error(E);
4526 }
4527 bool Error(const Expr *E, diag::kind D) {
4528 return IntEval.Error(E, D);
4529 }
4530
4531 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4532 return Info.CCEDiag(E, D);
4533 }
4534
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004535 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4536 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004537 bool &SuppressRHSDiags);
4538
4539 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4540 const BinaryOperator *E, APValue &Result);
4541
4542 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4543 Result.Failed = !Evaluate(Result.Val, Info, E);
4544 if (Result.Failed)
4545 Result.Val = APValue();
4546 }
4547
Richard Trieuba4d0872012-03-21 23:30:30 +00004548 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004549
4550 void enqueue(const Expr *E) {
4551 E = E->IgnoreParens();
4552 Queue.resize(Queue.size()+1);
4553 Queue.back().E = E;
4554 Queue.back().Kind = Job::AnyExprKind;
4555 }
4556};
4557
4558}
4559
4560bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004561 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004562 bool &SuppressRHSDiags) {
4563 if (E->getOpcode() == BO_Comma) {
4564 // Ignore LHS but note if we could not evaluate it.
4565 if (LHSResult.Failed)
4566 Info.EvalStatus.HasSideEffects = true;
4567 return true;
4568 }
4569
4570 if (E->isLogicalOp()) {
4571 bool lhsResult;
4572 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004573 // We were able to evaluate the LHS, see if we can get away with not
4574 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004575 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004576 Success(lhsResult, E, LHSResult.Val);
4577 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004578 }
4579 } else {
4580 // Since we weren't able to evaluate the left hand side, it
4581 // must have had side effects.
4582 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004583
4584 // We can't evaluate the LHS; however, sometimes the result
4585 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4586 // Don't ignore RHS and suppress diagnostics from this arm.
4587 SuppressRHSDiags = true;
4588 }
4589
4590 return true;
4591 }
4592
4593 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4594 E->getRHS()->getType()->isIntegralOrEnumerationType());
4595
4596 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004597 return false; // Ignore RHS;
4598
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004599 return true;
4600}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004601
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004602bool DataRecursiveIntBinOpEvaluator::
4603 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4604 const BinaryOperator *E, APValue &Result) {
4605 if (E->getOpcode() == BO_Comma) {
4606 if (RHSResult.Failed)
4607 return false;
4608 Result = RHSResult.Val;
4609 return true;
4610 }
4611
4612 if (E->isLogicalOp()) {
4613 bool lhsResult, rhsResult;
4614 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4615 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4616
4617 if (LHSIsOK) {
4618 if (RHSIsOK) {
4619 if (E->getOpcode() == BO_LOr)
4620 return Success(lhsResult || rhsResult, E, Result);
4621 else
4622 return Success(lhsResult && rhsResult, E, Result);
4623 }
4624 } else {
4625 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004626 // We can't evaluate the LHS; however, sometimes the result
4627 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4628 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004629 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004630 }
4631 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004632
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004633 return false;
4634 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004635
4636 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4637 E->getRHS()->getType()->isIntegralOrEnumerationType());
4638
4639 if (LHSResult.Failed || RHSResult.Failed)
4640 return false;
4641
4642 const APValue &LHSVal = LHSResult.Val;
4643 const APValue &RHSVal = RHSResult.Val;
4644
4645 // Handle cases like (unsigned long)&a + 4.
4646 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4647 Result = LHSVal;
4648 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4649 RHSVal.getInt().getZExtValue());
4650 if (E->getOpcode() == BO_Add)
4651 Result.getLValueOffset() += AdditionalOffset;
4652 else
4653 Result.getLValueOffset() -= AdditionalOffset;
4654 return true;
4655 }
4656
4657 // Handle cases like 4 + (unsigned long)&a
4658 if (E->getOpcode() == BO_Add &&
4659 RHSVal.isLValue() && LHSVal.isInt()) {
4660 Result = RHSVal;
4661 Result.getLValueOffset() += CharUnits::fromQuantity(
4662 LHSVal.getInt().getZExtValue());
4663 return true;
4664 }
4665
4666 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4667 // Handle (intptr_t)&&A - (intptr_t)&&B.
4668 if (!LHSVal.getLValueOffset().isZero() ||
4669 !RHSVal.getLValueOffset().isZero())
4670 return false;
4671 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4672 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4673 if (!LHSExpr || !RHSExpr)
4674 return false;
4675 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4676 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4677 if (!LHSAddrExpr || !RHSAddrExpr)
4678 return false;
4679 // Make sure both labels come from the same function.
4680 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4681 RHSAddrExpr->getLabel()->getDeclContext())
4682 return false;
4683 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4684 return true;
4685 }
4686
4687 // All the following cases expect both operands to be an integer
4688 if (!LHSVal.isInt() || !RHSVal.isInt())
4689 return Error(E);
4690
4691 const APSInt &LHS = LHSVal.getInt();
4692 APSInt RHS = RHSVal.getInt();
4693
4694 switch (E->getOpcode()) {
4695 default:
4696 return Error(E);
4697 case BO_Mul:
4698 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4699 LHS.getBitWidth() * 2,
4700 std::multiplies<APSInt>()), E,
4701 Result);
4702 case BO_Add:
4703 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4704 LHS.getBitWidth() + 1,
4705 std::plus<APSInt>()), E, Result);
4706 case BO_Sub:
4707 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4708 LHS.getBitWidth() + 1,
4709 std::minus<APSInt>()), E, Result);
4710 case BO_And: return Success(LHS & RHS, E, Result);
4711 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4712 case BO_Or: return Success(LHS | RHS, E, Result);
4713 case BO_Div:
4714 case BO_Rem:
4715 if (RHS == 0)
4716 return Error(E, diag::note_expr_divide_by_zero);
4717 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4718 // not actually undefined behavior in C++11 due to a language defect.
4719 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4720 LHS.isSigned() && LHS.isMinSignedValue())
4721 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4722 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4723 Result);
4724 case BO_Shl: {
David Tweed042e0882013-01-07 16:43:27 +00004725 if (Info.getLangOpts().OpenCL)
4726 // OpenCL 6.3j: shift values are effectively % word size of LHS.
4727 RHS &= APSInt(llvm::APInt(LHS.getBitWidth(),
4728 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
4729 RHS.isUnsigned());
4730 else if (RHS.isSigned() && RHS.isNegative()) {
4731 // During constant-folding, a negative shift is an opposite shift. Such
4732 // a shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004733 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4734 RHS = -RHS;
4735 goto shift_right;
4736 }
4737
4738 shift_left:
4739 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4740 // the shifted type.
4741 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4742 if (SA != RHS) {
4743 CCEDiag(E, diag::note_constexpr_large_shift)
4744 << RHS << E->getType() << LHS.getBitWidth();
4745 } else if (LHS.isSigned()) {
4746 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4747 // operand, and must not overflow the corresponding unsigned type.
4748 if (LHS.isNegative())
4749 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4750 else if (LHS.countLeadingZeros() < SA)
4751 CCEDiag(E, diag::note_constexpr_lshift_discards);
4752 }
4753
4754 return Success(LHS << SA, E, Result);
4755 }
4756 case BO_Shr: {
David Tweed042e0882013-01-07 16:43:27 +00004757 if (Info.getLangOpts().OpenCL)
4758 // OpenCL 6.3j: shift values are effectively % word size of LHS.
4759 RHS &= APSInt(llvm::APInt(LHS.getBitWidth(),
4760 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
4761 RHS.isUnsigned());
4762 else if (RHS.isSigned() && RHS.isNegative()) {
4763 // During constant-folding, a negative shift is an opposite shift. Such a
4764 // shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004765 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4766 RHS = -RHS;
4767 goto shift_left;
4768 }
4769
4770 shift_right:
4771 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4772 // shifted type.
4773 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4774 if (SA != RHS)
4775 CCEDiag(E, diag::note_constexpr_large_shift)
4776 << RHS << E->getType() << LHS.getBitWidth();
4777
4778 return Success(LHS >> SA, E, Result);
4779 }
4780
4781 case BO_LT: return Success(LHS < RHS, E, Result);
4782 case BO_GT: return Success(LHS > RHS, E, Result);
4783 case BO_LE: return Success(LHS <= RHS, E, Result);
4784 case BO_GE: return Success(LHS >= RHS, E, Result);
4785 case BO_EQ: return Success(LHS == RHS, E, Result);
4786 case BO_NE: return Success(LHS != RHS, E, Result);
4787 }
4788}
4789
Richard Trieuba4d0872012-03-21 23:30:30 +00004790void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004791 Job &job = Queue.back();
4792
4793 switch (job.Kind) {
4794 case Job::AnyExprKind: {
4795 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4796 if (shouldEnqueue(Bop)) {
4797 job.Kind = Job::BinOpKind;
4798 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00004799 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004800 }
4801 }
4802
4803 EvaluateExpr(job.E, Result);
4804 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00004805 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004806 }
4807
4808 case Job::BinOpKind: {
4809 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004810 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004811 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004812 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00004813 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004814 }
4815 if (SuppressRHSDiags)
4816 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004817 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004818 job.Kind = Job::BinOpVisitedLHSKind;
4819 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00004820 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004821 }
4822
4823 case Job::BinOpVisitedLHSKind: {
4824 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4825 EvalResult RHS;
4826 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00004827 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004828 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00004829 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004830 }
4831 }
4832
4833 llvm_unreachable("Invalid Job::Kind!");
4834}
4835
4836bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4837 if (E->isAssignmentOp())
4838 return Error(E);
4839
4840 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4841 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004842
Anders Carlssonacc79812008-11-16 07:17:21 +00004843 QualType LHSTy = E->getLHS()->getType();
4844 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004845
4846 if (LHSTy->isAnyComplexType()) {
4847 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00004848 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004849
Richard Smith253c2a32012-01-27 01:14:48 +00004850 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4851 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004852 return false;
4853
Richard Smith253c2a32012-01-27 01:14:48 +00004854 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004855 return false;
4856
4857 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00004858 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004859 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00004860 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004861 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4862
John McCalle3027922010-08-25 11:45:40 +00004863 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004864 return Success((CR_r == APFloat::cmpEqual &&
4865 CR_i == APFloat::cmpEqual), E);
4866 else {
John McCalle3027922010-08-25 11:45:40 +00004867 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004868 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00004869 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00004870 CR_r == APFloat::cmpLessThan ||
4871 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00004872 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00004873 CR_i == APFloat::cmpLessThan ||
4874 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004875 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004876 } else {
John McCalle3027922010-08-25 11:45:40 +00004877 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004878 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4879 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4880 else {
John McCalle3027922010-08-25 11:45:40 +00004881 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004882 "Invalid compex comparison.");
4883 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4884 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4885 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004886 }
4887 }
Mike Stump11289f42009-09-09 15:08:12 +00004888
Anders Carlssonacc79812008-11-16 07:17:21 +00004889 if (LHSTy->isRealFloatingType() &&
4890 RHSTy->isRealFloatingType()) {
4891 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00004892
Richard Smith253c2a32012-01-27 01:14:48 +00004893 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4894 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00004895 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004896
Richard Smith253c2a32012-01-27 01:14:48 +00004897 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00004898 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004899
Anders Carlssonacc79812008-11-16 07:17:21 +00004900 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00004901
Anders Carlssonacc79812008-11-16 07:17:21 +00004902 switch (E->getOpcode()) {
4903 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004904 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00004905 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004906 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00004907 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004908 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00004909 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004910 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00004911 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00004912 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004913 E);
John McCalle3027922010-08-25 11:45:40 +00004914 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004915 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00004916 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00004917 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00004918 || CR == APFloat::cmpLessThan
4919 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00004920 }
Anders Carlssonacc79812008-11-16 07:17:21 +00004921 }
Mike Stump11289f42009-09-09 15:08:12 +00004922
Eli Friedmana38da572009-04-28 19:17:36 +00004923 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00004924 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004925 LValue LHSValue, RHSValue;
4926
4927 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4928 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004929 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004930
Richard Smith253c2a32012-01-27 01:14:48 +00004931 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004932 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004933
Richard Smith8b3497e2011-10-31 01:37:14 +00004934 // Reject differing bases from the normal codepath; we special-case
4935 // comparisons to null.
4936 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004937 if (E->getOpcode() == BO_Sub) {
4938 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004939 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4940 return false;
4941 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00004942 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004943 if (!LHSExpr || !RHSExpr)
4944 return false;
4945 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4946 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4947 if (!LHSAddrExpr || !RHSAddrExpr)
4948 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004949 // Make sure both labels come from the same function.
4950 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4951 RHSAddrExpr->getLabel()->getDeclContext())
4952 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004953 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004954 return true;
4955 }
Richard Smith83c68212011-10-31 05:11:32 +00004956 // Inequalities and subtractions between unrelated pointers have
4957 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00004958 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004959 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004960 // A constant address may compare equal to the address of a symbol.
4961 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00004962 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004963 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4964 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004965 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004966 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00004967 // distinct addresses. In clang, the result of such a comparison is
4968 // unspecified, so it is not a constant expression. However, we do know
4969 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00004970 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4971 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004972 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004973 // We can't tell whether weak symbols will end up pointing to the same
4974 // object.
4975 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004976 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004977 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00004978 // (Note that clang defaults to -fmerge-all-constants, which can
4979 // lead to inconsistent results for comparisons involving the address
4980 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00004981 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00004982 }
Eli Friedman64004332009-03-23 04:38:34 +00004983
Richard Smith1b470412012-02-01 08:10:20 +00004984 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
4985 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
4986
Richard Smith84f6dcf2012-02-02 01:16:57 +00004987 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
4988 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
4989
John McCalle3027922010-08-25 11:45:40 +00004990 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004991 // C++11 [expr.add]p6:
4992 // Unless both pointers point to elements of the same array object, or
4993 // one past the last element of the array object, the behavior is
4994 // undefined.
4995 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
4996 !AreElementsOfSameArray(getType(LHSValue.Base),
4997 LHSDesignator, RHSDesignator))
4998 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
4999
Chris Lattner882bdf22010-04-20 17:13:14 +00005000 QualType Type = E->getLHS()->getType();
5001 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005002
Richard Smithd62306a2011-11-10 06:34:14 +00005003 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00005004 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00005005 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005006
Richard Smith1b470412012-02-01 08:10:20 +00005007 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5008 // and produce incorrect results when it overflows. Such behavior
5009 // appears to be non-conforming, but is common, so perhaps we should
5010 // assume the standard intended for such cases to be undefined behavior
5011 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00005012
Richard Smith1b470412012-02-01 08:10:20 +00005013 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5014 // overflow in the final conversion to ptrdiff_t.
5015 APSInt LHS(
5016 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5017 APSInt RHS(
5018 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5019 APSInt ElemSize(
5020 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5021 APSInt TrueResult = (LHS - RHS) / ElemSize;
5022 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5023
5024 if (Result.extend(65) != TrueResult)
5025 HandleOverflow(Info, E, TrueResult, E->getType());
5026 return Success(Result, E);
5027 }
Richard Smithde21b242012-01-31 06:41:30 +00005028
5029 // C++11 [expr.rel]p3:
5030 // Pointers to void (after pointer conversions) can be compared, with a
5031 // result defined as follows: If both pointers represent the same
5032 // address or are both the null pointer value, the result is true if the
5033 // operator is <= or >= and false otherwise; otherwise the result is
5034 // unspecified.
5035 // We interpret this as applying to pointers to *cv* void.
5036 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00005037 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00005038 CCEDiag(E, diag::note_constexpr_void_comparison);
5039
Richard Smith84f6dcf2012-02-02 01:16:57 +00005040 // C++11 [expr.rel]p2:
5041 // - If two pointers point to non-static data members of the same object,
5042 // or to subobjects or array elements fo such members, recursively, the
5043 // pointer to the later declared member compares greater provided the
5044 // two members have the same access control and provided their class is
5045 // not a union.
5046 // [...]
5047 // - Otherwise pointer comparisons are unspecified.
5048 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5049 E->isRelationalOp()) {
5050 bool WasArrayIndex;
5051 unsigned Mismatch =
5052 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5053 RHSDesignator, WasArrayIndex);
5054 // At the point where the designators diverge, the comparison has a
5055 // specified value if:
5056 // - we are comparing array indices
5057 // - we are comparing fields of a union, or fields with the same access
5058 // Otherwise, the result is unspecified and thus the comparison is not a
5059 // constant expression.
5060 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5061 Mismatch < RHSDesignator.Entries.size()) {
5062 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5063 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5064 if (!LF && !RF)
5065 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5066 else if (!LF)
5067 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5068 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5069 << RF->getParent() << RF;
5070 else if (!RF)
5071 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5072 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5073 << LF->getParent() << LF;
5074 else if (!LF->getParent()->isUnion() &&
5075 LF->getAccess() != RF->getAccess())
5076 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5077 << LF << LF->getAccess() << RF << RF->getAccess()
5078 << LF->getParent();
5079 }
5080 }
5081
Eli Friedman6c31cb42012-04-16 04:30:08 +00005082 // The comparison here must be unsigned, and performed with the same
5083 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00005084 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5085 uint64_t CompareLHS = LHSOffset.getQuantity();
5086 uint64_t CompareRHS = RHSOffset.getQuantity();
5087 assert(PtrSize <= 64 && "Unexpected pointer width");
5088 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5089 CompareLHS &= Mask;
5090 CompareRHS &= Mask;
5091
Eli Friedman2f5b7c52012-04-16 19:23:57 +00005092 // If there is a base and this is a relational operator, we can only
5093 // compare pointers within the object in question; otherwise, the result
5094 // depends on where the object is located in memory.
5095 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5096 QualType BaseTy = getType(LHSValue.Base);
5097 if (BaseTy->isIncompleteType())
5098 return Error(E);
5099 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5100 uint64_t OffsetLimit = Size.getQuantity();
5101 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5102 return Error(E);
5103 }
5104
Richard Smith8b3497e2011-10-31 01:37:14 +00005105 switch (E->getOpcode()) {
5106 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00005107 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5108 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5109 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5110 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5111 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5112 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00005113 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005114 }
5115 }
Richard Smith7bb00672012-02-01 01:42:44 +00005116
5117 if (LHSTy->isMemberPointerType()) {
5118 assert(E->isEqualityOp() && "unexpected member pointer operation");
5119 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5120
5121 MemberPtr LHSValue, RHSValue;
5122
5123 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5124 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5125 return false;
5126
5127 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5128 return false;
5129
5130 // C++11 [expr.eq]p2:
5131 // If both operands are null, they compare equal. Otherwise if only one is
5132 // null, they compare unequal.
5133 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5134 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5135 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5136 }
5137
5138 // Otherwise if either is a pointer to a virtual member function, the
5139 // result is unspecified.
5140 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5141 if (MD->isVirtual())
5142 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5143 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5144 if (MD->isVirtual())
5145 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5146
5147 // Otherwise they compare equal if and only if they would refer to the
5148 // same member of the same most derived object or the same subobject if
5149 // they were dereferenced with a hypothetical object of the associated
5150 // class type.
5151 bool Equal = LHSValue == RHSValue;
5152 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5153 }
5154
Richard Smithab44d9b2012-02-14 22:35:28 +00005155 if (LHSTy->isNullPtrType()) {
5156 assert(E->isComparisonOp() && "unexpected nullptr operation");
5157 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5158 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5159 // are compared, the result is true of the operator is <=, >= or ==, and
5160 // false otherwise.
5161 BinaryOperator::Opcode Opcode = E->getOpcode();
5162 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5163 }
5164
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005165 assert((!LHSTy->isIntegralOrEnumerationType() ||
5166 !RHSTy->isIntegralOrEnumerationType()) &&
5167 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5168 // We can't continue from here for non-integral types.
5169 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00005170}
5171
Ken Dyck160146e2010-01-27 17:10:57 +00005172CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00005173 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5174 // result shall be the alignment of the referenced type."
5175 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5176 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00005177
5178 // __alignof is defined to return the preferred alignment.
5179 return Info.Ctx.toCharUnitsFromBits(
5180 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00005181}
5182
Ken Dyck160146e2010-01-27 17:10:57 +00005183CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00005184 E = E->IgnoreParens();
5185
5186 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00005187 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00005188 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005189 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5190 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00005191
Chris Lattner68061312009-01-24 21:53:27 +00005192 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005193 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5194 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00005195
Chris Lattner24aeeab2009-01-24 21:09:06 +00005196 return GetAlignOfType(E->getType());
5197}
5198
5199
Peter Collingbournee190dee2011-03-11 19:24:49 +00005200/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5201/// a result as the expression's type.
5202bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5203 const UnaryExprOrTypeTraitExpr *E) {
5204 switch(E->getKind()) {
5205 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00005206 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00005207 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005208 else
Ken Dyckdbc01912011-03-11 02:13:43 +00005209 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005210 }
Eli Friedman64004332009-03-23 04:38:34 +00005211
Peter Collingbournee190dee2011-03-11 19:24:49 +00005212 case UETT_VecStep: {
5213 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00005214
Peter Collingbournee190dee2011-03-11 19:24:49 +00005215 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00005216 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00005217
Peter Collingbournee190dee2011-03-11 19:24:49 +00005218 // The vec_step built-in functions that take a 3-component
5219 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5220 if (n == 3)
5221 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00005222
Peter Collingbournee190dee2011-03-11 19:24:49 +00005223 return Success(n, E);
5224 } else
5225 return Success(1, E);
5226 }
5227
5228 case UETT_SizeOf: {
5229 QualType SrcTy = E->getTypeOfArgument();
5230 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5231 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00005232 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5233 SrcTy = Ref->getPointeeType();
5234
Richard Smithd62306a2011-11-10 06:34:14 +00005235 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00005236 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00005237 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005238 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005239 }
5240 }
5241
5242 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005243}
5244
Peter Collingbournee9200682011-05-13 03:29:01 +00005245bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00005246 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00005247 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00005248 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005249 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00005250 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00005251 for (unsigned i = 0; i != n; ++i) {
5252 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5253 switch (ON.getKind()) {
5254 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00005255 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00005256 APSInt IdxResult;
5257 if (!EvaluateInteger(Idx, IdxResult, Info))
5258 return false;
5259 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5260 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005261 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005262 CurrentType = AT->getElementType();
5263 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5264 Result += IdxResult.getSExtValue() * ElementSize;
5265 break;
5266 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005267
Douglas Gregor882211c2010-04-28 22:16:22 +00005268 case OffsetOfExpr::OffsetOfNode::Field: {
5269 FieldDecl *MemberDecl = ON.getField();
5270 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005271 if (!RT)
5272 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005273 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005274 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00005275 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00005276 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00005277 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00005278 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00005279 CurrentType = MemberDecl->getType().getNonReferenceType();
5280 break;
5281 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005282
Douglas Gregor882211c2010-04-28 22:16:22 +00005283 case OffsetOfExpr::OffsetOfNode::Identifier:
5284 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00005285
Douglas Gregord1702062010-04-29 00:18:15 +00005286 case OffsetOfExpr::OffsetOfNode::Base: {
5287 CXXBaseSpecifier *BaseSpec = ON.getBase();
5288 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005289 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005290
5291 // Find the layout of the class whose base we are looking into.
5292 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005293 if (!RT)
5294 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005295 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005296 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00005297 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5298
5299 // Find the base class itself.
5300 CurrentType = BaseSpec->getType();
5301 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5302 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005303 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005304
5305 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00005306 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00005307 break;
5308 }
Douglas Gregor882211c2010-04-28 22:16:22 +00005309 }
5310 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005311 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005312}
5313
Chris Lattnere13042c2008-07-11 19:10:17 +00005314bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005315 switch (E->getOpcode()) {
5316 default:
5317 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5318 // See C99 6.6p3.
5319 return Error(E);
5320 case UO_Extension:
5321 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5322 // If so, we could clear the diagnostic ID.
5323 return Visit(E->getSubExpr());
5324 case UO_Plus:
5325 // The result is just the value.
5326 return Visit(E->getSubExpr());
5327 case UO_Minus: {
5328 if (!Visit(E->getSubExpr()))
5329 return false;
5330 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00005331 const APSInt &Value = Result.getInt();
5332 if (Value.isSigned() && Value.isMinSignedValue())
5333 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5334 E->getType());
5335 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005336 }
5337 case UO_Not: {
5338 if (!Visit(E->getSubExpr()))
5339 return false;
5340 if (!Result.isInt()) return Error(E);
5341 return Success(~Result.getInt(), E);
5342 }
5343 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00005344 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00005345 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00005346 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005347 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005348 }
Anders Carlsson9c181652008-07-08 14:35:21 +00005349 }
Anders Carlsson9c181652008-07-08 14:35:21 +00005350}
Mike Stump11289f42009-09-09 15:08:12 +00005351
Chris Lattner477c4be2008-07-12 01:15:53 +00005352/// HandleCast - This is used to evaluate implicit or explicit casts where the
5353/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00005354bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5355 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00005356 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00005357 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00005358
Eli Friedmanc757de22011-03-25 00:43:55 +00005359 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00005360 case CK_BaseToDerived:
5361 case CK_DerivedToBase:
5362 case CK_UncheckedDerivedToBase:
5363 case CK_Dynamic:
5364 case CK_ToUnion:
5365 case CK_ArrayToPointerDecay:
5366 case CK_FunctionToPointerDecay:
5367 case CK_NullToPointer:
5368 case CK_NullToMemberPointer:
5369 case CK_BaseToDerivedMemberPointer:
5370 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00005371 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00005372 case CK_ConstructorConversion:
5373 case CK_IntegralToPointer:
5374 case CK_ToVoid:
5375 case CK_VectorSplat:
5376 case CK_IntegralToFloating:
5377 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00005378 case CK_CPointerToObjCPointerCast:
5379 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00005380 case CK_AnyPointerToBlockPointerCast:
5381 case CK_ObjCObjectLValueCast:
5382 case CK_FloatingRealToComplex:
5383 case CK_FloatingComplexToReal:
5384 case CK_FloatingComplexCast:
5385 case CK_FloatingComplexToIntegralComplex:
5386 case CK_IntegralRealToComplex:
5387 case CK_IntegralComplexCast:
5388 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00005389 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005390 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005391 llvm_unreachable("invalid cast kind for integral value");
5392
Eli Friedman9faf2f92011-03-25 19:07:11 +00005393 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00005394 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005395 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00005396 case CK_ARCProduceObject:
5397 case CK_ARCConsumeObject:
5398 case CK_ARCReclaimReturnedObject:
5399 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00005400 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005401 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005402
Richard Smith4ef685b2012-01-17 21:17:26 +00005403 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00005404 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00005405 case CK_AtomicToNonAtomic:
5406 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00005407 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00005408 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005409
5410 case CK_MemberPointerToBoolean:
5411 case CK_PointerToBoolean:
5412 case CK_IntegralToBoolean:
5413 case CK_FloatingToBoolean:
5414 case CK_FloatingComplexToBoolean:
5415 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00005416 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00005417 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00005418 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005419 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005420 }
5421
Eli Friedmanc757de22011-03-25 00:43:55 +00005422 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00005423 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00005424 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00005425
Eli Friedman742421e2009-02-20 01:15:07 +00005426 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005427 // Allow casts of address-of-label differences if they are no-ops
5428 // or narrowing. (The narrowing case isn't actually guaranteed to
5429 // be constant-evaluatable except in some narrow cases which are hard
5430 // to detect here. We let it through on the assumption the user knows
5431 // what they are doing.)
5432 if (Result.isAddrLabelDiff())
5433 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00005434 // Only allow casts of lvalues if they are lossless.
5435 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5436 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005437
Richard Smith911e1422012-01-30 22:27:01 +00005438 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5439 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00005440 }
Mike Stump11289f42009-09-09 15:08:12 +00005441
Eli Friedmanc757de22011-03-25 00:43:55 +00005442 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005443 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5444
John McCall45d55e42010-05-07 21:00:08 +00005445 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00005446 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00005447 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00005448
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005449 if (LV.getLValueBase()) {
5450 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00005451 // FIXME: Allow a larger integer size than the pointer size, and allow
5452 // narrowing back down to pointer width in subsequent integral casts.
5453 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005454 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005455 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005456
Richard Smithcf74da72011-11-16 07:18:12 +00005457 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005458 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005459 return true;
5460 }
5461
Ken Dyck02990832010-01-15 12:37:54 +00005462 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5463 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00005464 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005465 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005466
Eli Friedmanc757de22011-03-25 00:43:55 +00005467 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00005468 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00005469 if (!EvaluateComplex(SubExpr, C, Info))
5470 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00005471 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00005472 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00005473
Eli Friedmanc757de22011-03-25 00:43:55 +00005474 case CK_FloatingToIntegral: {
5475 APFloat F(0.0);
5476 if (!EvaluateFloat(SubExpr, F, Info))
5477 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00005478
Richard Smith357362d2011-12-13 06:39:58 +00005479 APSInt Value;
5480 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5481 return false;
5482 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005483 }
5484 }
Mike Stump11289f42009-09-09 15:08:12 +00005485
Eli Friedmanc757de22011-03-25 00:43:55 +00005486 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00005487}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005488
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005489bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5490 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00005491 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005492 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5493 return false;
5494 if (!LV.isComplexInt())
5495 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005496 return Success(LV.getComplexIntReal(), E);
5497 }
5498
5499 return Visit(E->getSubExpr());
5500}
5501
Eli Friedman4e7a2412009-02-27 04:45:43 +00005502bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005503 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00005504 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005505 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5506 return false;
5507 if (!LV.isComplexInt())
5508 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005509 return Success(LV.getComplexIntImag(), E);
5510 }
5511
Richard Smith4a678122011-10-24 18:44:57 +00005512 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00005513 return Success(0, E);
5514}
5515
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005516bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5517 return Success(E->getPackLength(), E);
5518}
5519
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005520bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5521 return Success(E->getValue(), E);
5522}
5523
Chris Lattner05706e882008-07-11 18:11:29 +00005524//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00005525// Float Evaluation
5526//===----------------------------------------------------------------------===//
5527
5528namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005529class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005530 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00005531 APFloat &Result;
5532public:
5533 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005534 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00005535
Richard Smith2e312c82012-03-03 22:46:17 +00005536 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005537 Result = V.getFloat();
5538 return true;
5539 }
Eli Friedman24c01542008-08-22 00:06:13 +00005540
Richard Smithfddd3842011-12-30 21:15:51 +00005541 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00005542 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5543 return true;
5544 }
5545
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005546 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00005547
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005548 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00005549 bool VisitBinaryOperator(const BinaryOperator *E);
5550 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005551 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00005552
John McCallb1fb0d32010-05-07 22:08:54 +00005553 bool VisitUnaryReal(const UnaryOperator *E);
5554 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00005555
Richard Smithfddd3842011-12-30 21:15:51 +00005556 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00005557};
5558} // end anonymous namespace
5559
5560static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005561 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005562 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00005563}
5564
Jay Foad39c79802011-01-12 09:06:06 +00005565static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00005566 QualType ResultTy,
5567 const Expr *Arg,
5568 bool SNaN,
5569 llvm::APFloat &Result) {
5570 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5571 if (!S) return false;
5572
5573 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5574
5575 llvm::APInt fill;
5576
5577 // Treat empty strings as if they were zero.
5578 if (S->getString().empty())
5579 fill = llvm::APInt(32, 0);
5580 else if (S->getString().getAsInteger(0, fill))
5581 return false;
5582
5583 if (SNaN)
5584 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5585 else
5586 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5587 return true;
5588}
5589
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005590bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005591 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005592 default:
5593 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5594
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005595 case Builtin::BI__builtin_huge_val:
5596 case Builtin::BI__builtin_huge_valf:
5597 case Builtin::BI__builtin_huge_vall:
5598 case Builtin::BI__builtin_inf:
5599 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00005600 case Builtin::BI__builtin_infl: {
5601 const llvm::fltSemantics &Sem =
5602 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00005603 Result = llvm::APFloat::getInf(Sem);
5604 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00005605 }
Mike Stump11289f42009-09-09 15:08:12 +00005606
John McCall16291492010-02-28 13:00:19 +00005607 case Builtin::BI__builtin_nans:
5608 case Builtin::BI__builtin_nansf:
5609 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005610 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5611 true, Result))
5612 return Error(E);
5613 return true;
John McCall16291492010-02-28 13:00:19 +00005614
Chris Lattner0b7282e2008-10-06 06:31:58 +00005615 case Builtin::BI__builtin_nan:
5616 case Builtin::BI__builtin_nanf:
5617 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00005618 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00005619 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005620 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5621 false, Result))
5622 return Error(E);
5623 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005624
5625 case Builtin::BI__builtin_fabs:
5626 case Builtin::BI__builtin_fabsf:
5627 case Builtin::BI__builtin_fabsl:
5628 if (!EvaluateFloat(E->getArg(0), Result, Info))
5629 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005630
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005631 if (Result.isNegative())
5632 Result.changeSign();
5633 return true;
5634
Mike Stump11289f42009-09-09 15:08:12 +00005635 case Builtin::BI__builtin_copysign:
5636 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005637 case Builtin::BI__builtin_copysignl: {
5638 APFloat RHS(0.);
5639 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5640 !EvaluateFloat(E->getArg(1), RHS, Info))
5641 return false;
5642 Result.copySign(RHS);
5643 return true;
5644 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005645 }
5646}
5647
John McCallb1fb0d32010-05-07 22:08:54 +00005648bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00005649 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5650 ComplexValue CV;
5651 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5652 return false;
5653 Result = CV.FloatReal;
5654 return true;
5655 }
5656
5657 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00005658}
5659
5660bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00005661 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5662 ComplexValue CV;
5663 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5664 return false;
5665 Result = CV.FloatImag;
5666 return true;
5667 }
5668
Richard Smith4a678122011-10-24 18:44:57 +00005669 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00005670 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5671 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00005672 return true;
5673}
5674
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005675bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005676 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005677 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00005678 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00005679 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00005680 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00005681 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5682 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005683 Result.changeSign();
5684 return true;
5685 }
5686}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005687
Eli Friedman24c01542008-08-22 00:06:13 +00005688bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005689 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5690 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00005691
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005692 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00005693 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5694 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00005695 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005696 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedman24c01542008-08-22 00:06:13 +00005697 return false;
5698
5699 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005700 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00005701 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00005702 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005703 break;
John McCalle3027922010-08-25 11:45:40 +00005704 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00005705 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005706 break;
John McCalle3027922010-08-25 11:45:40 +00005707 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00005708 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005709 break;
John McCalle3027922010-08-25 11:45:40 +00005710 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00005711 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005712 break;
Eli Friedman24c01542008-08-22 00:06:13 +00005713 }
Richard Smithc8042322012-02-01 05:53:12 +00005714
5715 if (Result.isInfinity() || Result.isNaN())
5716 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5717 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00005718}
5719
5720bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5721 Result = E->getValue();
5722 return true;
5723}
5724
Peter Collingbournee9200682011-05-13 03:29:01 +00005725bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5726 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00005727
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005728 switch (E->getCastKind()) {
5729 default:
Richard Smith11562c52011-10-28 17:51:58 +00005730 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005731
5732 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00005733 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00005734 return EvaluateInteger(SubExpr, IntResult, Info) &&
5735 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5736 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005737 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005738
5739 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00005740 if (!Visit(SubExpr))
5741 return false;
Richard Smith357362d2011-12-13 06:39:58 +00005742 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5743 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005744 }
John McCalld7646252010-11-14 08:17:51 +00005745
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005746 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00005747 ComplexValue V;
5748 if (!EvaluateComplex(SubExpr, V, Info))
5749 return false;
5750 Result = V.getComplexFloatReal();
5751 return true;
5752 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005753 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005754}
5755
Eli Friedman24c01542008-08-22 00:06:13 +00005756//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005757// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00005758//===----------------------------------------------------------------------===//
5759
5760namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005761class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005762 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00005763 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00005764
Anders Carlsson537969c2008-11-16 20:27:53 +00005765public:
John McCall93d91dc2010-05-07 17:22:02 +00005766 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005767 : ExprEvaluatorBaseTy(info), Result(Result) {}
5768
Richard Smith2e312c82012-03-03 22:46:17 +00005769 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005770 Result.setFrom(V);
5771 return true;
5772 }
Mike Stump11289f42009-09-09 15:08:12 +00005773
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005774 bool ZeroInitialization(const Expr *E);
5775
Anders Carlsson537969c2008-11-16 20:27:53 +00005776 //===--------------------------------------------------------------------===//
5777 // Visitor Methods
5778 //===--------------------------------------------------------------------===//
5779
Peter Collingbournee9200682011-05-13 03:29:01 +00005780 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005781 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00005782 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005783 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005784 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00005785};
5786} // end anonymous namespace
5787
John McCall93d91dc2010-05-07 17:22:02 +00005788static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5789 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005790 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005791 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00005792}
5793
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005794bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00005795 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005796 if (ElemTy->isRealFloatingType()) {
5797 Result.makeComplexFloat();
5798 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5799 Result.FloatReal = Zero;
5800 Result.FloatImag = Zero;
5801 } else {
5802 Result.makeComplexInt();
5803 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5804 Result.IntReal = Zero;
5805 Result.IntImag = Zero;
5806 }
5807 return true;
5808}
5809
Peter Collingbournee9200682011-05-13 03:29:01 +00005810bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5811 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005812
5813 if (SubExpr->getType()->isRealFloatingType()) {
5814 Result.makeComplexFloat();
5815 APFloat &Imag = Result.FloatImag;
5816 if (!EvaluateFloat(SubExpr, Imag, Info))
5817 return false;
5818
5819 Result.FloatReal = APFloat(Imag.getSemantics());
5820 return true;
5821 } else {
5822 assert(SubExpr->getType()->isIntegerType() &&
5823 "Unexpected imaginary literal.");
5824
5825 Result.makeComplexInt();
5826 APSInt &Imag = Result.IntImag;
5827 if (!EvaluateInteger(SubExpr, Imag, Info))
5828 return false;
5829
5830 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5831 return true;
5832 }
5833}
5834
Peter Collingbournee9200682011-05-13 03:29:01 +00005835bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005836
John McCallfcef3cf2010-12-14 17:51:41 +00005837 switch (E->getCastKind()) {
5838 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00005839 case CK_BaseToDerived:
5840 case CK_DerivedToBase:
5841 case CK_UncheckedDerivedToBase:
5842 case CK_Dynamic:
5843 case CK_ToUnion:
5844 case CK_ArrayToPointerDecay:
5845 case CK_FunctionToPointerDecay:
5846 case CK_NullToPointer:
5847 case CK_NullToMemberPointer:
5848 case CK_BaseToDerivedMemberPointer:
5849 case CK_DerivedToBaseMemberPointer:
5850 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00005851 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00005852 case CK_ConstructorConversion:
5853 case CK_IntegralToPointer:
5854 case CK_PointerToIntegral:
5855 case CK_PointerToBoolean:
5856 case CK_ToVoid:
5857 case CK_VectorSplat:
5858 case CK_IntegralCast:
5859 case CK_IntegralToBoolean:
5860 case CK_IntegralToFloating:
5861 case CK_FloatingToIntegral:
5862 case CK_FloatingToBoolean:
5863 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00005864 case CK_CPointerToObjCPointerCast:
5865 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00005866 case CK_AnyPointerToBlockPointerCast:
5867 case CK_ObjCObjectLValueCast:
5868 case CK_FloatingComplexToReal:
5869 case CK_FloatingComplexToBoolean:
5870 case CK_IntegralComplexToReal:
5871 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00005872 case CK_ARCProduceObject:
5873 case CK_ARCConsumeObject:
5874 case CK_ARCReclaimReturnedObject:
5875 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00005876 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00005877 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005878 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00005879 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00005880
John McCallfcef3cf2010-12-14 17:51:41 +00005881 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00005882 case CK_AtomicToNonAtomic:
5883 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00005884 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00005885 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00005886
5887 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005888 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00005889 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005890 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00005891
5892 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005893 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00005894 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005895 return false;
5896
John McCallfcef3cf2010-12-14 17:51:41 +00005897 Result.makeComplexFloat();
5898 Result.FloatImag = APFloat(Real.getSemantics());
5899 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005900 }
5901
John McCallfcef3cf2010-12-14 17:51:41 +00005902 case CK_FloatingComplexCast: {
5903 if (!Visit(E->getSubExpr()))
5904 return false;
5905
5906 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5907 QualType From
5908 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5909
Richard Smith357362d2011-12-13 06:39:58 +00005910 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5911 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005912 }
5913
5914 case CK_FloatingComplexToIntegralComplex: {
5915 if (!Visit(E->getSubExpr()))
5916 return false;
5917
5918 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5919 QualType From
5920 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5921 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00005922 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5923 To, Result.IntReal) &&
5924 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5925 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005926 }
5927
5928 case CK_IntegralRealToComplex: {
5929 APSInt &Real = Result.IntReal;
5930 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5931 return false;
5932
5933 Result.makeComplexInt();
5934 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5935 return true;
5936 }
5937
5938 case CK_IntegralComplexCast: {
5939 if (!Visit(E->getSubExpr()))
5940 return false;
5941
5942 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5943 QualType From
5944 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5945
Richard Smith911e1422012-01-30 22:27:01 +00005946 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5947 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005948 return true;
5949 }
5950
5951 case CK_IntegralComplexToFloatingComplex: {
5952 if (!Visit(E->getSubExpr()))
5953 return false;
5954
Ted Kremenek28831752012-08-23 20:46:57 +00005955 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005956 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00005957 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005958 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00005959 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5960 To, Result.FloatReal) &&
5961 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5962 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005963 }
5964 }
5965
5966 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005967}
5968
John McCall93d91dc2010-05-07 17:22:02 +00005969bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005970 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00005971 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5972
Richard Smith253c2a32012-01-27 01:14:48 +00005973 bool LHSOK = Visit(E->getLHS());
5974 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00005975 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005976
John McCall93d91dc2010-05-07 17:22:02 +00005977 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00005978 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00005979 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005980
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005981 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5982 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005983 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005984 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00005985 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005986 if (Result.isComplexFloat()) {
5987 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
5988 APFloat::rmNearestTiesToEven);
5989 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
5990 APFloat::rmNearestTiesToEven);
5991 } else {
5992 Result.getComplexIntReal() += RHS.getComplexIntReal();
5993 Result.getComplexIntImag() += RHS.getComplexIntImag();
5994 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005995 break;
John McCalle3027922010-08-25 11:45:40 +00005996 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005997 if (Result.isComplexFloat()) {
5998 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
5999 APFloat::rmNearestTiesToEven);
6000 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6001 APFloat::rmNearestTiesToEven);
6002 } else {
6003 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6004 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6005 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006006 break;
John McCalle3027922010-08-25 11:45:40 +00006007 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006008 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00006009 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006010 APFloat &LHS_r = LHS.getComplexFloatReal();
6011 APFloat &LHS_i = LHS.getComplexFloatImag();
6012 APFloat &RHS_r = RHS.getComplexFloatReal();
6013 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00006014
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006015 APFloat Tmp = LHS_r;
6016 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6017 Result.getComplexFloatReal() = Tmp;
6018 Tmp = LHS_i;
6019 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6020 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6021
6022 Tmp = LHS_r;
6023 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6024 Result.getComplexFloatImag() = Tmp;
6025 Tmp = LHS_i;
6026 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6027 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6028 } else {
John McCall93d91dc2010-05-07 17:22:02 +00006029 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00006030 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006031 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6032 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00006033 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006034 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6035 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6036 }
6037 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006038 case BO_Div:
6039 if (Result.isComplexFloat()) {
6040 ComplexValue LHS = Result;
6041 APFloat &LHS_r = LHS.getComplexFloatReal();
6042 APFloat &LHS_i = LHS.getComplexFloatImag();
6043 APFloat &RHS_r = RHS.getComplexFloatReal();
6044 APFloat &RHS_i = RHS.getComplexFloatImag();
6045 APFloat &Res_r = Result.getComplexFloatReal();
6046 APFloat &Res_i = Result.getComplexFloatImag();
6047
6048 APFloat Den = RHS_r;
6049 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6050 APFloat Tmp = RHS_i;
6051 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6052 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6053
6054 Res_r = LHS_r;
6055 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6056 Tmp = LHS_i;
6057 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6058 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6059 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6060
6061 Res_i = LHS_i;
6062 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6063 Tmp = LHS_r;
6064 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6065 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6066 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6067 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006068 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6069 return Error(E, diag::note_expr_divide_by_zero);
6070
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006071 ComplexValue LHS = Result;
6072 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6073 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6074 Result.getComplexIntReal() =
6075 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6076 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6077 Result.getComplexIntImag() =
6078 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6079 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6080 }
6081 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006082 }
6083
John McCall93d91dc2010-05-07 17:22:02 +00006084 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006085}
6086
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006087bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6088 // Get the operand value into 'Result'.
6089 if (!Visit(E->getSubExpr()))
6090 return false;
6091
6092 switch (E->getOpcode()) {
6093 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006094 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006095 case UO_Extension:
6096 return true;
6097 case UO_Plus:
6098 // The result is always just the subexpr.
6099 return true;
6100 case UO_Minus:
6101 if (Result.isComplexFloat()) {
6102 Result.getComplexFloatReal().changeSign();
6103 Result.getComplexFloatImag().changeSign();
6104 }
6105 else {
6106 Result.getComplexIntReal() = -Result.getComplexIntReal();
6107 Result.getComplexIntImag() = -Result.getComplexIntImag();
6108 }
6109 return true;
6110 case UO_Not:
6111 if (Result.isComplexFloat())
6112 Result.getComplexFloatImag().changeSign();
6113 else
6114 Result.getComplexIntImag() = -Result.getComplexIntImag();
6115 return true;
6116 }
6117}
6118
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006119bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6120 if (E->getNumInits() == 2) {
6121 if (E->getType()->isComplexType()) {
6122 Result.makeComplexFloat();
6123 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6124 return false;
6125 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6126 return false;
6127 } else {
6128 Result.makeComplexInt();
6129 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6130 return false;
6131 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6132 return false;
6133 }
6134 return true;
6135 }
6136 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6137}
6138
Anders Carlsson537969c2008-11-16 20:27:53 +00006139//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00006140// Void expression evaluation, primarily for a cast to void on the LHS of a
6141// comma operator
6142//===----------------------------------------------------------------------===//
6143
6144namespace {
6145class VoidExprEvaluator
6146 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6147public:
6148 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6149
Richard Smith2e312c82012-03-03 22:46:17 +00006150 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00006151
6152 bool VisitCastExpr(const CastExpr *E) {
6153 switch (E->getCastKind()) {
6154 default:
6155 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6156 case CK_ToVoid:
6157 VisitIgnoredValue(E->getSubExpr());
6158 return true;
6159 }
6160 }
6161};
6162} // end anonymous namespace
6163
6164static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6165 assert(E->isRValue() && E->getType()->isVoidType());
6166 return VoidExprEvaluator(Info).Visit(E);
6167}
6168
6169//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00006170// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00006171//===----------------------------------------------------------------------===//
6172
Richard Smith2e312c82012-03-03 22:46:17 +00006173static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006174 // In C, function designators are not lvalues, but we evaluate them as if they
6175 // are.
6176 if (E->isGLValue() || E->getType()->isFunctionType()) {
6177 LValue LV;
6178 if (!EvaluateLValue(E, LV, Info))
6179 return false;
6180 LV.moveInto(Result);
6181 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006182 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006183 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006184 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006185 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006186 return false;
John McCall45d55e42010-05-07 21:00:08 +00006187 } else if (E->getType()->hasPointerRepresentation()) {
6188 LValue LV;
6189 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006190 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006191 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00006192 } else if (E->getType()->isRealFloatingType()) {
6193 llvm::APFloat F(0.0);
6194 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006195 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006196 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00006197 } else if (E->getType()->isAnyComplexType()) {
6198 ComplexValue C;
6199 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006200 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006201 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00006202 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00006203 MemberPtr P;
6204 if (!EvaluateMemberPointer(E, P, Info))
6205 return false;
6206 P.moveInto(Result);
6207 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00006208 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006209 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006210 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006211 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00006212 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006213 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00006214 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006215 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006216 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006217 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6218 return false;
6219 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00006220 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006221 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006222 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00006223 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00006224 if (!EvaluateVoid(E, Info))
6225 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006226 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006227 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00006228 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006229 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006230 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00006231 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006232 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006233
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00006234 return true;
6235}
6236
Richard Smithb228a862012-02-15 02:18:13 +00006237/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6238/// cases, the in-place evaluation is essential, since later initializers for
6239/// an object can indirectly refer to subobjects which were initialized earlier.
6240static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6241 const Expr *E, CheckConstantExpressionKind CCEK,
6242 bool AllowNonLiteralTypes) {
Richard Smith6331c402012-02-13 22:16:19 +00006243 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00006244 return false;
6245
6246 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00006247 // Evaluate arrays and record types in-place, so that later initializers can
6248 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00006249 if (E->getType()->isArrayType())
6250 return EvaluateArray(E, This, Result, Info);
6251 else if (E->getType()->isRecordType())
6252 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00006253 }
6254
6255 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00006256 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00006257}
6258
Richard Smithf57d8cb2011-12-09 22:58:01 +00006259/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6260/// lvalue-to-rvalue cast if it is an lvalue.
6261static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00006262 if (!CheckLiteralType(Info, E))
6263 return false;
6264
Richard Smith2e312c82012-03-03 22:46:17 +00006265 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006266 return false;
6267
6268 if (E->isGLValue()) {
6269 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00006270 LV.setFrom(Info.Ctx, Result);
6271 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006272 return false;
6273 }
6274
Richard Smith2e312c82012-03-03 22:46:17 +00006275 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00006276 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006277}
Richard Smith11562c52011-10-28 17:51:58 +00006278
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006279static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
6280 const ASTContext &Ctx, bool &IsConst) {
6281 // Fast-path evaluations of integer literals, since we sometimes see files
6282 // containing vast quantities of these.
6283 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
6284 Result.Val = APValue(APSInt(L->getValue(),
6285 L->getType()->isUnsignedIntegerType()));
6286 IsConst = true;
6287 return true;
6288 }
6289
6290 // FIXME: Evaluating values of large array and record types can cause
6291 // performance problems. Only do so in C++11 for now.
6292 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
6293 Exp->getType()->isRecordType()) &&
6294 !Ctx.getLangOpts().CPlusPlus11) {
6295 IsConst = false;
6296 return true;
6297 }
6298 return false;
6299}
6300
6301
Richard Smith7b553f12011-10-29 00:50:52 +00006302/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00006303/// any crazy technique (that has nothing to do with language standards) that
6304/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00006305/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6306/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00006307bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006308 bool IsConst;
6309 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
6310 return IsConst;
6311
Richard Smithf57d8cb2011-12-09 22:58:01 +00006312 EvalInfo Info(Ctx, Result);
6313 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00006314}
6315
Jay Foad39c79802011-01-12 09:06:06 +00006316bool Expr::EvaluateAsBooleanCondition(bool &Result,
6317 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00006318 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00006319 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00006320 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00006321}
6322
Richard Smith5fab0c92011-12-28 19:48:30 +00006323bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6324 SideEffectsKind AllowSideEffects) const {
6325 if (!getType()->isIntegralOrEnumerationType())
6326 return false;
6327
Richard Smith11562c52011-10-28 17:51:58 +00006328 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00006329 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6330 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00006331 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006332
Richard Smith11562c52011-10-28 17:51:58 +00006333 Result = ExprResult.Val.getInt();
6334 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00006335}
6336
Jay Foad39c79802011-01-12 09:06:06 +00006337bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00006338 EvalInfo Info(Ctx, Result);
6339
John McCall45d55e42010-05-07 21:00:08 +00006340 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006341 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6342 !CheckLValueConstantExpression(Info, getExprLoc(),
6343 Ctx.getLValueReferenceType(getType()), LV))
6344 return false;
6345
Richard Smith2e312c82012-03-03 22:46:17 +00006346 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00006347 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00006348}
6349
Richard Smithd0b4dd62011-12-19 06:19:21 +00006350bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6351 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006352 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00006353 // FIXME: Evaluating initializers for large array and record types can cause
6354 // performance problems. Only do so in C++11 for now.
6355 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006356 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00006357 return false;
6358
Richard Smithd0b4dd62011-12-19 06:19:21 +00006359 Expr::EvalStatus EStatus;
6360 EStatus.Diag = &Notes;
6361
6362 EvalInfo InitInfo(Ctx, EStatus);
6363 InitInfo.setEvaluatingDecl(VD, Value);
6364
6365 LValue LVal;
6366 LVal.set(VD);
6367
Richard Smithfddd3842011-12-30 21:15:51 +00006368 // C++11 [basic.start.init]p2:
6369 // Variables with static storage duration or thread storage duration shall be
6370 // zero-initialized before any other initialization takes place.
6371 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006372 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00006373 !VD->getType()->isReferenceType()) {
6374 ImplicitValueInitExpr VIE(VD->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006375 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6376 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00006377 return false;
6378 }
6379
Richard Smithb228a862012-02-15 02:18:13 +00006380 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6381 /*AllowNonLiteralTypes=*/true) ||
6382 EStatus.HasSideEffects)
6383 return false;
6384
6385 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6386 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00006387}
6388
Richard Smith7b553f12011-10-29 00:50:52 +00006389/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6390/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00006391bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00006392 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00006393 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00006394}
Anders Carlsson59689ed2008-11-22 21:04:56 +00006395
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00006396APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006397 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006398 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00006399 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00006400 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00006401 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00006402 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006403 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00006404
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006405 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00006406}
John McCall864e3962010-05-07 05:32:02 +00006407
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006408void Expr::EvaluateForOverflow(const ASTContext &Ctx,
6409 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
6410 bool IsConst;
6411 EvalResult EvalResult;
6412 EvalResult.Diag = Diags;
6413 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
6414 EvalInfo Info(Ctx, EvalResult, true);
6415 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
6416 }
6417}
6418
Abramo Bagnaraf8199452010-05-14 17:07:14 +00006419 bool Expr::EvalResult::isGlobalLValue() const {
6420 assert(Val.isLValue());
6421 return IsGlobalLValue(Val.getLValueBase());
6422 }
6423
6424
John McCall864e3962010-05-07 05:32:02 +00006425/// isIntegerConstantExpr - this recursive routine will test if an expression is
6426/// an integer constant expression.
6427
6428/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6429/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00006430
6431// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00006432// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
6433// and a (possibly null) SourceLocation indicating the location of the problem.
6434//
John McCall864e3962010-05-07 05:32:02 +00006435// Note that to reduce code duplication, this helper does no evaluation
6436// itself; the caller checks whether the expression is evaluatable, and
6437// in the rare cases where CheckICE actually cares about the evaluated
6438// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00006439
Dan Gohman28ade552010-07-26 21:25:24 +00006440namespace {
6441
Richard Smith9e575da2012-12-28 13:25:52 +00006442enum ICEKind {
6443 /// This expression is an ICE.
6444 IK_ICE,
6445 /// This expression is not an ICE, but if it isn't evaluated, it's
6446 /// a legal subexpression for an ICE. This return value is used to handle
6447 /// the comma operator in C99 mode, and non-constant subexpressions.
6448 IK_ICEIfUnevaluated,
6449 /// This expression is not an ICE, and is not a legal subexpression for one.
6450 IK_NotICE
6451};
6452
John McCall864e3962010-05-07 05:32:02 +00006453struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00006454 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00006455 SourceLocation Loc;
6456
Richard Smith9e575da2012-12-28 13:25:52 +00006457 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00006458};
6459
Dan Gohman28ade552010-07-26 21:25:24 +00006460}
6461
Richard Smith9e575da2012-12-28 13:25:52 +00006462static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
6463
6464static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00006465
6466static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6467 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00006468 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00006469 !EVResult.Val.isInt())
6470 return ICEDiag(IK_NotICE, E->getLocStart());
6471
John McCall864e3962010-05-07 05:32:02 +00006472 return NoDiag();
6473}
6474
6475static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6476 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00006477 if (!E->getType()->isIntegralOrEnumerationType())
6478 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006479
6480 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00006481#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00006482#define STMT(Node, Base) case Expr::Node##Class:
6483#define EXPR(Node, Base)
6484#include "clang/AST/StmtNodes.inc"
6485 case Expr::PredefinedExprClass:
6486 case Expr::FloatingLiteralClass:
6487 case Expr::ImaginaryLiteralClass:
6488 case Expr::StringLiteralClass:
6489 case Expr::ArraySubscriptExprClass:
6490 case Expr::MemberExprClass:
6491 case Expr::CompoundAssignOperatorClass:
6492 case Expr::CompoundLiteralExprClass:
6493 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00006494 case Expr::DesignatedInitExprClass:
6495 case Expr::ImplicitValueInitExprClass:
6496 case Expr::ParenListExprClass:
6497 case Expr::VAArgExprClass:
6498 case Expr::AddrLabelExprClass:
6499 case Expr::StmtExprClass:
6500 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00006501 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00006502 case Expr::CXXDynamicCastExprClass:
6503 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00006504 case Expr::CXXUuidofExprClass:
John McCall864e3962010-05-07 05:32:02 +00006505 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00006506 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00006507 case Expr::CXXThisExprClass:
6508 case Expr::CXXThrowExprClass:
6509 case Expr::CXXNewExprClass:
6510 case Expr::CXXDeleteExprClass:
6511 case Expr::CXXPseudoDestructorExprClass:
6512 case Expr::UnresolvedLookupExprClass:
6513 case Expr::DependentScopeDeclRefExprClass:
6514 case Expr::CXXConstructExprClass:
6515 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00006516 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00006517 case Expr::CXXTemporaryObjectExprClass:
6518 case Expr::CXXUnresolvedConstructExprClass:
6519 case Expr::CXXDependentScopeMemberExprClass:
6520 case Expr::UnresolvedMemberExprClass:
6521 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00006522 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006523 case Expr::ObjCArrayLiteralClass:
6524 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00006525 case Expr::ObjCEncodeExprClass:
6526 case Expr::ObjCMessageExprClass:
6527 case Expr::ObjCSelectorExprClass:
6528 case Expr::ObjCProtocolExprClass:
6529 case Expr::ObjCIvarRefExprClass:
6530 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006531 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00006532 case Expr::ObjCIsaExprClass:
6533 case Expr::ShuffleVectorExprClass:
6534 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00006535 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00006536 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00006537 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00006538 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00006539 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00006540 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00006541 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00006542 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00006543 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00006544 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00006545 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00006546 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00006547 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00006548
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006549 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00006550 case Expr::GNUNullExprClass:
6551 // GCC considers the GNU __null value to be an integral constant expression.
6552 return NoDiag();
6553
John McCall7c454bb2011-07-15 05:09:51 +00006554 case Expr::SubstNonTypeTemplateParmExprClass:
6555 return
6556 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6557
John McCall864e3962010-05-07 05:32:02 +00006558 case Expr::ParenExprClass:
6559 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00006560 case Expr::GenericSelectionExprClass:
6561 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00006562 case Expr::IntegerLiteralClass:
6563 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006564 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00006565 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00006566 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00006567 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00006568 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00006569 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00006570 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00006571 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006572 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00006573 return NoDiag();
6574 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00006575 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00006576 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6577 // constant expressions, but they can never be ICEs because an ICE cannot
6578 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00006579 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006580 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00006581 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006582 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006583 }
Richard Smith6365c912012-02-24 22:12:32 +00006584 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00006585 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6586 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00006587 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006588 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00006589 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00006590 // Parameter variables are never constants. Without this check,
6591 // getAnyInitializer() can find a default argument, which leads
6592 // to chaos.
6593 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00006594 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00006595
6596 // C++ 7.1.5.1p2
6597 // A variable of non-volatile const-qualified integral or enumeration
6598 // type initialized by an ICE can be used in ICEs.
6599 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00006600 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00006601 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00006602
Richard Smithd0b4dd62011-12-19 06:19:21 +00006603 const VarDecl *VD;
6604 // Look for a declaration of this variable that has an initializer, and
6605 // check whether it is an ICE.
6606 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6607 return NoDiag();
6608 else
Richard Smith9e575da2012-12-28 13:25:52 +00006609 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00006610 }
6611 }
Richard Smith9e575da2012-12-28 13:25:52 +00006612 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00006613 }
John McCall864e3962010-05-07 05:32:02 +00006614 case Expr::UnaryOperatorClass: {
6615 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6616 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00006617 case UO_PostInc:
6618 case UO_PostDec:
6619 case UO_PreInc:
6620 case UO_PreDec:
6621 case UO_AddrOf:
6622 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00006623 // C99 6.6/3 allows increment and decrement within unevaluated
6624 // subexpressions of constant expressions, but they can never be ICEs
6625 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00006626 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00006627 case UO_Extension:
6628 case UO_LNot:
6629 case UO_Plus:
6630 case UO_Minus:
6631 case UO_Not:
6632 case UO_Real:
6633 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00006634 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00006635 }
Richard Smith9e575da2012-12-28 13:25:52 +00006636
John McCall864e3962010-05-07 05:32:02 +00006637 // OffsetOf falls through here.
6638 }
6639 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00006640 // Note that per C99, offsetof must be an ICE. And AFAIK, using
6641 // EvaluateAsRValue matches the proposed gcc behavior for cases like
6642 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
6643 // compliance: we should warn earlier for offsetof expressions with
6644 // array subscripts that aren't ICEs, and if the array subscripts
6645 // are ICEs, the value of the offsetof must be an integer constant.
6646 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00006647 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00006648 case Expr::UnaryExprOrTypeTraitExprClass: {
6649 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6650 if ((Exp->getKind() == UETT_SizeOf) &&
6651 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00006652 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006653 return NoDiag();
6654 }
6655 case Expr::BinaryOperatorClass: {
6656 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6657 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00006658 case BO_PtrMemD:
6659 case BO_PtrMemI:
6660 case BO_Assign:
6661 case BO_MulAssign:
6662 case BO_DivAssign:
6663 case BO_RemAssign:
6664 case BO_AddAssign:
6665 case BO_SubAssign:
6666 case BO_ShlAssign:
6667 case BO_ShrAssign:
6668 case BO_AndAssign:
6669 case BO_XorAssign:
6670 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00006671 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6672 // constant expressions, but they can never be ICEs because an ICE cannot
6673 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00006674 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006675
John McCalle3027922010-08-25 11:45:40 +00006676 case BO_Mul:
6677 case BO_Div:
6678 case BO_Rem:
6679 case BO_Add:
6680 case BO_Sub:
6681 case BO_Shl:
6682 case BO_Shr:
6683 case BO_LT:
6684 case BO_GT:
6685 case BO_LE:
6686 case BO_GE:
6687 case BO_EQ:
6688 case BO_NE:
6689 case BO_And:
6690 case BO_Xor:
6691 case BO_Or:
6692 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00006693 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6694 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00006695 if (Exp->getOpcode() == BO_Div ||
6696 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00006697 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00006698 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00006699 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00006700 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00006701 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00006702 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006703 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00006704 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00006705 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00006706 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006707 }
6708 }
6709 }
John McCalle3027922010-08-25 11:45:40 +00006710 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006711 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00006712 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6713 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00006714 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
6715 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006716 } else {
6717 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00006718 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006719 }
6720 }
Richard Smith9e575da2012-12-28 13:25:52 +00006721 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00006722 }
John McCalle3027922010-08-25 11:45:40 +00006723 case BO_LAnd:
6724 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00006725 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6726 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006727 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00006728 // Rare case where the RHS has a comma "side-effect"; we need
6729 // to actually check the condition to see whether the side
6730 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00006731 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00006732 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00006733 return RHSResult;
6734 return NoDiag();
6735 }
6736
Richard Smith9e575da2012-12-28 13:25:52 +00006737 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00006738 }
6739 }
6740 }
6741 case Expr::ImplicitCastExprClass:
6742 case Expr::CStyleCastExprClass:
6743 case Expr::CXXFunctionalCastExprClass:
6744 case Expr::CXXStaticCastExprClass:
6745 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00006746 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006747 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00006748 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00006749 if (isa<ExplicitCastExpr>(E)) {
6750 if (const FloatingLiteral *FL
6751 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6752 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6753 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6754 APSInt IgnoredVal(DestWidth, !DestSigned);
6755 bool Ignored;
6756 // If the value does not fit in the destination type, the behavior is
6757 // undefined, so we are not required to treat it as a constant
6758 // expression.
6759 if (FL->getValue().convertToInteger(IgnoredVal,
6760 llvm::APFloat::rmTowardZero,
6761 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00006762 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00006763 return NoDiag();
6764 }
6765 }
Eli Friedman76d4e432011-09-29 21:49:34 +00006766 switch (cast<CastExpr>(E)->getCastKind()) {
6767 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006768 case CK_AtomicToNonAtomic:
6769 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00006770 case CK_NoOp:
6771 case CK_IntegralToBoolean:
6772 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00006773 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00006774 default:
Richard Smith9e575da2012-12-28 13:25:52 +00006775 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00006776 }
John McCall864e3962010-05-07 05:32:02 +00006777 }
John McCallc07a0c72011-02-17 10:25:35 +00006778 case Expr::BinaryConditionalOperatorClass: {
6779 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6780 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006781 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00006782 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006783 if (FalseResult.Kind == IK_NotICE) return FalseResult;
6784 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
6785 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00006786 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00006787 return FalseResult;
6788 }
John McCall864e3962010-05-07 05:32:02 +00006789 case Expr::ConditionalOperatorClass: {
6790 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6791 // If the condition (ignoring parens) is a __builtin_constant_p call,
6792 // then only the true side is actually considered in an integer constant
6793 // expression, and it is fully evaluated. This is an important GNU
6794 // extension. See GCC PR38377 for discussion.
6795 if (const CallExpr *CallCE
6796 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00006797 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6798 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00006799 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006800 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00006801 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00006802
Richard Smithf57d8cb2011-12-09 22:58:01 +00006803 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6804 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00006805
Richard Smith9e575da2012-12-28 13:25:52 +00006806 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00006807 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00006808 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00006809 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00006810 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00006811 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00006812 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00006813 return NoDiag();
6814 // Rare case where the diagnostics depend on which side is evaluated
6815 // Note that if we get here, CondResult is 0, and at least one of
6816 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00006817 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00006818 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00006819 return TrueResult;
6820 }
6821 case Expr::CXXDefaultArgExprClass:
6822 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
6823 case Expr::ChooseExprClass: {
6824 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6825 }
6826 }
6827
David Blaikiee4d798f2012-01-20 21:50:17 +00006828 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00006829}
6830
Richard Smithf57d8cb2011-12-09 22:58:01 +00006831/// Evaluate an expression as a C++11 integral constant expression.
6832static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6833 const Expr *E,
6834 llvm::APSInt *Value,
6835 SourceLocation *Loc) {
6836 if (!E->getType()->isIntegralOrEnumerationType()) {
6837 if (Loc) *Loc = E->getExprLoc();
6838 return false;
6839 }
6840
Richard Smith66e05fe2012-01-18 05:21:49 +00006841 APValue Result;
6842 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00006843 return false;
6844
Richard Smith66e05fe2012-01-18 05:21:49 +00006845 assert(Result.isInt() && "pointer cast to int is not an ICE");
6846 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00006847 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006848}
6849
Richard Smith92b1ce02011-12-12 09:28:41 +00006850bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006851 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006852 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6853
Richard Smith9e575da2012-12-28 13:25:52 +00006854 ICEDiag D = CheckICE(this, Ctx);
6855 if (D.Kind != IK_ICE) {
6856 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00006857 return false;
6858 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006859 return true;
6860}
6861
6862bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6863 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006864 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006865 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6866
6867 if (!isIntegerConstantExpr(Ctx, Loc))
6868 return false;
6869 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00006870 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00006871 return true;
6872}
Richard Smith66e05fe2012-01-18 05:21:49 +00006873
Richard Smith98a0a492012-02-14 21:38:30 +00006874bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00006875 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00006876}
6877
Richard Smith66e05fe2012-01-18 05:21:49 +00006878bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6879 SourceLocation *Loc) const {
6880 // We support this checking in C++98 mode in order to diagnose compatibility
6881 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006882 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00006883
Richard Smith98a0a492012-02-14 21:38:30 +00006884 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00006885 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006886 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00006887 Status.Diag = &Diags;
6888 EvalInfo Info(Ctx, Status);
6889
6890 APValue Scratch;
6891 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6892
6893 if (!Diags.empty()) {
6894 IsConstExpr = false;
6895 if (Loc) *Loc = Diags[0].first;
6896 } else if (!IsConstExpr) {
6897 // FIXME: This shouldn't happen.
6898 if (Loc) *Loc = getExprLoc();
6899 }
6900
6901 return IsConstExpr;
6902}
Richard Smith253c2a32012-01-27 01:14:48 +00006903
6904bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006905 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00006906 PartialDiagnosticAt> &Diags) {
6907 // FIXME: It would be useful to check constexpr function templates, but at the
6908 // moment the constant expression evaluator cannot cope with the non-rigorous
6909 // ASTs which we build for dependent expressions.
6910 if (FD->isDependentContext())
6911 return true;
6912
6913 Expr::EvalStatus Status;
6914 Status.Diag = &Diags;
6915
6916 EvalInfo Info(FD->getASTContext(), Status);
6917 Info.CheckingPotentialConstantExpression = true;
6918
6919 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6920 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6921
6922 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6923 // is a temporary being used as the 'this' pointer.
6924 LValue This;
6925 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00006926 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00006927
Richard Smith253c2a32012-01-27 01:14:48 +00006928 ArrayRef<const Expr*> Args;
6929
6930 SourceLocation Loc = FD->getLocation();
6931
Richard Smith2e312c82012-03-03 22:46:17 +00006932 APValue Scratch;
6933 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith253c2a32012-01-27 01:14:48 +00006934 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith2e312c82012-03-03 22:46:17 +00006935 else
Richard Smith253c2a32012-01-27 01:14:48 +00006936 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6937 Args, FD->getBody(), Info, Scratch);
6938
6939 return Diags.empty();
6940}