blob: 4e468806dc4dbcf5f037e57af7d512c16e5ffc50 [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 Smith852c9db2013-04-20 22:23:05 +0000304 /// Temporarily override 'this'.
305 class ThisOverrideRAII {
306 public:
307 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
308 : Frame(Frame), OldThis(Frame.This) {
309 if (Enable)
310 Frame.This = NewThis;
311 }
312 ~ThisOverrideRAII() {
313 Frame.This = OldThis;
314 }
315 private:
316 CallStackFrame &Frame;
317 const LValue *OldThis;
318 };
319
Richard Smith92b1ce02011-12-12 09:28:41 +0000320 /// A partial diagnostic which we might know in advance that we are not going
321 /// to emit.
322 class OptionalDiagnostic {
323 PartialDiagnostic *Diag;
324
325 public:
326 explicit OptionalDiagnostic(PartialDiagnostic *Diag = 0) : Diag(Diag) {}
327
328 template<typename T>
329 OptionalDiagnostic &operator<<(const T &v) {
330 if (Diag)
331 *Diag << v;
332 return *this;
333 }
Richard Smithfe800032012-01-31 04:08:20 +0000334
335 OptionalDiagnostic &operator<<(const APSInt &I) {
336 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000337 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000338 I.toString(Buffer);
339 *Diag << StringRef(Buffer.data(), Buffer.size());
340 }
341 return *this;
342 }
343
344 OptionalDiagnostic &operator<<(const APFloat &F) {
345 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000346 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000347 F.toString(Buffer);
348 *Diag << StringRef(Buffer.data(), Buffer.size());
349 }
350 return *this;
351 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000352 };
353
Richard Smithb228a862012-02-15 02:18:13 +0000354 /// EvalInfo - This is a private struct used by the evaluator to capture
355 /// information about a subexpression as it is folded. It retains information
356 /// about the AST context, but also maintains information about the folded
357 /// expression.
358 ///
359 /// If an expression could be evaluated, it is still possible it is not a C
360 /// "integer constant expression" or constant expression. If not, this struct
361 /// captures information about how and why not.
362 ///
363 /// One bit of information passed *into* the request for constant folding
364 /// indicates whether the subexpression is "evaluated" or not according to C
365 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
366 /// evaluate the expression regardless of what the RHS is, but C only allows
367 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000368 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000369 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000370
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000371 /// EvalStatus - Contains information about the evaluation.
372 Expr::EvalStatus &EvalStatus;
373
374 /// CurrentCall - The top of the constexpr call stack.
375 CallStackFrame *CurrentCall;
376
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000377 /// CallStackDepth - The number of calls in the call stack right now.
378 unsigned CallStackDepth;
379
Richard Smithb228a862012-02-15 02:18:13 +0000380 /// NextCallIndex - The next call index to assign.
381 unsigned NextCallIndex;
382
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000383 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000384 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000385 CallStackFrame BottomFrame;
386
Richard Smithd62306a2011-11-10 06:34:14 +0000387 /// EvaluatingDecl - This is the declaration whose initializer is being
388 /// evaluated, if any.
389 const VarDecl *EvaluatingDecl;
390
391 /// EvaluatingDeclValue - This is the value being constructed for the
392 /// declaration whose initializer is being evaluated, if any.
393 APValue *EvaluatingDeclValue;
394
Richard Smith357362d2011-12-13 06:39:58 +0000395 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
396 /// notes attached to it will also be stored, otherwise they will not be.
397 bool HasActiveDiagnostic;
398
Richard Smith253c2a32012-01-27 01:14:48 +0000399 /// CheckingPotentialConstantExpression - Are we checking whether the
400 /// expression is a potential constant expression? If so, some diagnostics
401 /// are suppressed.
402 bool CheckingPotentialConstantExpression;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000403
404 bool IntOverflowCheckMode;
Richard Smith253c2a32012-01-27 01:14:48 +0000405
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000406 EvalInfo(const ASTContext &C, Expr::EvalStatus &S,
407 bool OverflowCheckMode=false)
Richard Smith92b1ce02011-12-12 09:28:41 +0000408 : Ctx(const_cast<ASTContext&>(C)), EvalStatus(S), CurrentCall(0),
Richard Smithb228a862012-02-15 02:18:13 +0000409 CallStackDepth(0), NextCallIndex(1),
410 BottomFrame(*this, SourceLocation(), 0, 0, 0),
Richard Smith253c2a32012-01-27 01:14:48 +0000411 EvaluatingDecl(0), EvaluatingDeclValue(0), HasActiveDiagnostic(false),
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000412 CheckingPotentialConstantExpression(false),
413 IntOverflowCheckMode(OverflowCheckMode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000414
Richard Smithd62306a2011-11-10 06:34:14 +0000415 void setEvaluatingDecl(const VarDecl *VD, APValue &Value) {
416 EvaluatingDecl = VD;
417 EvaluatingDeclValue = &Value;
418 }
419
David Blaikiebbafb8a2012-03-11 07:00:24 +0000420 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000421
Richard Smith357362d2011-12-13 06:39:58 +0000422 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000423 // Don't perform any constexpr calls (other than the call we're checking)
424 // when checking a potential constant expression.
425 if (CheckingPotentialConstantExpression && CallStackDepth > 1)
426 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000427 if (NextCallIndex == 0) {
428 // NextCallIndex has wrapped around.
429 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
430 return false;
431 }
Richard Smith357362d2011-12-13 06:39:58 +0000432 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
433 return true;
434 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
435 << getLangOpts().ConstexprCallDepth;
436 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000437 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000438
Richard Smithb228a862012-02-15 02:18:13 +0000439 CallStackFrame *getCallFrame(unsigned CallIndex) {
440 assert(CallIndex && "no call index in getCallFrame");
441 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
442 // be null in this loop.
443 CallStackFrame *Frame = CurrentCall;
444 while (Frame->Index > CallIndex)
445 Frame = Frame->Caller;
446 return (Frame->Index == CallIndex) ? Frame : 0;
447 }
448
Richard Smith357362d2011-12-13 06:39:58 +0000449 private:
450 /// Add a diagnostic to the diagnostics list.
451 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
452 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
453 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
454 return EvalStatus.Diag->back().second;
455 }
456
Richard Smithf6f003a2011-12-16 19:06:07 +0000457 /// Add notes containing a call stack to the current point of evaluation.
458 void addCallStack(unsigned Limit);
459
Richard Smith357362d2011-12-13 06:39:58 +0000460 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000461 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000462 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
463 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000464 unsigned ExtraNotes = 0) {
Richard Smithf57d8cb2011-12-09 22:58:01 +0000465 // If we have a prior diagnostic, it will be noting that the expression
466 // isn't a constant expression. This diagnostic is more important.
467 // FIXME: We might want to show both diagnostics to the user.
Richard Smith92b1ce02011-12-12 09:28:41 +0000468 if (EvalStatus.Diag) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000469 unsigned CallStackNotes = CallStackDepth - 1;
470 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
471 if (Limit)
472 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith253c2a32012-01-27 01:14:48 +0000473 if (CheckingPotentialConstantExpression)
474 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000475
Richard Smith357362d2011-12-13 06:39:58 +0000476 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000477 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000478 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
479 addDiag(Loc, DiagId);
Richard Smith253c2a32012-01-27 01:14:48 +0000480 if (!CheckingPotentialConstantExpression)
481 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000482 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000483 }
Richard Smith357362d2011-12-13 06:39:58 +0000484 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000485 return OptionalDiagnostic();
486 }
487
Richard Smithce1ec5e2012-03-15 04:53:45 +0000488 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
489 = diag::note_invalid_subexpr_in_const_expr,
490 unsigned ExtraNotes = 0) {
491 if (EvalStatus.Diag)
492 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
493 HasActiveDiagnostic = false;
494 return OptionalDiagnostic();
495 }
496
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000497 bool getIntOverflowCheckMode() { return IntOverflowCheckMode; }
498
Richard Smith92b1ce02011-12-12 09:28:41 +0000499 /// Diagnose that the evaluation does not produce a C++11 core constant
500 /// expression.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000501 template<typename LocArg>
502 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000503 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000504 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000505 // Don't override a previous diagnostic.
Eli Friedmanebea9af2012-02-21 22:41:33 +0000506 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
507 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000508 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000509 }
Richard Smith357362d2011-12-13 06:39:58 +0000510 return Diag(Loc, DiagId, ExtraNotes);
511 }
512
513 /// Add a note to a prior diagnostic.
514 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
515 if (!HasActiveDiagnostic)
516 return OptionalDiagnostic();
517 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000518 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000519
520 /// Add a stack of notes to a prior diagnostic.
521 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
522 if (HasActiveDiagnostic) {
523 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
524 Diags.begin(), Diags.end());
525 }
526 }
Richard Smith253c2a32012-01-27 01:14:48 +0000527
528 /// Should we continue evaluation as much as possible after encountering a
529 /// construct which can't be folded?
530 bool keepEvaluatingAfterFailure() {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000531 // Should return true in IntOverflowCheckMode, so that we check for
532 // overflow even if some subexpressions can't be evaluated as constants.
Fariborz Jahaniane735ff92013-01-24 22:11:45 +0000533 return IntOverflowCheckMode ||
534 (CheckingPotentialConstantExpression &&
535 EvalStatus.Diag && EvalStatus.Diag->empty());
Richard Smith253c2a32012-01-27 01:14:48 +0000536 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000537 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000538
539 /// Object used to treat all foldable expressions as constant expressions.
540 struct FoldConstant {
541 bool Enabled;
542
543 explicit FoldConstant(EvalInfo &Info)
544 : Enabled(Info.EvalStatus.Diag && Info.EvalStatus.Diag->empty() &&
545 !Info.EvalStatus.HasSideEffects) {
546 }
547 // Treat the value we've computed since this object was created as constant.
548 void Fold(EvalInfo &Info) {
549 if (Enabled && !Info.EvalStatus.Diag->empty() &&
550 !Info.EvalStatus.HasSideEffects)
551 Info.EvalStatus.Diag->clear();
552 }
553 };
Richard Smith17100ba2012-02-16 02:46:34 +0000554
555 /// RAII object used to suppress diagnostics and side-effects from a
556 /// speculative evaluation.
557 class SpeculativeEvaluationRAII {
558 EvalInfo &Info;
559 Expr::EvalStatus Old;
560
561 public:
562 SpeculativeEvaluationRAII(EvalInfo &Info,
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000563 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = 0)
Richard Smith17100ba2012-02-16 02:46:34 +0000564 : Info(Info), Old(Info.EvalStatus) {
565 Info.EvalStatus.Diag = NewDiag;
566 }
567 ~SpeculativeEvaluationRAII() {
568 Info.EvalStatus = Old;
569 }
570 };
Richard Smithf6f003a2011-12-16 19:06:07 +0000571}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000572
Richard Smitha8105bc2012-01-06 16:39:00 +0000573bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
574 CheckSubobjectKind CSK) {
575 if (Invalid)
576 return false;
577 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000578 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000579 << CSK;
580 setInvalid();
581 return false;
582 }
583 return true;
584}
585
586void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
587 const Expr *E, uint64_t N) {
588 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000589 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000590 << static_cast<int>(N) << /*array*/ 0
591 << static_cast<unsigned>(MostDerivedArraySize);
592 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000593 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000594 << static_cast<int>(N) << /*non-array*/ 1;
595 setInvalid();
596}
597
Richard Smithf6f003a2011-12-16 19:06:07 +0000598CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
599 const FunctionDecl *Callee, const LValue *This,
Richard Smith2e312c82012-03-03 22:46:17 +0000600 const APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000601 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000602 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000603 Info.CurrentCall = this;
604 ++Info.CallStackDepth;
605}
606
607CallStackFrame::~CallStackFrame() {
608 assert(Info.CurrentCall == this && "calls retired out of order");
609 --Info.CallStackDepth;
610 Info.CurrentCall = Caller;
611}
612
613/// Produce a string describing the given constexpr call.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000614static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000615 unsigned ArgIndex = 0;
616 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
Richard Smith74388b42012-02-04 00:33:54 +0000617 !isa<CXXConstructorDecl>(Frame->Callee) &&
618 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
Richard Smithf6f003a2011-12-16 19:06:07 +0000619
620 if (!IsMemberCall)
621 Out << *Frame->Callee << '(';
622
623 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
624 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
NAKAMURA Takumib8efa1e2012-01-26 09:37:36 +0000625 if (ArgIndex > (unsigned)IsMemberCall)
Richard Smithf6f003a2011-12-16 19:06:07 +0000626 Out << ", ";
627
628 const ParmVarDecl *Param = *I;
Richard Smith2e312c82012-03-03 22:46:17 +0000629 const APValue &Arg = Frame->Arguments[ArgIndex];
630 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
Richard Smithf6f003a2011-12-16 19:06:07 +0000631
632 if (ArgIndex == 0 && IsMemberCall)
633 Out << "->" << *Frame->Callee << '(';
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000634 }
635
Richard Smithf6f003a2011-12-16 19:06:07 +0000636 Out << ')';
637}
638
639void EvalInfo::addCallStack(unsigned Limit) {
640 // Determine which calls to skip, if any.
641 unsigned ActiveCalls = CallStackDepth - 1;
642 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
643 if (Limit && Limit < ActiveCalls) {
644 SkipStart = Limit / 2 + Limit % 2;
645 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000646 }
647
Richard Smithf6f003a2011-12-16 19:06:07 +0000648 // Walk the call stack and add the diagnostics.
649 unsigned CallIdx = 0;
650 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
651 Frame = Frame->Caller, ++CallIdx) {
652 // Skip this call?
653 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
654 if (CallIdx == SkipStart) {
655 // Note that we're skipping calls.
656 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
657 << unsigned(ActiveCalls - Limit);
658 }
659 continue;
660 }
661
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000662 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000663 llvm::raw_svector_ostream Out(Buffer);
664 describeCall(Frame, Out);
665 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
666 }
667}
668
669namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000670 struct ComplexValue {
671 private:
672 bool IsInt;
673
674 public:
675 APSInt IntReal, IntImag;
676 APFloat FloatReal, FloatImag;
677
678 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
679
680 void makeComplexFloat() { IsInt = false; }
681 bool isComplexFloat() const { return !IsInt; }
682 APFloat &getComplexFloatReal() { return FloatReal; }
683 APFloat &getComplexFloatImag() { return FloatImag; }
684
685 void makeComplexInt() { IsInt = true; }
686 bool isComplexInt() const { return IsInt; }
687 APSInt &getComplexIntReal() { return IntReal; }
688 APSInt &getComplexIntImag() { return IntImag; }
689
Richard Smith2e312c82012-03-03 22:46:17 +0000690 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000691 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000692 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000693 else
Richard Smith2e312c82012-03-03 22:46:17 +0000694 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000695 }
Richard Smith2e312c82012-03-03 22:46:17 +0000696 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000697 assert(v.isComplexFloat() || v.isComplexInt());
698 if (v.isComplexFloat()) {
699 makeComplexFloat();
700 FloatReal = v.getComplexFloatReal();
701 FloatImag = v.getComplexFloatImag();
702 } else {
703 makeComplexInt();
704 IntReal = v.getComplexIntReal();
705 IntImag = v.getComplexIntImag();
706 }
707 }
John McCall93d91dc2010-05-07 17:22:02 +0000708 };
John McCall45d55e42010-05-07 21:00:08 +0000709
710 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000711 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000712 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000713 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000714 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000715
Richard Smithce40ad62011-11-12 22:28:03 +0000716 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000717 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000718 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000719 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000720 SubobjectDesignator &getLValueDesignator() { return Designator; }
721 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000722
Richard Smith2e312c82012-03-03 22:46:17 +0000723 void moveInto(APValue &V) const {
724 if (Designator.Invalid)
725 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
726 else
727 V = APValue(Base, Offset, Designator.Entries,
728 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000729 }
Richard Smith2e312c82012-03-03 22:46:17 +0000730 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000731 assert(V.isLValue());
732 Base = V.getLValueBase();
733 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000734 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000735 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000736 }
737
Richard Smithb228a862012-02-15 02:18:13 +0000738 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000739 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000740 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000741 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000742 Designator = SubobjectDesignator(getType(B));
743 }
744
745 // Check that this LValue is not based on a null pointer. If it is, produce
746 // a diagnostic and mark the designator as invalid.
747 bool checkNullPointer(EvalInfo &Info, const Expr *E,
748 CheckSubobjectKind CSK) {
749 if (Designator.Invalid)
750 return false;
751 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000752 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000753 << CSK;
754 Designator.setInvalid();
755 return false;
756 }
757 return true;
758 }
759
760 // Check this LValue refers to an object. If not, set the designator to be
761 // invalid and emit a diagnostic.
762 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000763 // Outside C++11, do not build a designator referring to a subobject of
764 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000765 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000766 Designator.setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000767 return checkNullPointer(Info, E, CSK) &&
768 Designator.checkSubobject(Info, E, CSK);
769 }
770
771 void addDecl(EvalInfo &Info, const Expr *E,
772 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000773 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
774 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000775 }
776 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000777 if (checkSubobject(Info, E, CSK_ArrayToPointer))
778 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000779 }
Richard Smith66c96992012-02-18 22:04:06 +0000780 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000781 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
782 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000783 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000784 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000785 if (checkNullPointer(Info, E, CSK_ArrayIndex))
786 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000787 }
John McCall45d55e42010-05-07 21:00:08 +0000788 };
Richard Smith027bf112011-11-17 22:56:20 +0000789
790 struct MemberPtr {
791 MemberPtr() {}
792 explicit MemberPtr(const ValueDecl *Decl) :
793 DeclAndIsDerivedMember(Decl, false), Path() {}
794
795 /// The member or (direct or indirect) field referred to by this member
796 /// pointer, or 0 if this is a null member pointer.
797 const ValueDecl *getDecl() const {
798 return DeclAndIsDerivedMember.getPointer();
799 }
800 /// Is this actually a member of some type derived from the relevant class?
801 bool isDerivedMember() const {
802 return DeclAndIsDerivedMember.getInt();
803 }
804 /// Get the class which the declaration actually lives in.
805 const CXXRecordDecl *getContainingRecord() const {
806 return cast<CXXRecordDecl>(
807 DeclAndIsDerivedMember.getPointer()->getDeclContext());
808 }
809
Richard Smith2e312c82012-03-03 22:46:17 +0000810 void moveInto(APValue &V) const {
811 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +0000812 }
Richard Smith2e312c82012-03-03 22:46:17 +0000813 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +0000814 assert(V.isMemberPointer());
815 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
816 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
817 Path.clear();
818 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
819 Path.insert(Path.end(), P.begin(), P.end());
820 }
821
822 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
823 /// whether the member is a member of some class derived from the class type
824 /// of the member pointer.
825 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
826 /// Path - The path of base/derived classes from the member declaration's
827 /// class (exclusive) to the class type of the member pointer (inclusive).
828 SmallVector<const CXXRecordDecl*, 4> Path;
829
830 /// Perform a cast towards the class of the Decl (either up or down the
831 /// hierarchy).
832 bool castBack(const CXXRecordDecl *Class) {
833 assert(!Path.empty());
834 const CXXRecordDecl *Expected;
835 if (Path.size() >= 2)
836 Expected = Path[Path.size() - 2];
837 else
838 Expected = getContainingRecord();
839 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
840 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
841 // if B does not contain the original member and is not a base or
842 // derived class of the class containing the original member, the result
843 // of the cast is undefined.
844 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
845 // (D::*). We consider that to be a language defect.
846 return false;
847 }
848 Path.pop_back();
849 return true;
850 }
851 /// Perform a base-to-derived member pointer cast.
852 bool castToDerived(const CXXRecordDecl *Derived) {
853 if (!getDecl())
854 return true;
855 if (!isDerivedMember()) {
856 Path.push_back(Derived);
857 return true;
858 }
859 if (!castBack(Derived))
860 return false;
861 if (Path.empty())
862 DeclAndIsDerivedMember.setInt(false);
863 return true;
864 }
865 /// Perform a derived-to-base member pointer cast.
866 bool castToBase(const CXXRecordDecl *Base) {
867 if (!getDecl())
868 return true;
869 if (Path.empty())
870 DeclAndIsDerivedMember.setInt(true);
871 if (isDerivedMember()) {
872 Path.push_back(Base);
873 return true;
874 }
875 return castBack(Base);
876 }
877 };
Richard Smith357362d2011-12-13 06:39:58 +0000878
Richard Smith7bb00672012-02-01 01:42:44 +0000879 /// Compare two member pointers, which are assumed to be of the same type.
880 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
881 if (!LHS.getDecl() || !RHS.getDecl())
882 return !LHS.getDecl() && !RHS.getDecl();
883 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
884 return false;
885 return LHS.Path == RHS.Path;
886 }
887
Richard Smith357362d2011-12-13 06:39:58 +0000888 /// Kinds of constant expression checking, for diagnostics.
889 enum CheckConstantExpressionKind {
890 CCEK_Constant, ///< A normal constant.
891 CCEK_ReturnValue, ///< A constexpr function return value.
892 CCEK_MemberInit ///< A constexpr constructor mem-initializer.
893 };
John McCall93d91dc2010-05-07 17:22:02 +0000894}
Chris Lattnercdf34e72008-07-11 22:52:41 +0000895
Richard Smith2e312c82012-03-03 22:46:17 +0000896static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +0000897static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
898 const LValue &This, const Expr *E,
899 CheckConstantExpressionKind CCEK = CCEK_Constant,
900 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +0000901static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
902static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +0000903static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
904 EvalInfo &Info);
905static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +0000906static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +0000907static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +0000908 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +0000909static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +0000910static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +0000911
912//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +0000913// Misc utilities
914//===----------------------------------------------------------------------===//
915
Richard Smithd62306a2011-11-10 06:34:14 +0000916/// Should this call expression be treated as a string literal?
917static bool IsStringLiteralCall(const CallExpr *E) {
918 unsigned Builtin = E->isBuiltinCall();
919 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
920 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
921}
922
Richard Smithce40ad62011-11-12 22:28:03 +0000923static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +0000924 // C++11 [expr.const]p3 An address constant expression is a prvalue core
925 // constant expression of pointer type that evaluates to...
926
927 // ... a null pointer value, or a prvalue core constant expression of type
928 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +0000929 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +0000930
Richard Smithce40ad62011-11-12 22:28:03 +0000931 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
932 // ... the address of an object with static storage duration,
933 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
934 return VD->hasGlobalStorage();
935 // ... the address of a function,
936 return isa<FunctionDecl>(D);
937 }
938
939 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +0000940 switch (E->getStmtClass()) {
941 default:
942 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +0000943 case Expr::CompoundLiteralExprClass: {
944 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
945 return CLE->isFileScope() && CLE->isLValue();
946 }
Richard Smithd62306a2011-11-10 06:34:14 +0000947 // A string literal has static storage duration.
948 case Expr::StringLiteralClass:
949 case Expr::PredefinedExprClass:
950 case Expr::ObjCStringLiteralClass:
951 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +0000952 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +0000953 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +0000954 return true;
955 case Expr::CallExprClass:
956 return IsStringLiteralCall(cast<CallExpr>(E));
957 // For GCC compatibility, &&label has static storage duration.
958 case Expr::AddrLabelExprClass:
959 return true;
960 // A Block literal expression may be used as the initialization value for
961 // Block variables at global or local static scope.
962 case Expr::BlockExprClass:
963 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +0000964 case Expr::ImplicitValueInitExprClass:
965 // FIXME:
966 // We can never form an lvalue with an implicit value initialization as its
967 // base through expression evaluation, so these only appear in one case: the
968 // implicit variable declaration we invent when checking whether a constexpr
969 // constructor can produce a constant expression. We must assume that such
970 // an expression might be a global lvalue.
971 return true;
Richard Smithd62306a2011-11-10 06:34:14 +0000972 }
John McCall95007602010-05-10 23:27:23 +0000973}
974
Richard Smithb228a862012-02-15 02:18:13 +0000975static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
976 assert(Base && "no location for a null lvalue");
977 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
978 if (VD)
979 Info.Note(VD->getLocation(), diag::note_declared_at);
980 else
Ted Kremenek28831752012-08-23 20:46:57 +0000981 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +0000982 diag::note_constexpr_temporary_here);
983}
984
Richard Smith80815602011-11-07 05:07:52 +0000985/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +0000986/// value for an address or reference constant expression. Return true if we
987/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +0000988static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
989 QualType Type, const LValue &LVal) {
990 bool IsReferenceType = Type->isReferenceType();
991
Richard Smith357362d2011-12-13 06:39:58 +0000992 APValue::LValueBase Base = LVal.getLValueBase();
993 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
994
Richard Smith0dea49e2012-02-18 04:58:18 +0000995 // Check that the object is a global. Note that the fake 'this' object we
996 // manufacture when checking potential constant expressions is conservatively
997 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +0000998 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000999 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001000 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001001 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1002 << IsReferenceType << !Designator.Entries.empty()
1003 << !!VD << VD;
1004 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001005 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001006 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001007 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001008 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001009 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001010 }
Richard Smithb228a862012-02-15 02:18:13 +00001011 assert((Info.CheckingPotentialConstantExpression ||
1012 LVal.getLValueCallIndex() == 0) &&
1013 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001014
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001015 // Check if this is a thread-local variable.
1016 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1017 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
Richard Smithfd3834f2013-04-13 02:43:54 +00001018 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001019 return false;
1020 }
1021 }
1022
Richard Smitha8105bc2012-01-06 16:39:00 +00001023 // Allow address constant expressions to be past-the-end pointers. This is
1024 // an extension: the standard requires them to point to an object.
1025 if (!IsReferenceType)
1026 return true;
1027
1028 // A reference constant expression must refer to an object.
1029 if (!Base) {
1030 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001031 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001032 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001033 }
1034
Richard Smith357362d2011-12-13 06:39:58 +00001035 // Does this refer one past the end of some object?
Richard Smitha8105bc2012-01-06 16:39:00 +00001036 if (Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001037 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001038 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001039 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001040 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001041 }
1042
Richard Smith80815602011-11-07 05:07:52 +00001043 return true;
1044}
1045
Richard Smithfddd3842011-12-30 21:15:51 +00001046/// Check that this core constant expression is of literal type, and if not,
1047/// produce an appropriate diagnostic.
1048static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
1049 if (!E->isRValue() || E->getType()->isLiteralType())
1050 return true;
1051
1052 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001053 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001054 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001055 << E->getType();
1056 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001057 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001058 return false;
1059}
1060
Richard Smith0b0a0b62011-10-29 20:57:55 +00001061/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001062/// constant expression. If not, report an appropriate diagnostic. Does not
1063/// check that the expression is of literal type.
1064static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1065 QualType Type, const APValue &Value) {
1066 // Core issue 1454: For a literal constant expression of array or class type,
1067 // each subobject of its value shall have been initialized by a constant
1068 // expression.
1069 if (Value.isArray()) {
1070 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1071 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1072 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1073 Value.getArrayInitializedElt(I)))
1074 return false;
1075 }
1076 if (!Value.hasArrayFiller())
1077 return true;
1078 return CheckConstantExpression(Info, DiagLoc, EltTy,
1079 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001080 }
Richard Smithb228a862012-02-15 02:18:13 +00001081 if (Value.isUnion() && Value.getUnionField()) {
1082 return CheckConstantExpression(Info, DiagLoc,
1083 Value.getUnionField()->getType(),
1084 Value.getUnionValue());
1085 }
1086 if (Value.isStruct()) {
1087 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1088 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1089 unsigned BaseIndex = 0;
1090 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1091 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1092 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1093 Value.getStructBase(BaseIndex)))
1094 return false;
1095 }
1096 }
1097 for (RecordDecl::field_iterator I = RD->field_begin(), E = RD->field_end();
1098 I != E; ++I) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001099 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1100 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001101 return false;
1102 }
1103 }
1104
1105 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001106 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001107 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001108 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1109 }
1110
1111 // Everything else is fine.
1112 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001113}
1114
Richard Smith83c68212011-10-31 05:11:32 +00001115const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001116 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001117}
1118
1119static bool IsLiteralLValue(const LValue &Value) {
Richard Smithb228a862012-02-15 02:18:13 +00001120 return Value.Base.dyn_cast<const Expr*>() && !Value.CallIndex;
Richard Smith83c68212011-10-31 05:11:32 +00001121}
1122
Richard Smithcecf1842011-11-01 21:06:14 +00001123static bool IsWeakLValue(const LValue &Value) {
1124 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001125 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001126}
1127
Richard Smith2e312c82012-03-03 22:46:17 +00001128static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001129 // A null base expression indicates a null pointer. These are always
1130 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001131 if (!Value.getLValueBase()) {
1132 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001133 return true;
1134 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001135
Richard Smith027bf112011-11-17 22:56:20 +00001136 // We have a non-null base. These are generally known to be true, but if it's
1137 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001138 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001139 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001140 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001141}
1142
Richard Smith2e312c82012-03-03 22:46:17 +00001143static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001144 switch (Val.getKind()) {
1145 case APValue::Uninitialized:
1146 return false;
1147 case APValue::Int:
1148 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001149 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001150 case APValue::Float:
1151 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001152 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001153 case APValue::ComplexInt:
1154 Result = Val.getComplexIntReal().getBoolValue() ||
1155 Val.getComplexIntImag().getBoolValue();
1156 return true;
1157 case APValue::ComplexFloat:
1158 Result = !Val.getComplexFloatReal().isZero() ||
1159 !Val.getComplexFloatImag().isZero();
1160 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001161 case APValue::LValue:
1162 return EvalPointerValueAsBool(Val, Result);
1163 case APValue::MemberPointer:
1164 Result = Val.getMemberPointerDecl();
1165 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001166 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001167 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001168 case APValue::Struct:
1169 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001170 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001171 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001172 }
1173
Richard Smith11562c52011-10-28 17:51:58 +00001174 llvm_unreachable("unknown APValue kind");
1175}
1176
1177static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1178 EvalInfo &Info) {
1179 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001180 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001181 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001182 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001183 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001184}
1185
Richard Smith357362d2011-12-13 06:39:58 +00001186template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001187static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001188 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001189 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001190 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001191}
1192
1193static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1194 QualType SrcType, const APFloat &Value,
1195 QualType DestType, APSInt &Result) {
1196 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001197 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001198 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001199
Richard Smith357362d2011-12-13 06:39:58 +00001200 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001201 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001202 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1203 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001204 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001205 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001206}
1207
Richard Smith357362d2011-12-13 06:39:58 +00001208static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1209 QualType SrcType, QualType DestType,
1210 APFloat &Result) {
1211 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001212 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001213 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1214 APFloat::rmNearestTiesToEven, &ignored)
1215 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001216 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001217 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001218}
1219
Richard Smith911e1422012-01-30 22:27:01 +00001220static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1221 QualType DestType, QualType SrcType,
1222 APSInt &Value) {
1223 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001224 APSInt Result = Value;
1225 // Figure out if this is a truncate, extend or noop cast.
1226 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001227 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001228 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001229 return Result;
1230}
1231
Richard Smith357362d2011-12-13 06:39:58 +00001232static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1233 QualType SrcType, const APSInt &Value,
1234 QualType DestType, APFloat &Result) {
1235 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1236 if (Result.convertFromAPInt(Value, Value.isSigned(),
1237 APFloat::rmNearestTiesToEven)
1238 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001239 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001240 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001241}
1242
Eli Friedman803acb32011-12-22 03:51:45 +00001243static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1244 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001245 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001246 if (!Evaluate(SVal, Info, E))
1247 return false;
1248 if (SVal.isInt()) {
1249 Res = SVal.getInt();
1250 return true;
1251 }
1252 if (SVal.isFloat()) {
1253 Res = SVal.getFloat().bitcastToAPInt();
1254 return true;
1255 }
1256 if (SVal.isVector()) {
1257 QualType VecTy = E->getType();
1258 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1259 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1260 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1261 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1262 Res = llvm::APInt::getNullValue(VecSize);
1263 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1264 APValue &Elt = SVal.getVectorElt(i);
1265 llvm::APInt EltAsInt;
1266 if (Elt.isInt()) {
1267 EltAsInt = Elt.getInt();
1268 } else if (Elt.isFloat()) {
1269 EltAsInt = Elt.getFloat().bitcastToAPInt();
1270 } else {
1271 // Don't try to handle vectors of anything other than int or float
1272 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001273 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001274 return false;
1275 }
1276 unsigned BaseEltSize = EltAsInt.getBitWidth();
1277 if (BigEndian)
1278 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1279 else
1280 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1281 }
1282 return true;
1283 }
1284 // Give up if the input isn't an int, float, or vector. For example, we
1285 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001286 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001287 return false;
1288}
1289
Richard Smitha8105bc2012-01-06 16:39:00 +00001290/// Cast an lvalue referring to a base subobject to a derived class, by
1291/// truncating the lvalue's path to the given length.
1292static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1293 const RecordDecl *TruncatedType,
1294 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001295 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001296
1297 // Check we actually point to a derived class object.
1298 if (TruncatedElements == D.Entries.size())
1299 return true;
1300 assert(TruncatedElements >= D.MostDerivedPathLength &&
1301 "not casting to a derived class");
1302 if (!Result.checkSubobject(Info, E, CSK_Derived))
1303 return false;
1304
1305 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001306 const RecordDecl *RD = TruncatedType;
1307 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001308 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001309 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1310 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001311 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001312 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001313 else
Richard Smithd62306a2011-11-10 06:34:14 +00001314 Result.Offset -= Layout.getBaseClassOffset(Base);
1315 RD = Base;
1316 }
Richard Smith027bf112011-11-17 22:56:20 +00001317 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001318 return true;
1319}
1320
John McCalld7bca762012-05-01 00:38:49 +00001321static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001322 const CXXRecordDecl *Derived,
1323 const CXXRecordDecl *Base,
1324 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001325 if (!RL) {
1326 if (Derived->isInvalidDecl()) return false;
1327 RL = &Info.Ctx.getASTRecordLayout(Derived);
1328 }
1329
Richard Smithd62306a2011-11-10 06:34:14 +00001330 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001331 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001332 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001333}
1334
Richard Smitha8105bc2012-01-06 16:39:00 +00001335static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001336 const CXXRecordDecl *DerivedDecl,
1337 const CXXBaseSpecifier *Base) {
1338 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1339
John McCalld7bca762012-05-01 00:38:49 +00001340 if (!Base->isVirtual())
1341 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001342
Richard Smitha8105bc2012-01-06 16:39:00 +00001343 SubobjectDesignator &D = Obj.Designator;
1344 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001345 return false;
1346
Richard Smitha8105bc2012-01-06 16:39:00 +00001347 // Extract most-derived object and corresponding type.
1348 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1349 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1350 return false;
1351
1352 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001353 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001354 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1355 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001356 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001357 return true;
1358}
1359
1360/// Update LVal to refer to the given field, which must be a member of the type
1361/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001362static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001363 const FieldDecl *FD,
1364 const ASTRecordLayout *RL = 0) {
John McCalld7bca762012-05-01 00:38:49 +00001365 if (!RL) {
1366 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001367 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001368 }
Richard Smithd62306a2011-11-10 06:34:14 +00001369
1370 unsigned I = FD->getFieldIndex();
1371 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001372 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001373 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001374}
1375
Richard Smith1b78b3d2012-01-25 22:15:11 +00001376/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001377static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001378 LValue &LVal,
1379 const IndirectFieldDecl *IFD) {
1380 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
1381 CE = IFD->chain_end(); C != CE; ++C)
John McCalld7bca762012-05-01 00:38:49 +00001382 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(*C)))
1383 return false;
1384 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001385}
1386
Richard Smithd62306a2011-11-10 06:34:14 +00001387/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001388static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1389 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001390 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1391 // extension.
1392 if (Type->isVoidType() || Type->isFunctionType()) {
1393 Size = CharUnits::One();
1394 return true;
1395 }
1396
1397 if (!Type->isConstantSizeType()) {
1398 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001399 // FIXME: Better diagnostic.
1400 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001401 return false;
1402 }
1403
1404 Size = Info.Ctx.getTypeSizeInChars(Type);
1405 return true;
1406}
1407
1408/// Update a pointer value to model pointer arithmetic.
1409/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001410/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001411/// \param LVal - The pointer value to be updated.
1412/// \param EltTy - The pointee type represented by LVal.
1413/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001414static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1415 LValue &LVal, QualType EltTy,
1416 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001417 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001418 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001419 return false;
1420
1421 // Compute the new offset in the appropriate width.
1422 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001423 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001424 return true;
1425}
1426
Richard Smith66c96992012-02-18 22:04:06 +00001427/// Update an lvalue to refer to a component of a complex number.
1428/// \param Info - Information about the ongoing evaluation.
1429/// \param LVal - The lvalue to be updated.
1430/// \param EltTy - The complex number's component type.
1431/// \param Imag - False for the real component, true for the imaginary.
1432static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1433 LValue &LVal, QualType EltTy,
1434 bool Imag) {
1435 if (Imag) {
1436 CharUnits SizeOfComponent;
1437 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1438 return false;
1439 LVal.Offset += SizeOfComponent;
1440 }
1441 LVal.addComplex(Info, E, EltTy, Imag);
1442 return true;
1443}
1444
Richard Smith27908702011-10-24 17:54:18 +00001445/// Try to evaluate the initializer for a variable declaration.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001446static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1447 const VarDecl *VD,
Richard Smith2e312c82012-03-03 22:46:17 +00001448 CallStackFrame *Frame, APValue &Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001449 // If this is a parameter to an active constexpr function call, perform
1450 // argument substitution.
1451 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001452 // Assume arguments of a potential constant expression are unknown
1453 // constant expressions.
1454 if (Info.CheckingPotentialConstantExpression)
1455 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001456 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001457 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001458 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001459 }
Richard Smithfec09922011-11-01 16:57:24 +00001460 Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
1461 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001462 }
Richard Smith27908702011-10-24 17:54:18 +00001463
Richard Smithd0b4dd62011-12-19 06:19:21 +00001464 // Dig out the initializer, and use the declaration which it's attached to.
1465 const Expr *Init = VD->getAnyInitializer(VD);
1466 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001467 // If we're checking a potential constant expression, the variable could be
1468 // initialized later.
1469 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001470 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001471 return false;
1472 }
1473
Richard Smithd62306a2011-11-10 06:34:14 +00001474 // If we're currently evaluating the initializer of this declaration, use that
1475 // in-flight value.
1476 if (Info.EvaluatingDecl == VD) {
Richard Smith2e312c82012-03-03 22:46:17 +00001477 Result = *Info.EvaluatingDeclValue;
Richard Smithd62306a2011-11-10 06:34:14 +00001478 return !Result.isUninit();
1479 }
1480
Richard Smithcecf1842011-11-01 21:06:14 +00001481 // Never evaluate the initializer of a weak variable. We can't be sure that
1482 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001483 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001484 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001485 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001486 }
Richard Smithcecf1842011-11-01 21:06:14 +00001487
Richard Smithd0b4dd62011-12-19 06:19:21 +00001488 // Check that we can fold the initializer. In C++, we will have already done
1489 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001490 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001491 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001492 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001493 Notes.size() + 1) << VD;
1494 Info.Note(VD->getLocation(), diag::note_declared_at);
1495 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001496 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001497 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001498 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001499 Notes.size() + 1) << VD;
1500 Info.Note(VD->getLocation(), diag::note_declared_at);
1501 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001502 }
Richard Smith27908702011-10-24 17:54:18 +00001503
Richard Smith2e312c82012-03-03 22:46:17 +00001504 Result = *VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001505 return true;
Richard Smith27908702011-10-24 17:54:18 +00001506}
1507
Richard Smith11562c52011-10-28 17:51:58 +00001508static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00001509 Qualifiers Quals = T.getQualifiers();
1510 return Quals.hasConst() && !Quals.hasVolatile();
1511}
1512
Richard Smithe97cbd72011-11-11 04:05:33 +00001513/// Get the base index of the given base class within an APValue representing
1514/// the given derived class.
1515static unsigned getBaseIndex(const CXXRecordDecl *Derived,
1516 const CXXRecordDecl *Base) {
1517 Base = Base->getCanonicalDecl();
1518 unsigned Index = 0;
1519 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
1520 E = Derived->bases_end(); I != E; ++I, ++Index) {
1521 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
1522 return Index;
1523 }
1524
1525 llvm_unreachable("base class missing from derived class's bases list");
1526}
1527
Richard Smith9ec1e482012-04-15 02:50:59 +00001528/// Extract the value of a character from a string literal. CharType is used to
1529/// determine the expected signedness of the result -- a string literal used to
1530/// initialize an array of 'signed char' or 'unsigned char' might contain chars
1531/// of the wrong signedness.
Richard Smith14a94132012-02-17 03:35:37 +00001532static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
Richard Smith9ec1e482012-04-15 02:50:59 +00001533 uint64_t Index, QualType CharType) {
Richard Smith14a94132012-02-17 03:35:37 +00001534 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
1535 const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
1536 assert(S && "unexpected string literal expression kind");
Richard Smith9ec1e482012-04-15 02:50:59 +00001537 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00001538
1539 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00001540 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00001541 if (Index < S->getLength())
1542 Value = S->getCodeUnit(Index);
1543 return Value;
1544}
1545
Richard Smithf3e9e432011-11-07 09:22:26 +00001546/// Extract the designated sub-object of an rvalue.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001547static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith2e312c82012-03-03 22:46:17 +00001548 APValue &Obj, QualType ObjType,
Richard Smithf3e9e432011-11-07 09:22:26 +00001549 const SubobjectDesignator &Sub, QualType SubType) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001550 if (Sub.Invalid)
1551 // A diagnostic will have already been produced.
Richard Smithf3e9e432011-11-07 09:22:26 +00001552 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00001553 if (Sub.isOnePastTheEnd()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001554 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001555 (unsigned)diag::note_constexpr_read_past_end :
1556 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001557 return false;
1558 }
Richard Smith6804be52011-11-11 08:28:03 +00001559 if (Sub.Entries.empty())
Richard Smithf3e9e432011-11-07 09:22:26 +00001560 return true;
Richard Smith253c2a32012-01-27 01:14:48 +00001561 if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
1562 // This object might be initialized later.
1563 return false;
Richard Smithf3e9e432011-11-07 09:22:26 +00001564
Richard Smith4e9e5232012-03-10 00:28:11 +00001565 APValue *O = &Obj;
Richard Smithd62306a2011-11-10 06:34:14 +00001566 // Walk the designator's path to find the subobject.
Richard Smithf3e9e432011-11-07 09:22:26 +00001567 for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
Richard Smithf3e9e432011-11-07 09:22:26 +00001568 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00001569 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00001570 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001571 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00001572 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001573 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00001574 // Note, it should not be possible to form a pointer with a valid
1575 // designator which points more than one past the end of the array.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001576 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Matt Beaumont-Gay4a39e492011-12-21 19:36:37 +00001577 (unsigned)diag::note_constexpr_read_past_end :
1578 (unsigned)diag::note_invalid_subexpr_in_const_expr);
Richard Smithf3e9e432011-11-07 09:22:26 +00001579 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001580 }
Richard Smith14a94132012-02-17 03:35:37 +00001581 // An array object is represented as either an Array APValue or as an
1582 // LValue which refers to a string literal.
1583 if (O->isLValue()) {
1584 assert(I == N - 1 && "extracting subobject of character?");
1585 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith2e312c82012-03-03 22:46:17 +00001586 Obj = APValue(ExtractStringLiteralCharacter(
Richard Smith9ec1e482012-04-15 02:50:59 +00001587 Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
Richard Smith14a94132012-02-17 03:35:37 +00001588 return true;
1589 } else if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00001590 O = &O->getArrayInitializedElt(Index);
1591 else
1592 O = &O->getArrayFiller();
1593 ObjType = CAT->getElementType();
Richard Smith66c96992012-02-18 22:04:06 +00001594 } else if (ObjType->isAnyComplexType()) {
1595 // Next subobject is a complex number.
1596 uint64_t Index = Sub.Entries[I].ArrayIndex;
1597 if (Index > 1) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001598 Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
Richard Smith66c96992012-02-18 22:04:06 +00001599 (unsigned)diag::note_constexpr_read_past_end :
1600 (unsigned)diag::note_invalid_subexpr_in_const_expr);
1601 return false;
1602 }
1603 assert(I == N - 1 && "extracting subobject of scalar?");
1604 if (O->isComplexInt()) {
Richard Smith2e312c82012-03-03 22:46:17 +00001605 Obj = APValue(Index ? O->getComplexIntImag()
Richard Smith66c96992012-02-18 22:04:06 +00001606 : O->getComplexIntReal());
1607 } else {
1608 assert(O->isComplexFloat());
Richard Smith2e312c82012-03-03 22:46:17 +00001609 Obj = APValue(Index ? O->getComplexFloatImag()
Richard Smith66c96992012-02-18 22:04:06 +00001610 : O->getComplexFloatReal());
1611 }
1612 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001613 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith5a294e62012-02-09 03:29:58 +00001614 if (Field->isMutable()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001615 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00001616 << Field;
1617 Info.Note(Field->getLocation(), diag::note_declared_at);
1618 return false;
1619 }
1620
Richard Smithd62306a2011-11-10 06:34:14 +00001621 // Next subobject is a class, struct or union field.
1622 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
1623 if (RD->isUnion()) {
1624 const FieldDecl *UnionField = O->getUnionField();
1625 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00001626 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001627 Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
Richard Smithf2b681b2011-12-21 05:04:46 +00001628 << Field << !UnionField << UnionField;
Richard Smithd62306a2011-11-10 06:34:14 +00001629 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001630 }
Richard Smithd62306a2011-11-10 06:34:14 +00001631 O = &O->getUnionValue();
1632 } else
1633 O = &O->getStructField(Field->getFieldIndex());
1634 ObjType = Field->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001635
1636 if (ObjType.isVolatileQualified()) {
1637 if (Info.getLangOpts().CPlusPlus) {
1638 // FIXME: Include a description of the path to the volatile subobject.
Richard Smithce1ec5e2012-03-15 04:53:45 +00001639 Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
Richard Smithf2b681b2011-12-21 05:04:46 +00001640 << 2 << Field;
1641 Info.Note(Field->getLocation(), diag::note_declared_at);
1642 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001643 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001644 }
1645 return false;
1646 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001647 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00001648 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00001649 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
1650 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
1651 O = &O->getStructBase(getBaseIndex(Derived, Base));
1652 ObjType = Info.Ctx.getRecordType(Base);
Richard Smithf3e9e432011-11-07 09:22:26 +00001653 }
Richard Smithd62306a2011-11-10 06:34:14 +00001654
Richard Smithf57d8cb2011-12-09 22:58:01 +00001655 if (O->isUninit()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001656 if (!Info.CheckingPotentialConstantExpression)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001657 Info.Diag(E, diag::note_constexpr_read_uninit);
Richard Smithd62306a2011-11-10 06:34:14 +00001658 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001659 }
Richard Smithf3e9e432011-11-07 09:22:26 +00001660 }
1661
Richard Smith4e9e5232012-03-10 00:28:11 +00001662 // This may look super-stupid, but it serves an important purpose: if we just
1663 // swapped Obj and *O, we'd create an object which had itself as a subobject.
1664 // To avoid the leak, we ensure that Tmp ends up owning the original complete
1665 // object, which is destroyed by Tmp's destructor.
1666 APValue Tmp;
1667 O->swap(Tmp);
1668 Obj.swap(Tmp);
Richard Smithf3e9e432011-11-07 09:22:26 +00001669 return true;
1670}
1671
Richard Smith84f6dcf2012-02-02 01:16:57 +00001672/// Find the position where two subobject designators diverge, or equivalently
1673/// the length of the common initial subsequence.
1674static unsigned FindDesignatorMismatch(QualType ObjType,
1675 const SubobjectDesignator &A,
1676 const SubobjectDesignator &B,
1677 bool &WasArrayIndex) {
1678 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
1679 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00001680 if (!ObjType.isNull() &&
1681 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00001682 // Next subobject is an array element.
1683 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
1684 WasArrayIndex = true;
1685 return I;
1686 }
Richard Smith66c96992012-02-18 22:04:06 +00001687 if (ObjType->isAnyComplexType())
1688 ObjType = ObjType->castAs<ComplexType>()->getElementType();
1689 else
1690 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00001691 } else {
1692 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
1693 WasArrayIndex = false;
1694 return I;
1695 }
1696 if (const FieldDecl *FD = getAsField(A.Entries[I]))
1697 // Next subobject is a field.
1698 ObjType = FD->getType();
1699 else
1700 // Next subobject is a base class.
1701 ObjType = QualType();
1702 }
1703 }
1704 WasArrayIndex = false;
1705 return I;
1706}
1707
1708/// Determine whether the given subobject designators refer to elements of the
1709/// same array object.
1710static bool AreElementsOfSameArray(QualType ObjType,
1711 const SubobjectDesignator &A,
1712 const SubobjectDesignator &B) {
1713 if (A.Entries.size() != B.Entries.size())
1714 return false;
1715
1716 bool IsArray = A.MostDerivedArraySize != 0;
1717 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
1718 // A is a subobject of the array element.
1719 return false;
1720
1721 // If A (and B) designates an array element, the last entry will be the array
1722 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
1723 // of length 1' case, and the entire path must match.
1724 bool WasArrayIndex;
1725 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
1726 return CommonLength >= A.Entries.size() - IsArray;
1727}
1728
Richard Smithd62306a2011-11-10 06:34:14 +00001729/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
1730/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
1731/// for looking up the glvalue referred to by an entity of reference type.
1732///
1733/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001734/// \param Conv - The expression for which we are performing the conversion.
1735/// Used for diagnostics.
Richard Smithc82fae62012-02-05 01:23:16 +00001736/// \param Type - The type we expect this conversion to produce, before
1737/// stripping cv-qualifiers in the case of a non-clas type.
Richard Smithd62306a2011-11-10 06:34:14 +00001738/// \param LVal - The glvalue on which we are attempting to perform this action.
1739/// \param RVal - The produced value will be placed here.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001740static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
1741 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00001742 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00001743 if (LVal.Designator.Invalid)
1744 // A diagnostic will have already been produced.
1745 return false;
1746
Richard Smithce40ad62011-11-12 22:28:03 +00001747 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith11562c52011-10-28 17:51:58 +00001748
Richard Smithf57d8cb2011-12-09 22:58:01 +00001749 if (!LVal.Base) {
1750 // FIXME: Indirection through a null pointer deserves a specific diagnostic.
Richard Smithce1ec5e2012-03-15 04:53:45 +00001751 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00001752 return false;
1753 }
1754
Richard Smithb228a862012-02-15 02:18:13 +00001755 CallStackFrame *Frame = 0;
1756 if (LVal.CallIndex) {
1757 Frame = Info.getCallFrame(LVal.CallIndex);
1758 if (!Frame) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001759 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smithb228a862012-02-15 02:18:13 +00001760 NoteLValueLocation(Info, LVal.Base);
1761 return false;
1762 }
1763 }
1764
Richard Smithf2b681b2011-12-21 05:04:46 +00001765 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
1766 // is not a constant expression (even if the object is non-volatile). We also
1767 // apply this rule to C++98, in order to conform to the expected 'volatile'
1768 // semantics.
1769 if (Type.isVolatileQualified()) {
1770 if (Info.getLangOpts().CPlusPlus)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001771 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
Richard Smithf2b681b2011-12-21 05:04:46 +00001772 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001773 Info.Diag(Conv);
Richard Smith11562c52011-10-28 17:51:58 +00001774 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001775 }
Richard Smith11562c52011-10-28 17:51:58 +00001776
Richard Smithce40ad62011-11-12 22:28:03 +00001777 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
Richard Smith11562c52011-10-28 17:51:58 +00001778 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
1779 // In C++11, constexpr, non-volatile variables initialized with constant
Richard Smith254a73d2011-10-28 22:34:42 +00001780 // expressions are constant expressions too. Inside constexpr functions,
1781 // parameters are constant expressions even if they're non-const.
Richard Smith11562c52011-10-28 17:51:58 +00001782 // In C, such things can also be folded, although they are not ICEs.
Richard Smith11562c52011-10-28 17:51:58 +00001783 const VarDecl *VD = dyn_cast<VarDecl>(D);
Douglas Gregor31f55dc2012-04-06 22:40:38 +00001784 if (VD) {
1785 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
1786 VD = VDef;
1787 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00001788 if (!VD || VD->isInvalidDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001789 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00001790 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001791 }
1792
Richard Smithf2b681b2011-12-21 05:04:46 +00001793 // DR1313: If the object is volatile-qualified but the glvalue was not,
1794 // behavior is undefined so the result is not a constant expression.
Richard Smithce40ad62011-11-12 22:28:03 +00001795 QualType VT = VD->getType();
Richard Smithf2b681b2011-12-21 05:04:46 +00001796 if (VT.isVolatileQualified()) {
1797 if (Info.getLangOpts().CPlusPlus) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001798 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001799 Info.Note(VD->getLocation(), diag::note_declared_at);
1800 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001801 Info.Diag(Conv);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001802 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001803 return false;
1804 }
1805
1806 if (!isa<ParmVarDecl>(VD)) {
1807 if (VD->isConstexpr()) {
1808 // OK, we can read this variable.
1809 } else if (VT->isIntegralOrEnumerationType()) {
1810 if (!VT.isConstQualified()) {
1811 if (Info.getLangOpts().CPlusPlus) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001812 Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001813 Info.Note(VD->getLocation(), diag::note_declared_at);
1814 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001815 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001816 }
1817 return false;
1818 }
1819 } else if (VT->isFloatingType() && VT.isConstQualified()) {
1820 // We support folding of const floating-point types, in order to make
1821 // static const data members of such types (supported as an extension)
1822 // more useful.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001823 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001824 Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001825 Info.Note(VD->getLocation(), diag::note_declared_at);
1826 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001827 Info.CCEDiag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001828 }
1829 } else {
1830 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001831 if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001832 Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smithf2b681b2011-12-21 05:04:46 +00001833 Info.Note(VD->getLocation(), diag::note_declared_at);
1834 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001835 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001836 }
Richard Smith96e0c102011-11-04 02:25:55 +00001837 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001838 }
Richard Smith96e0c102011-11-04 02:25:55 +00001839 }
Richard Smithf2b681b2011-12-21 05:04:46 +00001840
Richard Smithf57d8cb2011-12-09 22:58:01 +00001841 if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
Richard Smith11562c52011-10-28 17:51:58 +00001842 return false;
1843
Richard Smith0b0a0b62011-10-29 20:57:55 +00001844 if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
Richard Smithf57d8cb2011-12-09 22:58:01 +00001845 return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
Richard Smith11562c52011-10-28 17:51:58 +00001846
1847 // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
1848 // conversion. This happens when the declaration and the lvalue should be
1849 // considered synonymous, for instance when initializing an array of char
1850 // from a string literal. Continue as if the initializer lvalue was the
1851 // value we were originally given.
Richard Smith96e0c102011-11-04 02:25:55 +00001852 assert(RVal.getLValueOffset().isZero() &&
1853 "offset for lvalue init of non-reference");
Richard Smithce40ad62011-11-12 22:28:03 +00001854 Base = RVal.getLValueBase().get<const Expr*>();
Richard Smithb228a862012-02-15 02:18:13 +00001855
1856 if (unsigned CallIndex = RVal.getLValueCallIndex()) {
1857 Frame = Info.getCallFrame(CallIndex);
1858 if (!Frame) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001859 Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
Richard Smithb228a862012-02-15 02:18:13 +00001860 NoteLValueLocation(Info, RVal.getLValueBase());
1861 return false;
1862 }
1863 } else {
1864 Frame = 0;
1865 }
Richard Smith11562c52011-10-28 17:51:58 +00001866 }
1867
Richard Smithf2b681b2011-12-21 05:04:46 +00001868 // Volatile temporary objects cannot be read in constant expressions.
1869 if (Base->getType().isVolatileQualified()) {
1870 if (Info.getLangOpts().CPlusPlus) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001871 Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
Richard Smithf2b681b2011-12-21 05:04:46 +00001872 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
1873 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001874 Info.Diag(Conv);
Richard Smithf2b681b2011-12-21 05:04:46 +00001875 }
1876 return false;
1877 }
1878
Richard Smithf3e9e432011-11-07 09:22:26 +00001879 if (Frame) {
1880 // If this is a temporary expression with a nontrivial initializer, grab the
1881 // value from the relevant stack frame.
1882 RVal = Frame->Temporaries[Base];
1883 } else if (const CompoundLiteralExpr *CLE
1884 = dyn_cast<CompoundLiteralExpr>(Base)) {
1885 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
1886 // initializer until now for such expressions. Such an expression can't be
1887 // an ICE in C, so this only matters for fold.
1888 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
1889 if (!Evaluate(RVal, Info, CLE->getInitializer()))
1890 return false;
Richard Smith14a94132012-02-17 03:35:37 +00001891 } else if (isa<StringLiteral>(Base)) {
1892 // We represent a string literal array as an lvalue pointing at the
1893 // corresponding expression, rather than building an array of chars.
1894 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith2e312c82012-03-03 22:46:17 +00001895 RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001896 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001897 Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
Richard Smith96e0c102011-11-04 02:25:55 +00001898 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001899 }
Richard Smith96e0c102011-11-04 02:25:55 +00001900
Richard Smithf57d8cb2011-12-09 22:58:01 +00001901 return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
1902 Type);
Richard Smith11562c52011-10-28 17:51:58 +00001903}
1904
Richard Smithe97cbd72011-11-11 04:05:33 +00001905/// Build an lvalue for the object argument of a member function call.
1906static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
1907 LValue &This) {
1908 if (Object->getType()->isPointerType())
1909 return EvaluatePointer(Object, This, Info);
1910
1911 if (Object->isGLValue())
1912 return EvaluateLValue(Object, This, Info);
1913
Richard Smith027bf112011-11-17 22:56:20 +00001914 if (Object->getType()->isLiteralType())
1915 return EvaluateTemporary(Object, This, Info);
1916
1917 return false;
1918}
1919
1920/// HandleMemberPointerAccess - Evaluate a member access operation and build an
1921/// lvalue referring to the result.
1922///
1923/// \param Info - Information about the ongoing evaluation.
1924/// \param BO - The member pointer access operation.
1925/// \param LV - Filled in with a reference to the resulting object.
1926/// \param IncludeMember - Specifies whether the member itself is included in
1927/// the resulting LValue subobject designator. This is not possible when
1928/// creating a bound member function.
1929/// \return The field or method declaration to which the member pointer refers,
1930/// or 0 if evaluation fails.
1931static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
1932 const BinaryOperator *BO,
1933 LValue &LV,
1934 bool IncludeMember = true) {
1935 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
1936
Richard Smith253c2a32012-01-27 01:14:48 +00001937 bool EvalObjOK = EvaluateObjectArgument(Info, BO->getLHS(), LV);
1938 if (!EvalObjOK && !Info.keepEvaluatingAfterFailure())
Richard Smith027bf112011-11-17 22:56:20 +00001939 return 0;
1940
1941 MemberPtr MemPtr;
1942 if (!EvaluateMemberPointer(BO->getRHS(), MemPtr, Info))
1943 return 0;
1944
1945 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
1946 // member value, the behavior is undefined.
1947 if (!MemPtr.getDecl())
1948 return 0;
1949
Richard Smith253c2a32012-01-27 01:14:48 +00001950 if (!EvalObjOK)
1951 return 0;
1952
Richard Smith027bf112011-11-17 22:56:20 +00001953 if (MemPtr.isDerivedMember()) {
1954 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00001955 // The end of the derived-to-base path for the base object must match the
1956 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00001957 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith027bf112011-11-17 22:56:20 +00001958 LV.Designator.Entries.size())
1959 return 0;
1960 unsigned PathLengthToMember =
1961 LV.Designator.Entries.size() - MemPtr.Path.size();
1962 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
1963 const CXXRecordDecl *LVDecl = getAsBaseClass(
1964 LV.Designator.Entries[PathLengthToMember + I]);
1965 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
1966 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl())
1967 return 0;
1968 }
1969
1970 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00001971 if (!CastToDerivedClass(Info, BO, LV, MemPtr.getContainingRecord(),
1972 PathLengthToMember))
1973 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00001974 } else if (!MemPtr.Path.empty()) {
1975 // Extend the LValue path with the member pointer's path.
1976 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
1977 MemPtr.Path.size() + IncludeMember);
1978
1979 // Walk down to the appropriate base class.
1980 QualType LVType = BO->getLHS()->getType();
1981 if (const PointerType *PT = LVType->getAs<PointerType>())
1982 LVType = PT->getPointeeType();
1983 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
1984 assert(RD && "member pointer access on non-class-type expression");
1985 // The first class in the path is that of the lvalue.
1986 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
1987 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
John McCalld7bca762012-05-01 00:38:49 +00001988 if (!HandleLValueDirectBase(Info, BO, LV, RD, Base))
1989 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00001990 RD = Base;
1991 }
1992 // Finally cast to the class containing the member.
John McCalld7bca762012-05-01 00:38:49 +00001993 if (!HandleLValueDirectBase(Info, BO, LV, RD, MemPtr.getContainingRecord()))
1994 return 0;
Richard Smith027bf112011-11-17 22:56:20 +00001995 }
1996
1997 // Add the member. Note that we cannot build bound member functions here.
1998 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00001999 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
2000 if (!HandleLValueMember(Info, BO, LV, FD))
2001 return 0;
2002 } else if (const IndirectFieldDecl *IFD =
2003 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
2004 if (!HandleLValueIndirectMember(Info, BO, LV, IFD))
2005 return 0;
2006 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002007 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00002008 }
Richard Smith027bf112011-11-17 22:56:20 +00002009 }
2010
2011 return MemPtr.getDecl();
2012}
2013
2014/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
2015/// the provided lvalue, which currently refers to the base object.
2016static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
2017 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00002018 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002019 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00002020 return false;
2021
Richard Smitha8105bc2012-01-06 16:39:00 +00002022 QualType TargetQT = E->getType();
2023 if (const PointerType *PT = TargetQT->getAs<PointerType>())
2024 TargetQT = PT->getPointeeType();
2025
2026 // Check this cast lands within the final derived-to-base subobject path.
2027 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
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;
2030 return false;
2031 }
2032
Richard Smith027bf112011-11-17 22:56:20 +00002033 // Check the type of the final cast. We don't need to check the path,
2034 // since a cast can only be formed if the path is unique.
2035 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00002036 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
2037 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00002038 if (NewEntriesSize == D.MostDerivedPathLength)
2039 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
2040 else
Richard Smith027bf112011-11-17 22:56:20 +00002041 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00002042 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002043 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00002044 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00002045 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00002046 }
Richard Smith027bf112011-11-17 22:56:20 +00002047
2048 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00002049 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00002050}
2051
Mike Stump876387b2009-10-27 22:09:17 +00002052namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00002053enum EvalStmtResult {
2054 /// Evaluation failed.
2055 ESR_Failed,
2056 /// Hit a 'return' statement.
2057 ESR_Returned,
2058 /// Evaluation succeeded.
2059 ESR_Succeeded
2060};
2061}
2062
2063// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00002064static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith254a73d2011-10-28 22:34:42 +00002065 const Stmt *S) {
2066 switch (S->getStmtClass()) {
2067 default:
2068 return ESR_Failed;
2069
2070 case Stmt::NullStmtClass:
2071 case Stmt::DeclStmtClass:
2072 return ESR_Succeeded;
2073
Richard Smith357362d2011-12-13 06:39:58 +00002074 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00002075 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smithb228a862012-02-15 02:18:13 +00002076 if (!Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00002077 return ESR_Failed;
2078 return ESR_Returned;
2079 }
Richard Smith254a73d2011-10-28 22:34:42 +00002080
2081 case Stmt::CompoundStmtClass: {
2082 const CompoundStmt *CS = cast<CompoundStmt>(S);
2083 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
2084 BE = CS->body_end(); BI != BE; ++BI) {
2085 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
2086 if (ESR != ESR_Succeeded)
2087 return ESR;
2088 }
2089 return ESR_Succeeded;
2090 }
2091 }
2092}
2093
Richard Smithcc36f692011-12-22 02:22:31 +00002094/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
2095/// default constructor. If so, we'll fold it whether or not it's marked as
2096/// constexpr. If it is marked as constexpr, we will never implicitly define it,
2097/// so we need special handling.
2098static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00002099 const CXXConstructorDecl *CD,
2100 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00002101 if (!CD->isTrivial() || !CD->isDefaultConstructor())
2102 return false;
2103
Richard Smith66e05fe2012-01-18 05:21:49 +00002104 // Value-initialization does not call a trivial default constructor, so such a
2105 // call is a core constant expression whether or not the constructor is
2106 // constexpr.
2107 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002108 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00002109 // FIXME: If DiagDecl is an implicitly-declared special member function,
2110 // we should be much more explicit about why it's not constexpr.
2111 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
2112 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
2113 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00002114 } else {
2115 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
2116 }
2117 }
2118 return true;
2119}
2120
Richard Smith357362d2011-12-13 06:39:58 +00002121/// CheckConstexprFunction - Check that a function can be called in a constant
2122/// expression.
2123static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
2124 const FunctionDecl *Declaration,
2125 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00002126 // Potential constant expressions can contain calls to declared, but not yet
2127 // defined, constexpr functions.
2128 if (Info.CheckingPotentialConstantExpression && !Definition &&
2129 Declaration->isConstexpr())
2130 return false;
2131
Richard Smith357362d2011-12-13 06:39:58 +00002132 // Can we evaluate this function call?
2133 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
2134 return true;
2135
Richard Smith2bf7fdb2013-01-02 11:42:31 +00002136 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00002137 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002138 // FIXME: If DiagDecl is an implicitly-declared special member function, we
2139 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00002140 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
2141 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
2142 << DiagDecl;
2143 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
2144 } else {
2145 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
2146 }
2147 return false;
2148}
2149
Richard Smithd62306a2011-11-10 06:34:14 +00002150namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00002151typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00002152}
2153
2154/// EvaluateArgs - Evaluate the arguments to a function call.
2155static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
2156 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00002157 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002158 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00002159 I != E; ++I) {
2160 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
2161 // If we're checking for a potential constant expression, evaluate all
2162 // initializers even if some of them fail.
2163 if (!Info.keepEvaluatingAfterFailure())
2164 return false;
2165 Success = false;
2166 }
2167 }
2168 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00002169}
2170
Richard Smith254a73d2011-10-28 22:34:42 +00002171/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00002172static bool HandleFunctionCall(SourceLocation CallLoc,
2173 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002174 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00002175 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002176 ArgVector ArgValues(Args.size());
2177 if (!EvaluateArgs(Args, ArgValues, Info))
2178 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00002179
Richard Smith253c2a32012-01-27 01:14:48 +00002180 if (!Info.CheckCallLimit(CallLoc))
2181 return false;
2182
2183 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith254a73d2011-10-28 22:34:42 +00002184 return EvaluateStmt(Result, Info, Body) == ESR_Returned;
2185}
2186
Richard Smithd62306a2011-11-10 06:34:14 +00002187/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00002188static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00002189 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00002190 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00002191 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00002192 ArgVector ArgValues(Args.size());
2193 if (!EvaluateArgs(Args, ArgValues, Info))
2194 return false;
2195
Richard Smith253c2a32012-01-27 01:14:48 +00002196 if (!Info.CheckCallLimit(CallLoc))
2197 return false;
2198
Richard Smith3607ffe2012-02-13 03:54:03 +00002199 const CXXRecordDecl *RD = Definition->getParent();
2200 if (RD->getNumVBases()) {
2201 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
2202 return false;
2203 }
2204
Richard Smith253c2a32012-01-27 01:14:48 +00002205 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00002206
2207 // If it's a delegating constructor, just delegate.
2208 if (Definition->isDelegatingConstructor()) {
2209 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smithb228a862012-02-15 02:18:13 +00002210 return EvaluateInPlace(Result, Info, This, (*I)->getInit());
Richard Smithd62306a2011-11-10 06:34:14 +00002211 }
2212
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002213 // For a trivial copy or move constructor, perform an APValue copy. This is
2214 // essential for unions, where the operations performed by the constructor
2215 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002216 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00002217 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
2218 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002219 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00002220 RHS.setFrom(Info.Ctx, ArgValues[0]);
2221 return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
2222 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00002223 }
2224
2225 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00002226 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00002227 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
2228 std::distance(RD->field_begin(), RD->field_end()));
2229
John McCalld7bca762012-05-01 00:38:49 +00002230 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002231 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2232
Richard Smith253c2a32012-01-27 01:14:48 +00002233 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00002234 unsigned BasesSeen = 0;
2235#ifndef NDEBUG
2236 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
2237#endif
2238 for (CXXConstructorDecl::init_const_iterator I = Definition->init_begin(),
2239 E = Definition->init_end(); I != E; ++I) {
Richard Smith253c2a32012-01-27 01:14:48 +00002240 LValue Subobject = This;
2241 APValue *Value = &Result;
2242
2243 // Determine the subobject to initialize.
Richard Smithd62306a2011-11-10 06:34:14 +00002244 if ((*I)->isBaseInitializer()) {
2245 QualType BaseType((*I)->getBaseClass(), 0);
2246#ifndef NDEBUG
2247 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00002248 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00002249 assert(!BaseIt->isVirtual() && "virtual base for literal type");
2250 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
2251 "base class initializers not in expected order");
2252 ++BaseIt;
2253#endif
John McCalld7bca762012-05-01 00:38:49 +00002254 if (!HandleLValueDirectBase(Info, (*I)->getInit(), Subobject, RD,
2255 BaseType->getAsCXXRecordDecl(), &Layout))
2256 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00002257 Value = &Result.getStructBase(BasesSeen++);
Richard Smithd62306a2011-11-10 06:34:14 +00002258 } else if (FieldDecl *FD = (*I)->getMember()) {
John McCalld7bca762012-05-01 00:38:49 +00002259 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD, &Layout))
2260 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002261 if (RD->isUnion()) {
2262 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00002263 Value = &Result.getUnionValue();
2264 } else {
2265 Value = &Result.getStructField(FD->getFieldIndex());
2266 }
Richard Smith1b78b3d2012-01-25 22:15:11 +00002267 } else if (IndirectFieldDecl *IFD = (*I)->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002268 // Walk the indirect field decl's chain to find the object to initialize,
2269 // and make sure we've initialized every step along it.
2270 for (IndirectFieldDecl::chain_iterator C = IFD->chain_begin(),
2271 CE = IFD->chain_end();
2272 C != CE; ++C) {
2273 FieldDecl *FD = cast<FieldDecl>(*C);
2274 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
2275 // Switch the union field if it differs. This happens if we had
2276 // preceding zero-initialization, and we're now initializing a union
2277 // subobject other than the first.
2278 // FIXME: In this case, the values of the other subobjects are
2279 // specified, since zero-initialization sets all padding bits to zero.
2280 if (Value->isUninit() ||
2281 (Value->isUnion() && Value->getUnionField() != FD)) {
2282 if (CD->isUnion())
2283 *Value = APValue(FD);
2284 else
2285 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
2286 std::distance(CD->field_begin(), CD->field_end()));
2287 }
John McCalld7bca762012-05-01 00:38:49 +00002288 if (!HandleLValueMember(Info, (*I)->getInit(), Subobject, FD))
2289 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002290 if (CD->isUnion())
2291 Value = &Value->getUnionValue();
2292 else
2293 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00002294 }
Richard Smithd62306a2011-11-10 06:34:14 +00002295 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00002296 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00002297 }
Richard Smith253c2a32012-01-27 01:14:48 +00002298
Richard Smithb228a862012-02-15 02:18:13 +00002299 if (!EvaluateInPlace(*Value, Info, Subobject, (*I)->getInit(),
2300 (*I)->isBaseInitializer()
Richard Smith253c2a32012-01-27 01:14:48 +00002301 ? CCEK_Constant : CCEK_MemberInit)) {
2302 // If we're checking for a potential constant expression, evaluate all
2303 // initializers even if some of them fail.
2304 if (!Info.keepEvaluatingAfterFailure())
2305 return false;
2306 Success = false;
2307 }
Richard Smithd62306a2011-11-10 06:34:14 +00002308 }
2309
Richard Smith253c2a32012-01-27 01:14:48 +00002310 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00002311}
2312
Eli Friedman9a156e52008-11-12 09:44:48 +00002313//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00002314// Generic Evaluation
2315//===----------------------------------------------------------------------===//
2316namespace {
2317
Richard Smithf57d8cb2011-12-09 22:58:01 +00002318// FIXME: RetTy is always bool. Remove it.
2319template <class Derived, typename RetTy=bool>
Peter Collingbournee9200682011-05-13 03:29:01 +00002320class ExprEvaluatorBase
2321 : public ConstStmtVisitor<Derived, RetTy> {
2322private:
Richard Smith2e312c82012-03-03 22:46:17 +00002323 RetTy DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00002324 return static_cast<Derived*>(this)->Success(V, E);
2325 }
Richard Smithfddd3842011-12-30 21:15:51 +00002326 RetTy DerivedZeroInitialization(const Expr *E) {
2327 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002328 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002329
Richard Smith17100ba2012-02-16 02:46:34 +00002330 // Check whether a conditional operator with a non-constant condition is a
2331 // potential constant expression. If neither arm is a potential constant
2332 // expression, then the conditional operator is not either.
2333 template<typename ConditionalOperator>
2334 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
2335 assert(Info.CheckingPotentialConstantExpression);
2336
2337 // Speculatively evaluate both arms.
2338 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002339 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00002340 SpeculativeEvaluationRAII Speculate(Info, &Diag);
2341
2342 StmtVisitorTy::Visit(E->getFalseExpr());
2343 if (Diag.empty())
2344 return;
2345
2346 Diag.clear();
2347 StmtVisitorTy::Visit(E->getTrueExpr());
2348 if (Diag.empty())
2349 return;
2350 }
2351
2352 Error(E, diag::note_constexpr_conditional_never_const);
2353 }
2354
2355
2356 template<typename ConditionalOperator>
2357 bool HandleConditionalOperator(const ConditionalOperator *E) {
2358 bool BoolResult;
2359 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
2360 if (Info.CheckingPotentialConstantExpression)
2361 CheckPotentialConstantConditional(E);
2362 return false;
2363 }
2364
2365 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
2366 return StmtVisitorTy::Visit(EvalExpr);
2367 }
2368
Peter Collingbournee9200682011-05-13 03:29:01 +00002369protected:
2370 EvalInfo &Info;
2371 typedef ConstStmtVisitor<Derived, RetTy> StmtVisitorTy;
2372 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
2373
Richard Smith92b1ce02011-12-12 09:28:41 +00002374 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002375 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002376 }
2377
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00002378 RetTy ZeroInitialization(const Expr *E) { return Error(E); }
2379
2380public:
2381 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
2382
2383 EvalInfo &getEvalInfo() { return Info; }
2384
Richard Smithf57d8cb2011-12-09 22:58:01 +00002385 /// Report an evaluation error. This should only be called when an error is
2386 /// first discovered. When propagating an error, just return false.
2387 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002388 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002389 return false;
2390 }
2391 bool Error(const Expr *E) {
2392 return Error(E, diag::note_invalid_subexpr_in_const_expr);
2393 }
2394
Peter Collingbournee9200682011-05-13 03:29:01 +00002395 RetTy VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00002396 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00002397 }
2398 RetTy VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002399 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002400 }
2401
2402 RetTy VisitParenExpr(const ParenExpr *E)
2403 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2404 RetTy VisitUnaryExtension(const UnaryOperator *E)
2405 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2406 RetTy VisitUnaryPlus(const UnaryOperator *E)
2407 { return StmtVisitorTy::Visit(E->getSubExpr()); }
2408 RetTy VisitChooseExpr(const ChooseExpr *E)
2409 { return StmtVisitorTy::Visit(E->getChosenSubExpr(Info.Ctx)); }
2410 RetTy VisitGenericSelectionExpr(const GenericSelectionExpr *E)
2411 { return StmtVisitorTy::Visit(E->getResultExpr()); }
John McCall7c454bb2011-07-15 05:09:51 +00002412 RetTy VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
2413 { return StmtVisitorTy::Visit(E->getReplacement()); }
Richard Smithf8120ca2011-11-09 02:12:41 +00002414 RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
2415 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith852c9db2013-04-20 22:23:05 +00002416 RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
2417 { return StmtVisitorTy::Visit(E->getExpr()); }
Richard Smith5894a912011-12-19 22:12:41 +00002418 // We cannot create any objects for which cleanups are required, so there is
2419 // nothing to do here; all cleanups must come from unevaluated subexpressions.
2420 RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
2421 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00002422
Richard Smith6d6ecc32011-12-12 12:46:16 +00002423 RetTy VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
2424 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
2425 return static_cast<Derived*>(this)->VisitCastExpr(E);
2426 }
2427 RetTy VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
2428 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
2429 return static_cast<Derived*>(this)->VisitCastExpr(E);
2430 }
2431
Richard Smith027bf112011-11-17 22:56:20 +00002432 RetTy VisitBinaryOperator(const BinaryOperator *E) {
2433 switch (E->getOpcode()) {
2434 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00002435 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002436
2437 case BO_Comma:
2438 VisitIgnoredValue(E->getLHS());
2439 return StmtVisitorTy::Visit(E->getRHS());
2440
2441 case BO_PtrMemD:
2442 case BO_PtrMemI: {
2443 LValue Obj;
2444 if (!HandleMemberPointerAccess(Info, E, Obj))
2445 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00002446 APValue Result;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002447 if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00002448 return false;
2449 return DerivedSuccess(Result, E);
2450 }
2451 }
2452 }
2453
Peter Collingbournee9200682011-05-13 03:29:01 +00002454 RetTy VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00002455 // Evaluate and cache the common expression. We treat it as a temporary,
2456 // even though it's not quite the same thing.
2457 if (!Evaluate(Info.CurrentCall->Temporaries[E->getOpaqueValue()],
2458 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002459 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00002460
Richard Smith17100ba2012-02-16 02:46:34 +00002461 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002462 }
2463
2464 RetTy VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002465 bool IsBcpCall = false;
2466 // If the condition (ignoring parens) is a __builtin_constant_p call,
2467 // the result is a constant expression if it can be folded without
2468 // side-effects. This is an important GNU extension. See GCC PR38377
2469 // for discussion.
2470 if (const CallExpr *CallCE =
2471 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
2472 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
2473 IsBcpCall = true;
2474
2475 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
2476 // constant expression; we can't check whether it's potentially foldable.
2477 if (Info.CheckingPotentialConstantExpression && IsBcpCall)
2478 return false;
2479
2480 FoldConstant Fold(Info);
2481
Richard Smith17100ba2012-02-16 02:46:34 +00002482 if (!HandleConditionalOperator(E))
Richard Smith84f6dcf2012-02-02 01:16:57 +00002483 return false;
2484
2485 if (IsBcpCall)
2486 Fold.Fold(Info);
2487
2488 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00002489 }
2490
2491 RetTy VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00002492 APValue &Value = Info.CurrentCall->Temporaries[E];
2493 if (Value.isUninit()) {
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002494 const Expr *Source = E->getSourceExpr();
2495 if (!Source)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002496 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002497 if (Source == E) { // sanity checking.
2498 assert(0 && "OpaqueValueExpr recursively refers to itself");
Richard Smithf57d8cb2011-12-09 22:58:01 +00002499 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00002500 }
2501 return StmtVisitorTy::Visit(Source);
2502 }
Richard Smith26d4cc12012-06-26 08:12:11 +00002503 return DerivedSuccess(Value, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002504 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002505
Richard Smith254a73d2011-10-28 22:34:42 +00002506 RetTy VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00002507 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00002508 QualType CalleeType = Callee->getType();
2509
Richard Smith254a73d2011-10-28 22:34:42 +00002510 const FunctionDecl *FD = 0;
Richard Smithe97cbd72011-11-11 04:05:33 +00002511 LValue *This = 0, ThisVal;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002512 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00002513 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00002514
Richard Smithe97cbd72011-11-11 04:05:33 +00002515 // Extract function decl and 'this' pointer from the callee.
2516 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002517 const ValueDecl *Member = 0;
Richard Smith027bf112011-11-17 22:56:20 +00002518 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
2519 // Explicit bound member calls, such as x.f() or p->g();
2520 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002521 return false;
2522 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00002523 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00002524 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00002525 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
2526 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00002527 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
2528 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00002529 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00002530 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002531 return Error(Callee);
2532
2533 FD = dyn_cast<FunctionDecl>(Member);
2534 if (!FD)
2535 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002536 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002537 LValue Call;
2538 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002539 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00002540
Richard Smitha8105bc2012-01-06 16:39:00 +00002541 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002542 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00002543 FD = dyn_cast_or_null<FunctionDecl>(
2544 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00002545 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00002546 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00002547
2548 // Overloaded operator calls to member functions are represented as normal
2549 // calls with '*this' as the first argument.
2550 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
2551 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00002552 // FIXME: When selecting an implicit conversion for an overloaded
2553 // operator delete, we sometimes try to evaluate calls to conversion
2554 // operators without a 'this' parameter!
2555 if (Args.empty())
2556 return Error(E);
2557
Richard Smithe97cbd72011-11-11 04:05:33 +00002558 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
2559 return false;
2560 This = &ThisVal;
2561 Args = Args.slice(1);
2562 }
2563
2564 // Don't call function pointers which have been cast to some other type.
2565 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002566 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00002567 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00002568 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00002569
Richard Smith47b34932012-02-01 02:39:43 +00002570 if (This && !This->checkSubobject(Info, E, CSK_This))
2571 return false;
2572
Richard Smith3607ffe2012-02-13 03:54:03 +00002573 // DR1358 allows virtual constexpr functions in some cases. Don't allow
2574 // calls to such functions in constant expressions.
2575 if (This && !HasQualifier &&
2576 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
2577 return Error(E, diag::note_constexpr_virtual_call);
2578
Richard Smith357362d2011-12-13 06:39:58 +00002579 const FunctionDecl *Definition = 0;
Richard Smith254a73d2011-10-28 22:34:42 +00002580 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00002581 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00002582
Richard Smith357362d2011-12-13 06:39:58 +00002583 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00002584 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
2585 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002586 return false;
2587
Richard Smithb228a862012-02-15 02:18:13 +00002588 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00002589 }
2590
Richard Smith11562c52011-10-28 17:51:58 +00002591 RetTy VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2592 return StmtVisitorTy::Visit(E->getInitializer());
2593 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002594 RetTy VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00002595 if (E->getNumInits() == 0)
2596 return DerivedZeroInitialization(E);
2597 if (E->getNumInits() == 1)
2598 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00002599 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002600 }
2601 RetTy VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002602 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002603 }
2604 RetTy VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002605 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00002606 }
Richard Smith027bf112011-11-17 22:56:20 +00002607 RetTy VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00002608 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00002609 }
Richard Smith4ce706a2011-10-11 21:43:33 +00002610
Richard Smithd62306a2011-11-10 06:34:14 +00002611 /// A member expression where the object is a prvalue is itself a prvalue.
2612 RetTy VisitMemberExpr(const MemberExpr *E) {
2613 assert(!E->isArrow() && "missing call to bound member function?");
2614
Richard Smith2e312c82012-03-03 22:46:17 +00002615 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00002616 if (!Evaluate(Val, Info, E->getBase()))
2617 return false;
2618
2619 QualType BaseTy = E->getBase()->getType();
2620
2621 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00002622 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00002623 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00002624 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00002625 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2626
Richard Smitha8105bc2012-01-06 16:39:00 +00002627 SubobjectDesignator Designator(BaseTy);
2628 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00002629
Richard Smithf57d8cb2011-12-09 22:58:01 +00002630 return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
Richard Smithd62306a2011-11-10 06:34:14 +00002631 DerivedSuccess(Val, E);
2632 }
2633
Richard Smith11562c52011-10-28 17:51:58 +00002634 RetTy VisitCastExpr(const CastExpr *E) {
2635 switch (E->getCastKind()) {
2636 default:
2637 break;
2638
David Chisnallfa35df62012-01-16 17:27:18 +00002639 case CK_AtomicToNonAtomic:
2640 case CK_NonAtomicToAtomic:
Richard Smith11562c52011-10-28 17:51:58 +00002641 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00002642 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00002643 return StmtVisitorTy::Visit(E->getSubExpr());
2644
2645 case CK_LValueToRValue: {
2646 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002647 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
2648 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00002649 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00002650 // Note, we use the subexpression's type in order to retain cv-qualifiers.
2651 if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
2652 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00002653 return false;
2654 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00002655 }
2656 }
2657
Richard Smithf57d8cb2011-12-09 22:58:01 +00002658 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002659 }
2660
Richard Smith4a678122011-10-24 18:44:57 +00002661 /// Visit a value which is evaluated, but whose value is ignored.
2662 void VisitIgnoredValue(const Expr *E) {
Richard Smith2e312c82012-03-03 22:46:17 +00002663 APValue Scratch;
Richard Smith4a678122011-10-24 18:44:57 +00002664 if (!Evaluate(Scratch, Info, E))
2665 Info.EvalStatus.HasSideEffects = true;
2666 }
Peter Collingbournee9200682011-05-13 03:29:01 +00002667};
2668
2669}
2670
2671//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00002672// Common base class for lvalue and temporary evaluation.
2673//===----------------------------------------------------------------------===//
2674namespace {
2675template<class Derived>
2676class LValueExprEvaluatorBase
2677 : public ExprEvaluatorBase<Derived, bool> {
2678protected:
2679 LValue &Result;
2680 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
2681 typedef ExprEvaluatorBase<Derived, bool> ExprEvaluatorBaseTy;
2682
2683 bool Success(APValue::LValueBase B) {
2684 Result.set(B);
2685 return true;
2686 }
2687
2688public:
2689 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
2690 ExprEvaluatorBaseTy(Info), Result(Result) {}
2691
Richard Smith2e312c82012-03-03 22:46:17 +00002692 bool Success(const APValue &V, const Expr *E) {
2693 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00002694 return true;
2695 }
Richard Smith027bf112011-11-17 22:56:20 +00002696
Richard Smith027bf112011-11-17 22:56:20 +00002697 bool VisitMemberExpr(const MemberExpr *E) {
2698 // Handle non-static data members.
2699 QualType BaseTy;
2700 if (E->isArrow()) {
2701 if (!EvaluatePointer(E->getBase(), Result, this->Info))
2702 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00002703 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00002704 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00002705 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00002706 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
2707 return false;
2708 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00002709 } else {
2710 if (!this->Visit(E->getBase()))
2711 return false;
2712 BaseTy = E->getBase()->getType();
2713 }
Richard Smith027bf112011-11-17 22:56:20 +00002714
Richard Smith1b78b3d2012-01-25 22:15:11 +00002715 const ValueDecl *MD = E->getMemberDecl();
2716 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
2717 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
2718 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
2719 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00002720 if (!HandleLValueMember(this->Info, E, Result, FD))
2721 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002722 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00002723 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
2724 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002725 } else
2726 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00002727
Richard Smith1b78b3d2012-01-25 22:15:11 +00002728 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00002729 APValue RefValue;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002730 if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00002731 RefValue))
2732 return false;
2733 return Success(RefValue, E);
2734 }
2735 return true;
2736 }
2737
2738 bool VisitBinaryOperator(const BinaryOperator *E) {
2739 switch (E->getOpcode()) {
2740 default:
2741 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
2742
2743 case BO_PtrMemD:
2744 case BO_PtrMemI:
2745 return HandleMemberPointerAccess(this->Info, E, Result);
2746 }
2747 }
2748
2749 bool VisitCastExpr(const CastExpr *E) {
2750 switch (E->getCastKind()) {
2751 default:
2752 return ExprEvaluatorBaseTy::VisitCastExpr(E);
2753
2754 case CK_DerivedToBase:
2755 case CK_UncheckedDerivedToBase: {
2756 if (!this->Visit(E->getSubExpr()))
2757 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002758
2759 // Now figure out the necessary offset to add to the base LV to get from
2760 // the derived class to the base class.
2761 QualType Type = E->getSubExpr()->getType();
2762
2763 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2764 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002765 if (!HandleLValueBase(this->Info, E, Result, Type->getAsCXXRecordDecl(),
Richard Smith027bf112011-11-17 22:56:20 +00002766 *PathI))
2767 return false;
2768 Type = (*PathI)->getType();
2769 }
2770
2771 return true;
2772 }
2773 }
2774 }
2775};
2776}
2777
2778//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00002779// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00002780//
2781// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
2782// function designators (in C), decl references to void objects (in C), and
2783// temporaries (if building with -Wno-address-of-temporary).
2784//
2785// LValue evaluation produces values comprising a base expression of one of the
2786// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00002787// - Declarations
2788// * VarDecl
2789// * FunctionDecl
2790// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00002791// * CompoundLiteralExpr in C
2792// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00002793// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00002794// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00002795// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00002796// * ObjCEncodeExpr
2797// * AddrLabelExpr
2798// * BlockExpr
2799// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00002800// - Locals and temporaries
Richard Smithb228a862012-02-15 02:18:13 +00002801// * Any Expr, with a CallIndex indicating the function in which the temporary
2802// was evaluated.
Richard Smithce40ad62011-11-12 22:28:03 +00002803// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00002804//===----------------------------------------------------------------------===//
2805namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002806class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00002807 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00002808public:
Richard Smith027bf112011-11-17 22:56:20 +00002809 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
2810 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00002811
Richard Smith11562c52011-10-28 17:51:58 +00002812 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
2813
Peter Collingbournee9200682011-05-13 03:29:01 +00002814 bool VisitDeclRefExpr(const DeclRefExpr *E);
2815 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002816 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002817 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
2818 bool VisitMemberExpr(const MemberExpr *E);
2819 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
2820 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00002821 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00002822 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00002823 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
2824 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00002825 bool VisitUnaryReal(const UnaryOperator *E);
2826 bool VisitUnaryImag(const UnaryOperator *E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002827
Peter Collingbournee9200682011-05-13 03:29:01 +00002828 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00002829 switch (E->getCastKind()) {
2830 default:
Richard Smith027bf112011-11-17 22:56:20 +00002831 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00002832
Eli Friedmance3e02a2011-10-11 00:13:24 +00002833 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00002834 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00002835 if (!Visit(E->getSubExpr()))
2836 return false;
2837 Result.Designator.setInvalid();
2838 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00002839
Richard Smith027bf112011-11-17 22:56:20 +00002840 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00002841 if (!Visit(E->getSubExpr()))
2842 return false;
Richard Smith027bf112011-11-17 22:56:20 +00002843 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00002844 }
2845 }
Eli Friedman9a156e52008-11-12 09:44:48 +00002846};
2847} // end anonymous namespace
2848
Richard Smith11562c52011-10-28 17:51:58 +00002849/// Evaluate an expression as an lvalue. This can be legitimately called on
2850/// expressions which are not glvalues, in a few cases:
2851/// * function designators in C,
2852/// * "extern void" objects,
2853/// * temporaries, if building with -Wno-address-of-temporary.
John McCall45d55e42010-05-07 21:00:08 +00002854static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00002855 assert((E->isGLValue() || E->getType()->isFunctionType() ||
2856 E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
2857 "can't evaluate expression as an lvalue");
Peter Collingbournee9200682011-05-13 03:29:01 +00002858 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002859}
2860
Peter Collingbournee9200682011-05-13 03:29:01 +00002861bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002862 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
2863 return Success(FD);
2864 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00002865 return VisitVarDecl(E, VD);
2866 return Error(E);
2867}
Richard Smith733237d2011-10-24 23:14:33 +00002868
Richard Smith11562c52011-10-28 17:51:58 +00002869bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Richard Smithfec09922011-11-01 16:57:24 +00002870 if (!VD->getType()->isReferenceType()) {
2871 if (isa<ParmVarDecl>(VD)) {
Richard Smithb228a862012-02-15 02:18:13 +00002872 Result.set(VD, Info.CurrentCall->Index);
Richard Smithfec09922011-11-01 16:57:24 +00002873 return true;
2874 }
Richard Smithce40ad62011-11-12 22:28:03 +00002875 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00002876 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00002877
Richard Smith2e312c82012-03-03 22:46:17 +00002878 APValue V;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002879 if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
2880 return false;
2881 return Success(V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00002882}
2883
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002884bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
2885 const MaterializeTemporaryExpr *E) {
Jordan Roseb1312a52013-04-11 00:58:58 +00002886 if (E->getType()->isRecordType())
2887 return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
Richard Smith027bf112011-11-17 22:56:20 +00002888
Richard Smithb228a862012-02-15 02:18:13 +00002889 Result.set(E, Info.CurrentCall->Index);
Jordan Roseb1312a52013-04-11 00:58:58 +00002890 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
2891 Result, E->GetTemporaryExpr());
Richard Smith4e4c78ff2011-10-31 05:52:43 +00002892}
2893
Peter Collingbournee9200682011-05-13 03:29:01 +00002894bool
2895LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002896 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2897 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
2898 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00002899 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002900}
2901
Richard Smith6e525142011-12-27 12:18:28 +00002902bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00002903 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00002904 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00002905
2906 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
2907 << E->getExprOperand()->getType()
2908 << E->getExprOperand()->getSourceRange();
2909 return false;
Richard Smith6e525142011-12-27 12:18:28 +00002910}
2911
Francois Pichet0066db92012-04-16 04:08:35 +00002912bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
2913 return Success(E);
2914}
2915
Peter Collingbournee9200682011-05-13 03:29:01 +00002916bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002917 // Handle static data members.
2918 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
2919 VisitIgnoredValue(E->getBase());
2920 return VisitVarDecl(E, VD);
2921 }
2922
Richard Smith254a73d2011-10-28 22:34:42 +00002923 // Handle static member functions.
2924 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
2925 if (MD->isStatic()) {
2926 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00002927 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00002928 }
2929 }
2930
Richard Smithd62306a2011-11-10 06:34:14 +00002931 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00002932 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00002933}
2934
Peter Collingbournee9200682011-05-13 03:29:01 +00002935bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00002936 // FIXME: Deal with vectors as array subscript bases.
2937 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00002938 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00002939
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002940 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00002941 return false;
Mike Stump11289f42009-09-09 15:08:12 +00002942
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002943 APSInt Index;
2944 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00002945 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002946 int64_t IndexValue
2947 = Index.isSigned() ? Index.getSExtValue()
2948 : static_cast<int64_t>(Index.getZExtValue());
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002949
Richard Smitha8105bc2012-01-06 16:39:00 +00002950 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(), IndexValue);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00002951}
Eli Friedman9a156e52008-11-12 09:44:48 +00002952
Peter Collingbournee9200682011-05-13 03:29:01 +00002953bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00002954 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00002955}
2956
Richard Smith66c96992012-02-18 22:04:06 +00002957bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
2958 if (!Visit(E->getSubExpr()))
2959 return false;
2960 // __real is a no-op on scalar lvalues.
2961 if (E->getSubExpr()->getType()->isAnyComplexType())
2962 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
2963 return true;
2964}
2965
2966bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
2967 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
2968 "lvalue __imag__ on scalar?");
2969 if (!Visit(E->getSubExpr()))
2970 return false;
2971 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
2972 return true;
2973}
2974
Eli Friedman9a156e52008-11-12 09:44:48 +00002975//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00002976// Pointer Evaluation
2977//===----------------------------------------------------------------------===//
2978
Anders Carlsson0a1707c2008-07-08 05:13:58 +00002979namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00002980class PointerExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00002981 : public ExprEvaluatorBase<PointerExprEvaluator, bool> {
John McCall45d55e42010-05-07 21:00:08 +00002982 LValue &Result;
2983
Peter Collingbournee9200682011-05-13 03:29:01 +00002984 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00002985 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00002986 return true;
2987 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00002988public:
Mike Stump11289f42009-09-09 15:08:12 +00002989
John McCall45d55e42010-05-07 21:00:08 +00002990 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00002991 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00002992
Richard Smith2e312c82012-03-03 22:46:17 +00002993 bool Success(const APValue &V, const Expr *E) {
2994 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00002995 return true;
2996 }
Richard Smithfddd3842011-12-30 21:15:51 +00002997 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00002998 return Success((Expr*)0);
2999 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00003000
John McCall45d55e42010-05-07 21:00:08 +00003001 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003002 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00003003 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003004 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00003005 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00003006 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00003007 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003008 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00003009 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003010 bool VisitCallExpr(const CallExpr *E);
3011 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00003012 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00003013 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003014 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00003015 }
Richard Smithd62306a2011-11-10 06:34:14 +00003016 bool VisitCXXThisExpr(const CXXThisExpr *E) {
3017 if (!Info.CurrentCall->This)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003018 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003019 Result = *Info.CurrentCall->This;
3020 return true;
3021 }
John McCallc07a0c72011-02-17 10:25:35 +00003022
Eli Friedman449fe542009-03-23 04:56:01 +00003023 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003024};
Chris Lattner05706e882008-07-11 18:11:29 +00003025} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00003026
John McCall45d55e42010-05-07 21:00:08 +00003027static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003028 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00003029 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00003030}
3031
John McCall45d55e42010-05-07 21:00:08 +00003032bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00003033 if (E->getOpcode() != BO_Add &&
3034 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00003035 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00003036
Chris Lattner05706e882008-07-11 18:11:29 +00003037 const Expr *PExp = E->getLHS();
3038 const Expr *IExp = E->getRHS();
3039 if (IExp->getType()->isPointerType())
3040 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00003041
Richard Smith253c2a32012-01-27 01:14:48 +00003042 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
3043 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00003044 return false;
Mike Stump11289f42009-09-09 15:08:12 +00003045
John McCall45d55e42010-05-07 21:00:08 +00003046 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00003047 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00003048 return false;
3049 int64_t AdditionalOffset
3050 = Offset.isSigned() ? Offset.getSExtValue()
3051 : static_cast<int64_t>(Offset.getZExtValue());
Richard Smith96e0c102011-11-04 02:25:55 +00003052 if (E->getOpcode() == BO_Sub)
3053 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00003054
Ted Kremenek28831752012-08-23 20:46:57 +00003055 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00003056 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
3057 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00003058}
Eli Friedman9a156e52008-11-12 09:44:48 +00003059
John McCall45d55e42010-05-07 21:00:08 +00003060bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3061 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003062}
Mike Stump11289f42009-09-09 15:08:12 +00003063
Peter Collingbournee9200682011-05-13 03:29:01 +00003064bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
3065 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00003066
Eli Friedman847a2bc2009-12-27 05:43:15 +00003067 switch (E->getCastKind()) {
3068 default:
3069 break;
3070
John McCalle3027922010-08-25 11:45:40 +00003071 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00003072 case CK_CPointerToObjCPointerCast:
3073 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00003074 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00003075 if (!Visit(SubExpr))
3076 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00003077 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
3078 // permitted in constant expressions in C++11. Bitcasts from cv void* are
3079 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00003080 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00003081 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00003082 if (SubExpr->getType()->isVoidPointerType())
3083 CCEDiag(E, diag::note_constexpr_invalid_cast)
3084 << 3 << SubExpr->getType();
3085 else
3086 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3087 }
Richard Smith96e0c102011-11-04 02:25:55 +00003088 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00003089
Anders Carlsson18275092010-10-31 20:41:46 +00003090 case CK_DerivedToBase:
3091 case CK_UncheckedDerivedToBase: {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003092 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00003093 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003094 if (!Result.Base && Result.Offset.isZero())
3095 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00003096
Richard Smithd62306a2011-11-10 06:34:14 +00003097 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00003098 // the derived class to the base class.
Richard Smithd62306a2011-11-10 06:34:14 +00003099 QualType Type =
3100 E->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
Anders Carlsson18275092010-10-31 20:41:46 +00003101
Richard Smithd62306a2011-11-10 06:34:14 +00003102 for (CastExpr::path_const_iterator PathI = E->path_begin(),
Anders Carlsson18275092010-10-31 20:41:46 +00003103 PathE = E->path_end(); PathI != PathE; ++PathI) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003104 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
3105 *PathI))
Anders Carlsson18275092010-10-31 20:41:46 +00003106 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003107 Type = (*PathI)->getType();
Anders Carlsson18275092010-10-31 20:41:46 +00003108 }
3109
Anders Carlsson18275092010-10-31 20:41:46 +00003110 return true;
3111 }
3112
Richard Smith027bf112011-11-17 22:56:20 +00003113 case CK_BaseToDerived:
3114 if (!Visit(E->getSubExpr()))
3115 return false;
3116 if (!Result.Base && Result.Offset.isZero())
3117 return true;
3118 return HandleBaseToDerivedCast(Info, E, Result);
3119
Richard Smith0b0a0b62011-10-29 20:57:55 +00003120 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003121 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003122 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00003123
John McCalle3027922010-08-25 11:45:40 +00003124 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003125 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
3126
Richard Smith2e312c82012-03-03 22:46:17 +00003127 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00003128 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00003129 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00003130
John McCall45d55e42010-05-07 21:00:08 +00003131 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00003132 unsigned Size = Info.Ctx.getTypeSize(E->getType());
3133 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Richard Smithce40ad62011-11-12 22:28:03 +00003134 Result.Base = (Expr*)0;
Richard Smith0b0a0b62011-10-29 20:57:55 +00003135 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00003136 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00003137 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00003138 return true;
3139 } else {
3140 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00003141 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00003142 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00003143 }
3144 }
John McCalle3027922010-08-25 11:45:40 +00003145 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00003146 if (SubExpr->isGLValue()) {
3147 if (!EvaluateLValue(SubExpr, Result, Info))
3148 return false;
3149 } else {
Richard Smithb228a862012-02-15 02:18:13 +00003150 Result.set(SubExpr, Info.CurrentCall->Index);
3151 if (!EvaluateInPlace(Info.CurrentCall->Temporaries[SubExpr],
3152 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00003153 return false;
3154 }
Richard Smith96e0c102011-11-04 02:25:55 +00003155 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00003156 if (const ConstantArrayType *CAT
3157 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
3158 Result.addArray(Info, E, CAT);
3159 else
3160 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00003161 return true;
Richard Smithdd785442011-10-31 20:57:44 +00003162
John McCalle3027922010-08-25 11:45:40 +00003163 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00003164 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00003165 }
3166
Richard Smith11562c52011-10-28 17:51:58 +00003167 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00003168}
Chris Lattner05706e882008-07-11 18:11:29 +00003169
Peter Collingbournee9200682011-05-13 03:29:01 +00003170bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003171 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00003172 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00003173
Peter Collingbournee9200682011-05-13 03:29:01 +00003174 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00003175}
Chris Lattner05706e882008-07-11 18:11:29 +00003176
3177//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003178// Member Pointer Evaluation
3179//===----------------------------------------------------------------------===//
3180
3181namespace {
3182class MemberPointerExprEvaluator
3183 : public ExprEvaluatorBase<MemberPointerExprEvaluator, bool> {
3184 MemberPtr &Result;
3185
3186 bool Success(const ValueDecl *D) {
3187 Result = MemberPtr(D);
3188 return true;
3189 }
3190public:
3191
3192 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
3193 : ExprEvaluatorBaseTy(Info), Result(Result) {}
3194
Richard Smith2e312c82012-03-03 22:46:17 +00003195 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003196 Result.setFrom(V);
3197 return true;
3198 }
Richard Smithfddd3842011-12-30 21:15:51 +00003199 bool ZeroInitialization(const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003200 return Success((const ValueDecl*)0);
3201 }
3202
3203 bool VisitCastExpr(const CastExpr *E);
3204 bool VisitUnaryAddrOf(const UnaryOperator *E);
3205};
3206} // end anonymous namespace
3207
3208static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
3209 EvalInfo &Info) {
3210 assert(E->isRValue() && E->getType()->isMemberPointerType());
3211 return MemberPointerExprEvaluator(Info, Result).Visit(E);
3212}
3213
3214bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
3215 switch (E->getCastKind()) {
3216 default:
3217 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3218
3219 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00003220 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003221 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00003222
3223 case CK_BaseToDerivedMemberPointer: {
3224 if (!Visit(E->getSubExpr()))
3225 return false;
3226 if (E->path_empty())
3227 return true;
3228 // Base-to-derived member pointer casts store the path in derived-to-base
3229 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
3230 // the wrong end of the derived->base arc, so stagger the path by one class.
3231 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
3232 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
3233 PathI != PathE; ++PathI) {
3234 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3235 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
3236 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003237 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003238 }
3239 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
3240 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003241 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003242 return true;
3243 }
3244
3245 case CK_DerivedToBaseMemberPointer:
3246 if (!Visit(E->getSubExpr()))
3247 return false;
3248 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3249 PathE = E->path_end(); PathI != PathE; ++PathI) {
3250 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
3251 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3252 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003253 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003254 }
3255 return true;
3256 }
3257}
3258
3259bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
3260 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
3261 // member can be formed.
3262 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
3263}
3264
3265//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00003266// Record Evaluation
3267//===----------------------------------------------------------------------===//
3268
3269namespace {
3270 class RecordExprEvaluator
3271 : public ExprEvaluatorBase<RecordExprEvaluator, bool> {
3272 const LValue &This;
3273 APValue &Result;
3274 public:
3275
3276 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
3277 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
3278
Richard Smith2e312c82012-03-03 22:46:17 +00003279 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003280 Result = V;
3281 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00003282 }
Richard Smithfddd3842011-12-30 21:15:51 +00003283 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003284
Richard Smithe97cbd72011-11-11 04:05:33 +00003285 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00003286 bool VisitInitListExpr(const InitListExpr *E);
3287 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
3288 };
3289}
3290
Richard Smithfddd3842011-12-30 21:15:51 +00003291/// Perform zero-initialization on an object of non-union class type.
3292/// C++11 [dcl.init]p5:
3293/// To zero-initialize an object or reference of type T means:
3294/// [...]
3295/// -- if T is a (possibly cv-qualified) non-union class type,
3296/// each non-static data member and each base-class subobject is
3297/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00003298static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
3299 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00003300 const LValue &This, APValue &Result) {
3301 assert(!RD->isUnion() && "Expected non-union class type");
3302 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
3303 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
3304 std::distance(RD->field_begin(), RD->field_end()));
3305
John McCalld7bca762012-05-01 00:38:49 +00003306 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003307 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3308
3309 if (CD) {
3310 unsigned Index = 0;
3311 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003312 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00003313 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
3314 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00003315 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
3316 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003317 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00003318 Result.getStructBase(Index)))
3319 return false;
3320 }
3321 }
3322
Richard Smitha8105bc2012-01-06 16:39:00 +00003323 for (RecordDecl::field_iterator I = RD->field_begin(), End = RD->field_end();
3324 I != End; ++I) {
Richard Smithfddd3842011-12-30 21:15:51 +00003325 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00003326 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00003327 continue;
3328
3329 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00003330 if (!HandleLValueMember(Info, E, Subobject, *I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003331 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003332
David Blaikie2d7c57e2012-04-30 02:36:29 +00003333 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00003334 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00003335 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00003336 return false;
3337 }
3338
3339 return true;
3340}
3341
3342bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
3343 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00003344 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00003345 if (RD->isUnion()) {
3346 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3347 // object's first non-static named data member is zero-initialized
3348 RecordDecl::field_iterator I = RD->field_begin();
3349 if (I == RD->field_end()) {
3350 Result = APValue((const FieldDecl*)0);
3351 return true;
3352 }
3353
3354 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00003355 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00003356 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00003357 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00003358 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00003359 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00003360 }
3361
Richard Smith5d108602012-02-17 00:44:16 +00003362 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003363 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00003364 return false;
3365 }
3366
Richard Smitha8105bc2012-01-06 16:39:00 +00003367 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00003368}
3369
Richard Smithe97cbd72011-11-11 04:05:33 +00003370bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
3371 switch (E->getCastKind()) {
3372 default:
3373 return ExprEvaluatorBaseTy::VisitCastExpr(E);
3374
3375 case CK_ConstructorConversion:
3376 return Visit(E->getSubExpr());
3377
3378 case CK_DerivedToBase:
3379 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00003380 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003381 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00003382 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003383 if (!DerivedObject.isStruct())
3384 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00003385
3386 // Derived-to-base rvalue conversion: just slice off the derived part.
3387 APValue *Value = &DerivedObject;
3388 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
3389 for (CastExpr::path_const_iterator PathI = E->path_begin(),
3390 PathE = E->path_end(); PathI != PathE; ++PathI) {
3391 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
3392 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
3393 Value = &Value->getStructBase(getBaseIndex(RD, Base));
3394 RD = Base;
3395 }
3396 Result = *Value;
3397 return true;
3398 }
3399 }
3400}
3401
Richard Smithd62306a2011-11-10 06:34:14 +00003402bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Sebastian Redle6c32e62012-02-19 14:53:49 +00003403 // Cannot constant-evaluate std::initializer_list inits.
3404 if (E->initializesStdInitializerList())
3405 return false;
3406
Richard Smithd62306a2011-11-10 06:34:14 +00003407 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00003408 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003409 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3410
3411 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00003412 const FieldDecl *Field = E->getInitializedFieldInUnion();
3413 Result = APValue(Field);
3414 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00003415 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00003416
3417 // If the initializer list for a union does not contain any elements, the
3418 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00003419 // FIXME: The element should be initialized from an initializer list.
3420 // Is this difference ever observable for initializer lists which
3421 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00003422 ImplicitValueInitExpr VIE(Field->getType());
3423 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
3424
Richard Smithd62306a2011-11-10 06:34:14 +00003425 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00003426 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
3427 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00003428
3429 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
3430 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
3431 isa<CXXDefaultInitExpr>(InitExpr));
3432
Richard Smithb228a862012-02-15 02:18:13 +00003433 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00003434 }
3435
3436 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
3437 "initializer list for class with base classes");
3438 Result = APValue(APValue::UninitStruct(), 0,
3439 std::distance(RD->field_begin(), RD->field_end()));
3440 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00003441 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003442 for (RecordDecl::field_iterator Field = RD->field_begin(),
3443 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field) {
3444 // Anonymous bit-fields are not considered members of the class for
3445 // purposes of aggregate initialization.
3446 if (Field->isUnnamedBitfield())
3447 continue;
3448
3449 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00003450
Richard Smith253c2a32012-01-27 01:14:48 +00003451 bool HaveInit = ElementNo < E->getNumInits();
3452
3453 // FIXME: Diagnostics here should point to the end of the initializer
3454 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00003455 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
David Blaikie40ed2972012-06-06 20:45:41 +00003456 Subobject, *Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003457 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003458
3459 // Perform an implicit value-initialization for members beyond the end of
3460 // the initializer list.
3461 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00003462 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00003463
Richard Smith852c9db2013-04-20 22:23:05 +00003464 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
3465 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
3466 isa<CXXDefaultInitExpr>(Init));
3467
3468 if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
3469 Subobject, Init)) {
Richard Smith253c2a32012-01-27 01:14:48 +00003470 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00003471 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003472 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00003473 }
3474 }
3475
Richard Smith253c2a32012-01-27 01:14:48 +00003476 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003477}
3478
3479bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
3480 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00003481 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
3482
Richard Smithfddd3842011-12-30 21:15:51 +00003483 bool ZeroInit = E->requiresZeroInitialization();
3484 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00003485 // If we've already performed zero-initialization, we're already done.
3486 if (!Result.isUninit())
3487 return true;
3488
Richard Smithfddd3842011-12-30 21:15:51 +00003489 if (ZeroInit)
3490 return ZeroInitialization(E);
3491
Richard Smithcc36f692011-12-22 02:22:31 +00003492 const CXXRecordDecl *RD = FD->getParent();
3493 if (RD->isUnion())
3494 Result = APValue((FieldDecl*)0);
3495 else
3496 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
3497 std::distance(RD->field_begin(), RD->field_end()));
3498 return true;
3499 }
3500
Richard Smithd62306a2011-11-10 06:34:14 +00003501 const FunctionDecl *Definition = 0;
3502 FD->getBody(Definition);
3503
Richard Smith357362d2011-12-13 06:39:58 +00003504 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3505 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003506
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003507 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00003508 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00003509 if (const MaterializeTemporaryExpr *ME
3510 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
3511 return Visit(ME->GetTemporaryExpr());
3512
Richard Smithfddd3842011-12-30 21:15:51 +00003513 if (ZeroInit && !ZeroInitialization(E))
3514 return false;
3515
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003516 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00003517 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003518 cast<CXXConstructorDecl>(Definition), Info,
3519 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00003520}
3521
3522static bool EvaluateRecord(const Expr *E, const LValue &This,
3523 APValue &Result, EvalInfo &Info) {
3524 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00003525 "can't evaluate expression as a record rvalue");
3526 return RecordExprEvaluator(Info, This, Result).Visit(E);
3527}
3528
3529//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00003530// Temporary Evaluation
3531//
3532// Temporaries are represented in the AST as rvalues, but generally behave like
3533// lvalues. The full-object of which the temporary is a subobject is implicitly
3534// materialized so that a reference can bind to it.
3535//===----------------------------------------------------------------------===//
3536namespace {
3537class TemporaryExprEvaluator
3538 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
3539public:
3540 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
3541 LValueExprEvaluatorBaseTy(Info, Result) {}
3542
3543 /// Visit an expression which constructs the value of this temporary.
3544 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00003545 Result.set(E, Info.CurrentCall->Index);
3546 return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00003547 }
3548
3549 bool VisitCastExpr(const CastExpr *E) {
3550 switch (E->getCastKind()) {
3551 default:
3552 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
3553
3554 case CK_ConstructorConversion:
3555 return VisitConstructExpr(E->getSubExpr());
3556 }
3557 }
3558 bool VisitInitListExpr(const InitListExpr *E) {
3559 return VisitConstructExpr(E);
3560 }
3561 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
3562 return VisitConstructExpr(E);
3563 }
3564 bool VisitCallExpr(const CallExpr *E) {
3565 return VisitConstructExpr(E);
3566 }
3567};
3568} // end anonymous namespace
3569
3570/// Evaluate an expression of record type as a temporary.
3571static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00003572 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00003573 return TemporaryExprEvaluator(Info, Result).Visit(E);
3574}
3575
3576//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003577// Vector Evaluation
3578//===----------------------------------------------------------------------===//
3579
3580namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003581 class VectorExprEvaluator
Richard Smith2d406342011-10-22 21:10:00 +00003582 : public ExprEvaluatorBase<VectorExprEvaluator, bool> {
3583 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003584 public:
Mike Stump11289f42009-09-09 15:08:12 +00003585
Richard Smith2d406342011-10-22 21:10:00 +00003586 VectorExprEvaluator(EvalInfo &info, APValue &Result)
3587 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00003588
Richard Smith2d406342011-10-22 21:10:00 +00003589 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
3590 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
3591 // FIXME: remove this APValue copy.
3592 Result = APValue(V.data(), V.size());
3593 return true;
3594 }
Richard Smith2e312c82012-03-03 22:46:17 +00003595 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00003596 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00003597 Result = V;
3598 return true;
3599 }
Richard Smithfddd3842011-12-30 21:15:51 +00003600 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00003601
Richard Smith2d406342011-10-22 21:10:00 +00003602 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00003603 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00003604 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00003605 bool VisitInitListExpr(const InitListExpr *E);
3606 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003607 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00003608 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00003609 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003610 };
3611} // end anonymous namespace
3612
3613static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00003614 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00003615 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003616}
3617
Richard Smith2d406342011-10-22 21:10:00 +00003618bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
3619 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003620 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003621
Richard Smith161f09a2011-12-06 22:44:34 +00003622 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00003623 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003624
Eli Friedmanc757de22011-03-25 00:43:55 +00003625 switch (E->getCastKind()) {
3626 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00003627 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00003628 if (SETy->isIntegerType()) {
3629 APSInt IntResult;
3630 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003631 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003632 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00003633 } else if (SETy->isRealFloatingType()) {
3634 APFloat F(0.0);
3635 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00003636 return false;
Richard Smith2d406342011-10-22 21:10:00 +00003637 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00003638 } else {
Richard Smith2d406342011-10-22 21:10:00 +00003639 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003640 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00003641
3642 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00003643 SmallVector<APValue, 4> Elts(NElts, Val);
3644 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00003645 }
Eli Friedman803acb32011-12-22 03:51:45 +00003646 case CK_BitCast: {
3647 // Evaluate the operand into an APInt we can extract from.
3648 llvm::APInt SValInt;
3649 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
3650 return false;
3651 // Extract the elements
3652 QualType EltTy = VTy->getElementType();
3653 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
3654 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
3655 SmallVector<APValue, 4> Elts;
3656 if (EltTy->isRealFloatingType()) {
3657 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00003658 unsigned FloatEltSize = EltSize;
3659 if (&Sem == &APFloat::x87DoubleExtended)
3660 FloatEltSize = 80;
3661 for (unsigned i = 0; i < NElts; i++) {
3662 llvm::APInt Elt;
3663 if (BigEndian)
3664 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
3665 else
3666 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00003667 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00003668 }
3669 } else if (EltTy->isIntegerType()) {
3670 for (unsigned i = 0; i < NElts; i++) {
3671 llvm::APInt Elt;
3672 if (BigEndian)
3673 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
3674 else
3675 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
3676 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
3677 }
3678 } else {
3679 return Error(E);
3680 }
3681 return Success(Elts, E);
3682 }
Eli Friedmanc757de22011-03-25 00:43:55 +00003683 default:
Richard Smith11562c52011-10-28 17:51:58 +00003684 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00003685 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003686}
3687
Richard Smith2d406342011-10-22 21:10:00 +00003688bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003689VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003690 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003691 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00003692 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00003693
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003694 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003695 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003696
Eli Friedmanb9c71292012-01-03 23:24:20 +00003697 // The number of initializers can be less than the number of
3698 // vector elements. For OpenCL, this can be due to nested vector
3699 // initialization. For GCC compatibility, missing trailing elements
3700 // should be initialized with zeroes.
3701 unsigned CountInits = 0, CountElts = 0;
3702 while (CountElts < NumElements) {
3703 // Handle nested vector initialization.
3704 if (CountInits < NumInits
3705 && E->getInit(CountInits)->getType()->isExtVectorType()) {
3706 APValue v;
3707 if (!EvaluateVector(E->getInit(CountInits), v, Info))
3708 return Error(E);
3709 unsigned vlen = v.getVectorLength();
3710 for (unsigned j = 0; j < vlen; j++)
3711 Elements.push_back(v.getVectorElt(j));
3712 CountElts += vlen;
3713 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003714 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003715 if (CountInits < NumInits) {
3716 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00003717 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00003718 } else // trailing integer zero.
3719 sInt = Info.Ctx.MakeIntValue(0, EltTy);
3720 Elements.push_back(APValue(sInt));
3721 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003722 } else {
3723 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00003724 if (CountInits < NumInits) {
3725 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00003726 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00003727 } else // trailing float zero.
3728 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
3729 Elements.push_back(APValue(f));
3730 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00003731 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00003732 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003733 }
Richard Smith2d406342011-10-22 21:10:00 +00003734 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003735}
3736
Richard Smith2d406342011-10-22 21:10:00 +00003737bool
Richard Smithfddd3842011-12-30 21:15:51 +00003738VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00003739 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00003740 QualType EltTy = VT->getElementType();
3741 APValue ZeroElement;
3742 if (EltTy->isIntegerType())
3743 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
3744 else
3745 ZeroElement =
3746 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
3747
Chris Lattner0e62c1c2011-07-23 10:55:15 +00003748 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00003749 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003750}
3751
Richard Smith2d406342011-10-22 21:10:00 +00003752bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00003753 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00003754 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00003755}
3756
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00003757//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00003758// Array Evaluation
3759//===----------------------------------------------------------------------===//
3760
3761namespace {
3762 class ArrayExprEvaluator
3763 : public ExprEvaluatorBase<ArrayExprEvaluator, bool> {
Richard Smithd62306a2011-11-10 06:34:14 +00003764 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00003765 APValue &Result;
3766 public:
3767
Richard Smithd62306a2011-11-10 06:34:14 +00003768 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
3769 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00003770
3771 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00003772 assert((V.isArray() || V.isLValue()) &&
3773 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00003774 Result = V;
3775 return true;
3776 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003777
Richard Smithfddd3842011-12-30 21:15:51 +00003778 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00003779 const ConstantArrayType *CAT =
3780 Info.Ctx.getAsConstantArrayType(E->getType());
3781 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003782 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00003783
3784 Result = APValue(APValue::UninitArray(), 0,
3785 CAT->getSize().getZExtValue());
3786 if (!Result.hasArrayFiller()) return true;
3787
Richard Smithfddd3842011-12-30 21:15:51 +00003788 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00003789 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003790 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00003791 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00003792 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00003793 }
3794
Richard Smithf3e9e432011-11-07 09:22:26 +00003795 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00003796 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003797 };
3798} // end anonymous namespace
3799
Richard Smithd62306a2011-11-10 06:34:14 +00003800static bool EvaluateArray(const Expr *E, const LValue &This,
3801 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00003802 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00003803 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003804}
3805
3806bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
3807 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
3808 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00003809 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00003810
Richard Smithca2cfbf2011-12-22 01:07:19 +00003811 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
3812 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00003813 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00003814 LValue LV;
3815 if (!EvaluateLValue(E->getInit(0), LV, Info))
3816 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003817 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00003818 LV.moveInto(Val);
3819 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00003820 }
3821
Richard Smith253c2a32012-01-27 01:14:48 +00003822 bool Success = true;
3823
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003824 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
3825 "zero-initialized array shouldn't have any initialized elts");
3826 APValue Filler;
3827 if (Result.isArray() && Result.hasArrayFiller())
3828 Filler = Result.getArrayFiller();
3829
Richard Smithf3e9e432011-11-07 09:22:26 +00003830 Result = APValue(APValue::UninitArray(), E->getNumInits(),
3831 CAT->getSize().getZExtValue());
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003832
3833 // If the array was previously zero-initialized, preserve the
3834 // zero-initialized values.
3835 if (!Filler.isUninit()) {
3836 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
3837 Result.getArrayInitializedElt(I) = Filler;
3838 if (Result.hasArrayFiller())
3839 Result.getArrayFiller() = Filler;
3840 }
3841
Richard Smithd62306a2011-11-10 06:34:14 +00003842 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00003843 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00003844 unsigned Index = 0;
Richard Smithf3e9e432011-11-07 09:22:26 +00003845 for (InitListExpr::const_iterator I = E->begin(), End = E->end();
Richard Smithd62306a2011-11-10 06:34:14 +00003846 I != End; ++I, ++Index) {
Richard Smithb228a862012-02-15 02:18:13 +00003847 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
3848 Info, Subobject, cast<Expr>(*I)) ||
Richard Smith253c2a32012-01-27 01:14:48 +00003849 !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
3850 CAT->getElementType(), 1)) {
3851 if (!Info.keepEvaluatingAfterFailure())
3852 return false;
3853 Success = false;
3854 }
Richard Smithd62306a2011-11-10 06:34:14 +00003855 }
Richard Smithf3e9e432011-11-07 09:22:26 +00003856
Richard Smith253c2a32012-01-27 01:14:48 +00003857 if (!Result.hasArrayFiller()) return Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00003858 assert(E->hasArrayFiller() && "no array filler for incomplete init list");
Richard Smithd62306a2011-11-10 06:34:14 +00003859 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3860 // but sometimes does:
3861 // struct S { constexpr S() : p(&p) {} void *p; };
3862 // S s[10] = {};
Richard Smithb228a862012-02-15 02:18:13 +00003863 return EvaluateInPlace(Result.getArrayFiller(), Info,
3864 Subobject, E->getArrayFiller()) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00003865}
3866
Richard Smith027bf112011-11-17 22:56:20 +00003867bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003868 // FIXME: The Subobject here isn't necessarily right. This rarely matters,
3869 // but sometimes does:
3870 // struct S { constexpr S() : p(&p) {} void *p; };
3871 // S s[10];
3872 LValue Subobject = This;
3873
3874 APValue *Value = &Result;
3875 bool HadZeroInit = true;
Richard Smith9fce7bc2012-07-10 22:12:55 +00003876 QualType ElemTy = E->getType();
3877 while (const ConstantArrayType *CAT =
3878 Info.Ctx.getAsConstantArrayType(ElemTy)) {
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003879 Subobject.addArray(Info, E, CAT);
3880 HadZeroInit &= !Value->isUninit();
3881 if (!HadZeroInit)
3882 *Value = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
3883 if (!Value->hasArrayFiller())
3884 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003885 Value = &Value->getArrayFiller();
Richard Smith9fce7bc2012-07-10 22:12:55 +00003886 ElemTy = CAT->getElementType();
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003887 }
Richard Smith027bf112011-11-17 22:56:20 +00003888
Richard Smith9fce7bc2012-07-10 22:12:55 +00003889 if (!ElemTy->isRecordType())
3890 return Error(E);
3891
Richard Smith027bf112011-11-17 22:56:20 +00003892 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00003893
Richard Smithfddd3842011-12-30 21:15:51 +00003894 bool ZeroInit = E->requiresZeroInitialization();
3895 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00003896 if (HadZeroInit)
3897 return true;
3898
Richard Smithfddd3842011-12-30 21:15:51 +00003899 if (ZeroInit) {
Richard Smith9fce7bc2012-07-10 22:12:55 +00003900 ImplicitValueInitExpr VIE(ElemTy);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003901 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00003902 }
3903
Richard Smithcc36f692011-12-22 02:22:31 +00003904 const CXXRecordDecl *RD = FD->getParent();
3905 if (RD->isUnion())
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003906 *Value = APValue((FieldDecl*)0);
Richard Smithcc36f692011-12-22 02:22:31 +00003907 else
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003908 *Value =
Richard Smithcc36f692011-12-22 02:22:31 +00003909 APValue(APValue::UninitStruct(), RD->getNumBases(),
3910 std::distance(RD->field_begin(), RD->field_end()));
3911 return true;
3912 }
3913
Richard Smith027bf112011-11-17 22:56:20 +00003914 const FunctionDecl *Definition = 0;
3915 FD->getBody(Definition);
3916
Richard Smith357362d2011-12-13 06:39:58 +00003917 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
3918 return false;
Richard Smith027bf112011-11-17 22:56:20 +00003919
Richard Smith9eae7232012-01-12 18:54:33 +00003920 if (ZeroInit && !HadZeroInit) {
Richard Smith9fce7bc2012-07-10 22:12:55 +00003921 ImplicitValueInitExpr VIE(ElemTy);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003922 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00003923 return false;
3924 }
3925
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003926 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00003927 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00003928 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00003929 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00003930}
3931
Richard Smithf3e9e432011-11-07 09:22:26 +00003932//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003933// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00003934//
3935// As a GNU extension, we support casting pointers to sufficiently-wide integer
3936// types and back in constant folding. Integer values are thus represented
3937// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00003938//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00003939
3940namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00003941class IntExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00003942 : public ExprEvaluatorBase<IntExprEvaluator, bool> {
Richard Smith2e312c82012-03-03 22:46:17 +00003943 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00003944public:
Richard Smith2e312c82012-03-03 22:46:17 +00003945 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00003946 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00003947
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003948 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003949 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00003950 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003951 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003952 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00003953 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003954 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00003955 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003956 return true;
3957 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003958 bool Success(const llvm::APSInt &SI, const Expr *E) {
3959 return Success(SI, E, Result);
3960 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003961
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003962 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003963 assert(E->getType()->isIntegralOrEnumerationType() &&
3964 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00003965 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00003966 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00003967 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00003968 Result.getInt().setIsUnsigned(
3969 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003970 return true;
3971 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003972 bool Success(const llvm::APInt &I, const Expr *E) {
3973 return Success(I, E, Result);
3974 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003975
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003976 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00003977 assert(E->getType()->isIntegralOrEnumerationType() &&
3978 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00003979 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003980 return true;
3981 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003982 bool Success(uint64_t Value, const Expr *E) {
3983 return Success(Value, E, Result);
3984 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00003985
Ken Dyckdbc01912011-03-11 02:13:43 +00003986 bool Success(CharUnits Size, const Expr *E) {
3987 return Success(Size.getQuantity(), E);
3988 }
3989
Richard Smith2e312c82012-03-03 22:46:17 +00003990 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00003991 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00003992 Result = V;
3993 return true;
3994 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003995 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00003996 }
Mike Stump11289f42009-09-09 15:08:12 +00003997
Richard Smithfddd3842011-12-30 21:15:51 +00003998 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00003999
Peter Collingbournee9200682011-05-13 03:29:01 +00004000 //===--------------------------------------------------------------------===//
4001 // Visitor Methods
4002 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004003
Chris Lattner7174bf32008-07-12 00:38:25 +00004004 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004005 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004006 }
4007 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004008 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00004009 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004010
4011 bool CheckReferencedDecl(const Expr *E, const Decl *D);
4012 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00004013 if (CheckReferencedDecl(E, E->getDecl()))
4014 return true;
4015
4016 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004017 }
4018 bool VisitMemberExpr(const MemberExpr *E) {
4019 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00004020 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004021 return true;
4022 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004023
4024 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004025 }
4026
Peter Collingbournee9200682011-05-13 03:29:01 +00004027 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004028 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00004029 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00004030 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00004031
Peter Collingbournee9200682011-05-13 03:29:01 +00004032 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00004033 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00004034
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004035 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004036 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004037 }
Mike Stump11289f42009-09-09 15:08:12 +00004038
Ted Kremeneke65b0862012-03-06 20:05:56 +00004039 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
4040 return Success(E->getValue(), E);
4041 }
4042
Richard Smith4ce706a2011-10-11 21:43:33 +00004043 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00004044 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004045 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004046 }
4047
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004048 bool VisitUnaryTypeTraitExpr(const UnaryTypeTraitExpr *E) {
Sebastian Redl8eb06f12010-09-13 20:56:31 +00004049 return Success(E->getValue(), E);
Sebastian Redlbaad4e72009-01-05 20:52:13 +00004050 }
4051
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00004052 bool VisitBinaryTypeTraitExpr(const BinaryTypeTraitExpr *E) {
4053 return Success(E->getValue(), E);
4054 }
4055
Douglas Gregor29c42f22012-02-24 07:38:34 +00004056 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
4057 return Success(E->getValue(), E);
4058 }
4059
John Wiegley6242b6a2011-04-28 00:16:57 +00004060 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
4061 return Success(E->getValue(), E);
4062 }
4063
John Wiegleyf9f65842011-04-25 06:54:41 +00004064 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
4065 return Success(E->getValue(), E);
4066 }
4067
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00004068 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004069 bool VisitUnaryImag(const UnaryOperator *E);
4070
Sebastian Redl5f0180d2010-09-10 20:55:47 +00004071 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00004072 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00004073
Chris Lattnerf8d7f722008-07-11 21:24:13 +00004074private:
Ken Dyck160146e2010-01-27 17:10:57 +00004075 CharUnits GetAlignOfExpr(const Expr *E);
4076 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00004077 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00004078 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00004079 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00004080};
Chris Lattner05706e882008-07-11 18:11:29 +00004081} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004082
Richard Smith11562c52011-10-28 17:51:58 +00004083/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
4084/// produce either the integer value or a pointer.
4085///
4086/// GCC has a heinous extension which folds casts between pointer types and
4087/// pointer-sized integral types. We support this by allowing the evaluation of
4088/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
4089/// Some simple arithmetic on such values is supported (they are treated much
4090/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00004091static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00004092 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004093 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004094 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00004095}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004096
Richard Smithf57d8cb2011-12-09 22:58:01 +00004097static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00004098 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004099 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00004100 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004101 if (!Val.isInt()) {
4102 // FIXME: It would be better to produce the diagnostic for casting
4103 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00004104 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004105 return false;
4106 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00004107 Result = Val.getInt();
4108 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004109}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004110
Richard Smithf57d8cb2011-12-09 22:58:01 +00004111/// Check whether the given declaration can be directly converted to an integral
4112/// rvalue. If not, no diagnostic is produced; there are other things we can
4113/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00004114bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00004115 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004116 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00004117 // Check for signedness/width mismatches between E type and ECD value.
4118 bool SameSign = (ECD->getInitVal().isSigned()
4119 == E->getType()->isSignedIntegerOrEnumerationType());
4120 bool SameWidth = (ECD->getInitVal().getBitWidth()
4121 == Info.Ctx.getIntWidth(E->getType()));
4122 if (SameSign && SameWidth)
4123 return Success(ECD->getInitVal(), E);
4124 else {
4125 // Get rid of mismatch (otherwise Success assertions will fail)
4126 // by computing a new value matching the type of E.
4127 llvm::APSInt Val = ECD->getInitVal();
4128 if (!SameSign)
4129 Val.setIsSigned(!ECD->getInitVal().isSigned());
4130 if (!SameWidth)
4131 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
4132 return Success(Val, E);
4133 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00004134 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004135 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00004136}
4137
Chris Lattner86ee2862008-10-06 06:40:35 +00004138/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
4139/// as GCC.
4140static int EvaluateBuiltinClassifyType(const CallExpr *E) {
4141 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00004142 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00004143 enum gcc_type_class {
4144 no_type_class = -1,
4145 void_type_class, integer_type_class, char_type_class,
4146 enumeral_type_class, boolean_type_class,
4147 pointer_type_class, reference_type_class, offset_type_class,
4148 real_type_class, complex_type_class,
4149 function_type_class, method_type_class,
4150 record_type_class, union_type_class,
4151 array_type_class, string_type_class,
4152 lang_type_class
4153 };
Mike Stump11289f42009-09-09 15:08:12 +00004154
4155 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00004156 // ideal, however it is what gcc does.
4157 if (E->getNumArgs() == 0)
4158 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00004159
Chris Lattner86ee2862008-10-06 06:40:35 +00004160 QualType ArgTy = E->getArg(0)->getType();
4161 if (ArgTy->isVoidType())
4162 return void_type_class;
4163 else if (ArgTy->isEnumeralType())
4164 return enumeral_type_class;
4165 else if (ArgTy->isBooleanType())
4166 return boolean_type_class;
4167 else if (ArgTy->isCharType())
4168 return string_type_class; // gcc doesn't appear to use char_type_class
4169 else if (ArgTy->isIntegerType())
4170 return integer_type_class;
4171 else if (ArgTy->isPointerType())
4172 return pointer_type_class;
4173 else if (ArgTy->isReferenceType())
4174 return reference_type_class;
4175 else if (ArgTy->isRealType())
4176 return real_type_class;
4177 else if (ArgTy->isComplexType())
4178 return complex_type_class;
4179 else if (ArgTy->isFunctionType())
4180 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00004181 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00004182 return record_type_class;
4183 else if (ArgTy->isUnionType())
4184 return union_type_class;
4185 else if (ArgTy->isArrayType())
4186 return array_type_class;
4187 else if (ArgTy->isUnionType())
4188 return union_type_class;
4189 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00004190 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00004191}
4192
Richard Smith5fab0c92011-12-28 19:48:30 +00004193/// EvaluateBuiltinConstantPForLValue - Determine the result of
4194/// __builtin_constant_p when applied to the given lvalue.
4195///
4196/// An lvalue is only "constant" if it is a pointer or reference to the first
4197/// character of a string literal.
4198template<typename LValue>
4199static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00004200 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00004201 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
4202}
4203
4204/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
4205/// GCC as we can manage.
4206static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
4207 QualType ArgType = Arg->getType();
4208
4209 // __builtin_constant_p always has one operand. The rules which gcc follows
4210 // are not precisely documented, but are as follows:
4211 //
4212 // - If the operand is of integral, floating, complex or enumeration type,
4213 // and can be folded to a known value of that type, it returns 1.
4214 // - If the operand and can be folded to a pointer to the first character
4215 // of a string literal (or such a pointer cast to an integral type), it
4216 // returns 1.
4217 //
4218 // Otherwise, it returns 0.
4219 //
4220 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
4221 // its support for this does not currently work.
4222 if (ArgType->isIntegralOrEnumerationType()) {
4223 Expr::EvalResult Result;
4224 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
4225 return false;
4226
4227 APValue &V = Result.Val;
4228 if (V.getKind() == APValue::Int)
4229 return true;
4230
4231 return EvaluateBuiltinConstantPForLValue(V);
4232 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
4233 return Arg->isEvaluatable(Ctx);
4234 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
4235 LValue LV;
4236 Expr::EvalStatus Status;
4237 EvalInfo Info(Ctx, Status);
4238 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
4239 : EvaluatePointer(Arg, LV, Info)) &&
4240 !Status.HasSideEffects)
4241 return EvaluateBuiltinConstantPForLValue(LV);
4242 }
4243
4244 // Anything else isn't considered to be sufficiently constant.
4245 return false;
4246}
4247
John McCall95007602010-05-10 23:27:23 +00004248/// Retrieves the "underlying object type" of the given expression,
4249/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00004250QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
4251 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
4252 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00004253 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00004254 } else if (const Expr *E = B.get<const Expr*>()) {
4255 if (isa<CompoundLiteralExpr>(E))
4256 return E->getType();
John McCall95007602010-05-10 23:27:23 +00004257 }
4258
4259 return QualType();
4260}
4261
Peter Collingbournee9200682011-05-13 03:29:01 +00004262bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00004263 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00004264
4265 {
4266 // The operand of __builtin_object_size is never evaluated for side-effects.
4267 // If there are any, but we can determine the pointed-to object anyway, then
4268 // ignore the side-effects.
4269 SpeculativeEvaluationRAII SpeculativeEval(Info);
4270 if (!EvaluatePointer(E->getArg(0), Base, Info))
4271 return false;
4272 }
John McCall95007602010-05-10 23:27:23 +00004273
4274 // If we can prove the base is null, lower to zero now.
Richard Smithce40ad62011-11-12 22:28:03 +00004275 if (!Base.getLValueBase()) return Success(0, E);
John McCall95007602010-05-10 23:27:23 +00004276
Richard Smithce40ad62011-11-12 22:28:03 +00004277 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00004278 if (T.isNull() ||
4279 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00004280 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00004281 T->isVariablyModifiedType() ||
4282 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004283 return Error(E);
John McCall95007602010-05-10 23:27:23 +00004284
4285 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
4286 CharUnits Offset = Base.getLValueOffset();
4287
4288 if (!Offset.isNegative() && Offset <= Size)
4289 Size -= Offset;
4290 else
4291 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00004292 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00004293}
4294
Peter Collingbournee9200682011-05-13 03:29:01 +00004295bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith01ba47d2012-04-13 00:45:38 +00004296 switch (unsigned BuiltinOp = E->isBuiltinCall()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004297 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00004298 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004299
4300 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00004301 if (TryEvaluateBuiltinObjectSize(E))
4302 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00004303
Richard Smith0421ce72012-08-07 04:16:51 +00004304 // If evaluating the argument has side-effects, we can't determine the size
4305 // of the object, and so we lower it to unknown now. CodeGen relies on us to
4306 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00004307 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00004308 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00004309 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00004310 return Success(0, E);
4311 }
Mike Stump876387b2009-10-27 22:09:17 +00004312
Richard Smith01ade172012-05-23 04:13:20 +00004313 // Expression had no side effects, but we couldn't statically determine the
4314 // size of the referenced object.
Richard Smithf57d8cb2011-12-09 22:58:01 +00004315 return Error(E);
Mike Stump722cedf2009-10-26 18:35:08 +00004316 }
4317
Benjamin Kramera801f4a2012-10-06 14:42:22 +00004318 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00004319 case Builtin::BI__builtin_bswap32:
4320 case Builtin::BI__builtin_bswap64: {
4321 APSInt Val;
4322 if (!EvaluateInteger(E->getArg(0), Val, Info))
4323 return false;
4324
4325 return Success(Val.byteSwap(), E);
4326 }
4327
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004328 case Builtin::BI__builtin_classify_type:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004329 return Success(EvaluateBuiltinClassifyType(E), E);
Mike Stump11289f42009-09-09 15:08:12 +00004330
Richard Smith5fab0c92011-12-28 19:48:30 +00004331 case Builtin::BI__builtin_constant_p:
4332 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
Richard Smith10c7c902011-12-09 02:04:48 +00004333
Chris Lattnerd545ad12009-09-23 06:06:36 +00004334 case Builtin::BI__builtin_eh_return_data_regno: {
Richard Smithcaf33902011-10-10 18:28:20 +00004335 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
Douglas Gregore8bbc122011-09-02 00:18:52 +00004336 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
Chris Lattnerd545ad12009-09-23 06:06:36 +00004337 return Success(Operand, E);
4338 }
Eli Friedmand5c93992010-02-13 00:10:10 +00004339
4340 case Builtin::BI__builtin_expect:
4341 return Visit(E->getArg(0));
Richard Smith9cf080f2012-01-18 03:06:12 +00004342
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004343 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00004344 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004345 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00004346 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00004347 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
4348 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00004349 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00004350 // Fall through.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004351 case Builtin::BI__builtin_strlen:
4352 // As an extension, we support strlen() and __builtin_strlen() as constant
4353 // expressions when the argument is a string literal.
Peter Collingbournee9200682011-05-13 03:29:01 +00004354 if (const StringLiteral *S
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004355 = dyn_cast<StringLiteral>(E->getArg(0)->IgnoreParenImpCasts())) {
4356 // The string literal may have embedded null characters. Find the first
4357 // one and truncate there.
Chris Lattner0e62c1c2011-07-23 10:55:15 +00004358 StringRef Str = S->getString();
4359 StringRef::size_type Pos = Str.find(0);
4360 if (Pos != StringRef::npos)
Douglas Gregor6a6dac22010-09-10 06:27:15 +00004361 Str = Str.substr(0, Pos);
4362
4363 return Success(Str.size(), E);
4364 }
4365
Richard Smithf57d8cb2011-12-09 22:58:01 +00004366 return Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004367
Richard Smith01ba47d2012-04-13 00:45:38 +00004368 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00004369 case Builtin::BI__atomic_is_lock_free:
4370 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00004371 APSInt SizeVal;
4372 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
4373 return false;
4374
4375 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
4376 // of two less than the maximum inline atomic width, we know it is
4377 // lock-free. If the size isn't a power of two, or greater than the
4378 // maximum alignment where we promote atomics, we know it is not lock-free
4379 // (at least not in the sense of atomic_is_lock_free). Otherwise,
4380 // the answer can only be determined at runtime; for example, 16-byte
4381 // atomics have lock-free implementations on some, but not all,
4382 // x86-64 processors.
4383
4384 // Check power-of-two.
4385 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00004386 if (Size.isPowerOfTwo()) {
4387 // Check against inlining width.
4388 unsigned InlineWidthBits =
4389 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
4390 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
4391 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
4392 Size == CharUnits::One() ||
4393 E->getArg(1)->isNullPointerConstant(Info.Ctx,
4394 Expr::NPC_NeverValueDependent))
4395 // OK, we will inline appropriately-aligned operations of this size,
4396 // and _Atomic(T) is appropriately-aligned.
4397 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004398
Richard Smith01ba47d2012-04-13 00:45:38 +00004399 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
4400 castAs<PointerType>()->getPointeeType();
4401 if (!PointeeType->isIncompleteType() &&
4402 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
4403 // OK, we will inline operations on this object.
4404 return Success(1, E);
4405 }
4406 }
4407 }
Eli Friedmana4c26022011-10-17 21:44:23 +00004408
Richard Smith01ba47d2012-04-13 00:45:38 +00004409 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
4410 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00004411 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00004412 }
Chris Lattner7174bf32008-07-12 00:38:25 +00004413}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004414
Richard Smith8b3497e2011-10-31 01:37:14 +00004415static bool HasSameBase(const LValue &A, const LValue &B) {
4416 if (!A.getLValueBase())
4417 return !B.getLValueBase();
4418 if (!B.getLValueBase())
4419 return false;
4420
Richard Smithce40ad62011-11-12 22:28:03 +00004421 if (A.getLValueBase().getOpaqueValue() !=
4422 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00004423 const Decl *ADecl = GetLValueBaseDecl(A);
4424 if (!ADecl)
4425 return false;
4426 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00004427 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00004428 return false;
4429 }
4430
4431 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00004432 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00004433}
4434
Richard Smithc8042322012-02-01 05:53:12 +00004435/// Perform the given integer operation, which is known to need at most BitWidth
4436/// bits, and check for overflow in the original type (if that type was not an
4437/// unsigned type).
4438template<typename Operation>
4439static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
4440 const APSInt &LHS, const APSInt &RHS,
4441 unsigned BitWidth, Operation Op) {
4442 if (LHS.isUnsigned())
4443 return Op(LHS, RHS);
4444
4445 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
4446 APSInt Result = Value.trunc(LHS.getBitWidth());
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00004447 if (Result.extend(BitWidth) != Value) {
4448 if (Info.getIntOverflowCheckMode())
4449 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
4450 diag::warn_integer_constant_overflow)
4451 << Result.toString(10) << E->getType();
4452 else
4453 HandleOverflow(Info, E, Value, E->getType());
4454 }
Richard Smithc8042322012-02-01 05:53:12 +00004455 return Result;
4456}
4457
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004458namespace {
Richard Smith11562c52011-10-28 17:51:58 +00004459
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004460/// \brief Data recursive integer evaluator of certain binary operators.
4461///
4462/// We use a data recursive algorithm for binary operators so that we are able
4463/// to handle extreme cases of chained binary operators without causing stack
4464/// overflow.
4465class DataRecursiveIntBinOpEvaluator {
4466 struct EvalResult {
4467 APValue Val;
4468 bool Failed;
4469
4470 EvalResult() : Failed(false) { }
4471
4472 void swap(EvalResult &RHS) {
4473 Val.swap(RHS.Val);
4474 Failed = RHS.Failed;
4475 RHS.Failed = false;
4476 }
4477 };
4478
4479 struct Job {
4480 const Expr *E;
4481 EvalResult LHSResult; // meaningful only for binary operator expression.
4482 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
4483
4484 Job() : StoredInfo(0) { }
4485 void startSpeculativeEval(EvalInfo &Info) {
4486 OldEvalStatus = Info.EvalStatus;
4487 Info.EvalStatus.Diag = 0;
4488 StoredInfo = &Info;
4489 }
4490 ~Job() {
4491 if (StoredInfo) {
4492 StoredInfo->EvalStatus = OldEvalStatus;
4493 }
4494 }
4495 private:
4496 EvalInfo *StoredInfo; // non-null if status changed.
4497 Expr::EvalStatus OldEvalStatus;
4498 };
4499
4500 SmallVector<Job, 16> Queue;
4501
4502 IntExprEvaluator &IntEval;
4503 EvalInfo &Info;
4504 APValue &FinalResult;
4505
4506public:
4507 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
4508 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
4509
4510 /// \brief True if \param E is a binary operator that we are going to handle
4511 /// data recursively.
4512 /// We handle binary operators that are comma, logical, or that have operands
4513 /// with integral or enumeration type.
4514 static bool shouldEnqueue(const BinaryOperator *E) {
4515 return E->getOpcode() == BO_Comma ||
4516 E->isLogicalOp() ||
4517 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4518 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00004519 }
4520
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004521 bool Traverse(const BinaryOperator *E) {
4522 enqueue(E);
4523 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00004524 while (!Queue.empty())
4525 process(PrevResult);
4526
4527 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004528
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004529 FinalResult.swap(PrevResult.Val);
4530 return true;
4531 }
4532
4533private:
4534 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
4535 return IntEval.Success(Value, E, Result);
4536 }
4537 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
4538 return IntEval.Success(Value, E, Result);
4539 }
4540 bool Error(const Expr *E) {
4541 return IntEval.Error(E);
4542 }
4543 bool Error(const Expr *E, diag::kind D) {
4544 return IntEval.Error(E, D);
4545 }
4546
4547 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
4548 return Info.CCEDiag(E, D);
4549 }
4550
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004551 // \brief Returns true if visiting the RHS is necessary, false otherwise.
4552 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004553 bool &SuppressRHSDiags);
4554
4555 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4556 const BinaryOperator *E, APValue &Result);
4557
4558 void EvaluateExpr(const Expr *E, EvalResult &Result) {
4559 Result.Failed = !Evaluate(Result.Val, Info, E);
4560 if (Result.Failed)
4561 Result.Val = APValue();
4562 }
4563
Richard Trieuba4d0872012-03-21 23:30:30 +00004564 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004565
4566 void enqueue(const Expr *E) {
4567 E = E->IgnoreParens();
4568 Queue.resize(Queue.size()+1);
4569 Queue.back().E = E;
4570 Queue.back().Kind = Job::AnyExprKind;
4571 }
4572};
4573
4574}
4575
4576bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004577 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004578 bool &SuppressRHSDiags) {
4579 if (E->getOpcode() == BO_Comma) {
4580 // Ignore LHS but note if we could not evaluate it.
4581 if (LHSResult.Failed)
4582 Info.EvalStatus.HasSideEffects = true;
4583 return true;
4584 }
4585
4586 if (E->isLogicalOp()) {
4587 bool lhsResult;
4588 if (HandleConversionToBool(LHSResult.Val, lhsResult)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004589 // We were able to evaluate the LHS, see if we can get away with not
4590 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004591 if (lhsResult == (E->getOpcode() == BO_LOr)) {
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004592 Success(lhsResult, E, LHSResult.Val);
4593 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004594 }
4595 } else {
4596 // Since we weren't able to evaluate the left hand side, it
4597 // must have had side effects.
4598 Info.EvalStatus.HasSideEffects = true;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004599
4600 // We can't evaluate the LHS; however, sometimes the result
4601 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4602 // Don't ignore RHS and suppress diagnostics from this arm.
4603 SuppressRHSDiags = true;
4604 }
4605
4606 return true;
4607 }
4608
4609 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4610 E->getRHS()->getType()->isIntegralOrEnumerationType());
4611
4612 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004613 return false; // Ignore RHS;
4614
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004615 return true;
4616}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004617
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004618bool DataRecursiveIntBinOpEvaluator::
4619 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
4620 const BinaryOperator *E, APValue &Result) {
4621 if (E->getOpcode() == BO_Comma) {
4622 if (RHSResult.Failed)
4623 return false;
4624 Result = RHSResult.Val;
4625 return true;
4626 }
4627
4628 if (E->isLogicalOp()) {
4629 bool lhsResult, rhsResult;
4630 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
4631 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
4632
4633 if (LHSIsOK) {
4634 if (RHSIsOK) {
4635 if (E->getOpcode() == BO_LOr)
4636 return Success(lhsResult || rhsResult, E, Result);
4637 else
4638 return Success(lhsResult && rhsResult, E, Result);
4639 }
4640 } else {
4641 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004642 // We can't evaluate the LHS; however, sometimes the result
4643 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
4644 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004645 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004646 }
4647 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004648
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00004649 return false;
4650 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004651
4652 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
4653 E->getRHS()->getType()->isIntegralOrEnumerationType());
4654
4655 if (LHSResult.Failed || RHSResult.Failed)
4656 return false;
4657
4658 const APValue &LHSVal = LHSResult.Val;
4659 const APValue &RHSVal = RHSResult.Val;
4660
4661 // Handle cases like (unsigned long)&a + 4.
4662 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
4663 Result = LHSVal;
4664 CharUnits AdditionalOffset = CharUnits::fromQuantity(
4665 RHSVal.getInt().getZExtValue());
4666 if (E->getOpcode() == BO_Add)
4667 Result.getLValueOffset() += AdditionalOffset;
4668 else
4669 Result.getLValueOffset() -= AdditionalOffset;
4670 return true;
4671 }
4672
4673 // Handle cases like 4 + (unsigned long)&a
4674 if (E->getOpcode() == BO_Add &&
4675 RHSVal.isLValue() && LHSVal.isInt()) {
4676 Result = RHSVal;
4677 Result.getLValueOffset() += CharUnits::fromQuantity(
4678 LHSVal.getInt().getZExtValue());
4679 return true;
4680 }
4681
4682 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
4683 // Handle (intptr_t)&&A - (intptr_t)&&B.
4684 if (!LHSVal.getLValueOffset().isZero() ||
4685 !RHSVal.getLValueOffset().isZero())
4686 return false;
4687 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
4688 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
4689 if (!LHSExpr || !RHSExpr)
4690 return false;
4691 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4692 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4693 if (!LHSAddrExpr || !RHSAddrExpr)
4694 return false;
4695 // Make sure both labels come from the same function.
4696 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4697 RHSAddrExpr->getLabel()->getDeclContext())
4698 return false;
4699 Result = APValue(LHSAddrExpr, RHSAddrExpr);
4700 return true;
4701 }
4702
4703 // All the following cases expect both operands to be an integer
4704 if (!LHSVal.isInt() || !RHSVal.isInt())
4705 return Error(E);
4706
4707 const APSInt &LHS = LHSVal.getInt();
4708 APSInt RHS = RHSVal.getInt();
4709
4710 switch (E->getOpcode()) {
4711 default:
4712 return Error(E);
4713 case BO_Mul:
4714 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4715 LHS.getBitWidth() * 2,
4716 std::multiplies<APSInt>()), E,
4717 Result);
4718 case BO_Add:
4719 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4720 LHS.getBitWidth() + 1,
4721 std::plus<APSInt>()), E, Result);
4722 case BO_Sub:
4723 return Success(CheckedIntArithmetic(Info, E, LHS, RHS,
4724 LHS.getBitWidth() + 1,
4725 std::minus<APSInt>()), E, Result);
4726 case BO_And: return Success(LHS & RHS, E, Result);
4727 case BO_Xor: return Success(LHS ^ RHS, E, Result);
4728 case BO_Or: return Success(LHS | RHS, E, Result);
4729 case BO_Div:
4730 case BO_Rem:
4731 if (RHS == 0)
4732 return Error(E, diag::note_expr_divide_by_zero);
4733 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. The latter is
4734 // not actually undefined behavior in C++11 due to a language defect.
4735 if (RHS.isNegative() && RHS.isAllOnesValue() &&
4736 LHS.isSigned() && LHS.isMinSignedValue())
4737 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
4738 return Success(E->getOpcode() == BO_Rem ? LHS % RHS : LHS / RHS, E,
4739 Result);
4740 case BO_Shl: {
David Tweed042e0882013-01-07 16:43:27 +00004741 if (Info.getLangOpts().OpenCL)
4742 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00004743 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00004744 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
4745 RHS.isUnsigned());
4746 else if (RHS.isSigned() && RHS.isNegative()) {
4747 // During constant-folding, a negative shift is an opposite shift. Such
4748 // a shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004749 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4750 RHS = -RHS;
4751 goto shift_right;
4752 }
4753
4754 shift_left:
4755 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
4756 // the shifted type.
4757 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4758 if (SA != RHS) {
4759 CCEDiag(E, diag::note_constexpr_large_shift)
4760 << RHS << E->getType() << LHS.getBitWidth();
4761 } else if (LHS.isSigned()) {
4762 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
4763 // operand, and must not overflow the corresponding unsigned type.
4764 if (LHS.isNegative())
4765 CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
4766 else if (LHS.countLeadingZeros() < SA)
4767 CCEDiag(E, diag::note_constexpr_lshift_discards);
4768 }
4769
4770 return Success(LHS << SA, E, Result);
4771 }
4772 case BO_Shr: {
David Tweed042e0882013-01-07 16:43:27 +00004773 if (Info.getLangOpts().OpenCL)
4774 // OpenCL 6.3j: shift values are effectively % word size of LHS.
Joey Gouly0942e0b2013-01-29 15:09:40 +00004775 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
David Tweed042e0882013-01-07 16:43:27 +00004776 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
4777 RHS.isUnsigned());
4778 else if (RHS.isSigned() && RHS.isNegative()) {
4779 // During constant-folding, a negative shift is an opposite shift. Such a
4780 // shift is not a constant expression.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004781 CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
4782 RHS = -RHS;
4783 goto shift_left;
4784 }
4785
4786 shift_right:
4787 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
4788 // shifted type.
4789 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
4790 if (SA != RHS)
4791 CCEDiag(E, diag::note_constexpr_large_shift)
4792 << RHS << E->getType() << LHS.getBitWidth();
4793
4794 return Success(LHS >> SA, E, Result);
4795 }
4796
4797 case BO_LT: return Success(LHS < RHS, E, Result);
4798 case BO_GT: return Success(LHS > RHS, E, Result);
4799 case BO_LE: return Success(LHS <= RHS, E, Result);
4800 case BO_GE: return Success(LHS >= RHS, E, Result);
4801 case BO_EQ: return Success(LHS == RHS, E, Result);
4802 case BO_NE: return Success(LHS != RHS, E, Result);
4803 }
4804}
4805
Richard Trieuba4d0872012-03-21 23:30:30 +00004806void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004807 Job &job = Queue.back();
4808
4809 switch (job.Kind) {
4810 case Job::AnyExprKind: {
4811 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
4812 if (shouldEnqueue(Bop)) {
4813 job.Kind = Job::BinOpKind;
4814 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00004815 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004816 }
4817 }
4818
4819 EvaluateExpr(job.E, Result);
4820 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00004821 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004822 }
4823
4824 case Job::BinOpKind: {
4825 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004826 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004827 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
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 if (SuppressRHSDiags)
4832 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00004833 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004834 job.Kind = Job::BinOpVisitedLHSKind;
4835 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00004836 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004837 }
4838
4839 case Job::BinOpVisitedLHSKind: {
4840 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
4841 EvalResult RHS;
4842 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00004843 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004844 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00004845 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004846 }
4847 }
4848
4849 llvm_unreachable("Invalid Job::Kind!");
4850}
4851
4852bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
4853 if (E->isAssignmentOp())
4854 return Error(E);
4855
4856 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
4857 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00004858
Anders Carlssonacc79812008-11-16 07:17:21 +00004859 QualType LHSTy = E->getLHS()->getType();
4860 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004861
4862 if (LHSTy->isAnyComplexType()) {
4863 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00004864 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004865
Richard Smith253c2a32012-01-27 01:14:48 +00004866 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
4867 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004868 return false;
4869
Richard Smith253c2a32012-01-27 01:14:48 +00004870 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004871 return false;
4872
4873 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00004874 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004875 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00004876 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004877 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
4878
John McCalle3027922010-08-25 11:45:40 +00004879 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004880 return Success((CR_r == APFloat::cmpEqual &&
4881 CR_i == APFloat::cmpEqual), E);
4882 else {
John McCalle3027922010-08-25 11:45:40 +00004883 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004884 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00004885 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00004886 CR_r == APFloat::cmpLessThan ||
4887 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00004888 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00004889 CR_i == APFloat::cmpLessThan ||
4890 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004891 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004892 } else {
John McCalle3027922010-08-25 11:45:40 +00004893 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004894 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
4895 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
4896 else {
John McCalle3027922010-08-25 11:45:40 +00004897 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004898 "Invalid compex comparison.");
4899 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
4900 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
4901 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00004902 }
4903 }
Mike Stump11289f42009-09-09 15:08:12 +00004904
Anders Carlssonacc79812008-11-16 07:17:21 +00004905 if (LHSTy->isRealFloatingType() &&
4906 RHSTy->isRealFloatingType()) {
4907 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00004908
Richard Smith253c2a32012-01-27 01:14:48 +00004909 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
4910 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00004911 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004912
Richard Smith253c2a32012-01-27 01:14:48 +00004913 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00004914 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004915
Anders Carlssonacc79812008-11-16 07:17:21 +00004916 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00004917
Anders Carlssonacc79812008-11-16 07:17:21 +00004918 switch (E->getOpcode()) {
4919 default:
David Blaikie83d382b2011-09-23 05:06:16 +00004920 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00004921 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004922 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00004923 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004924 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00004925 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004926 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00004927 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00004928 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004929 E);
John McCalle3027922010-08-25 11:45:40 +00004930 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00004931 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00004932 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00004933 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00004934 || CR == APFloat::cmpLessThan
4935 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00004936 }
Anders Carlssonacc79812008-11-16 07:17:21 +00004937 }
Mike Stump11289f42009-09-09 15:08:12 +00004938
Eli Friedmana38da572009-04-28 19:17:36 +00004939 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00004940 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004941 LValue LHSValue, RHSValue;
4942
4943 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
4944 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004945 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004946
Richard Smith253c2a32012-01-27 01:14:48 +00004947 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004948 return false;
Eli Friedman64004332009-03-23 04:38:34 +00004949
Richard Smith8b3497e2011-10-31 01:37:14 +00004950 // Reject differing bases from the normal codepath; we special-case
4951 // comparisons to null.
4952 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004953 if (E->getOpcode() == BO_Sub) {
4954 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004955 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
4956 return false;
4957 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00004958 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004959 if (!LHSExpr || !RHSExpr)
4960 return false;
4961 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
4962 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
4963 if (!LHSAddrExpr || !RHSAddrExpr)
4964 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00004965 // Make sure both labels come from the same function.
4966 if (LHSAddrExpr->getLabel()->getDeclContext() !=
4967 RHSAddrExpr->getLabel()->getDeclContext())
4968 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004969 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00004970 return true;
4971 }
Richard Smith83c68212011-10-31 05:11:32 +00004972 // Inequalities and subtractions between unrelated pointers have
4973 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00004974 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004975 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004976 // A constant address may compare equal to the address of a symbol.
4977 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00004978 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00004979 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
4980 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004981 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004982 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00004983 // distinct addresses. In clang, the result of such a comparison is
4984 // unspecified, so it is not a constant expression. However, we do know
4985 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00004986 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
4987 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004988 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004989 // We can't tell whether weak symbols will end up pointing to the same
4990 // object.
4991 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004992 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00004993 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00004994 // (Note that clang defaults to -fmerge-all-constants, which can
4995 // lead to inconsistent results for comparisons involving the address
4996 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00004997 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00004998 }
Eli Friedman64004332009-03-23 04:38:34 +00004999
Richard Smith1b470412012-02-01 08:10:20 +00005000 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
5001 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
5002
Richard Smith84f6dcf2012-02-02 01:16:57 +00005003 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
5004 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
5005
John McCalle3027922010-08-25 11:45:40 +00005006 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00005007 // C++11 [expr.add]p6:
5008 // Unless both pointers point to elements of the same array object, or
5009 // one past the last element of the array object, the behavior is
5010 // undefined.
5011 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5012 !AreElementsOfSameArray(getType(LHSValue.Base),
5013 LHSDesignator, RHSDesignator))
5014 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
5015
Chris Lattner882bdf22010-04-20 17:13:14 +00005016 QualType Type = E->getLHS()->getType();
5017 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005018
Richard Smithd62306a2011-11-10 06:34:14 +00005019 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00005020 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00005021 return false;
Eli Friedman64004332009-03-23 04:38:34 +00005022
Richard Smith1b470412012-02-01 08:10:20 +00005023 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
5024 // and produce incorrect results when it overflows. Such behavior
5025 // appears to be non-conforming, but is common, so perhaps we should
5026 // assume the standard intended for such cases to be undefined behavior
5027 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00005028
Richard Smith1b470412012-02-01 08:10:20 +00005029 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
5030 // overflow in the final conversion to ptrdiff_t.
5031 APSInt LHS(
5032 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
5033 APSInt RHS(
5034 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
5035 APSInt ElemSize(
5036 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
5037 APSInt TrueResult = (LHS - RHS) / ElemSize;
5038 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
5039
5040 if (Result.extend(65) != TrueResult)
5041 HandleOverflow(Info, E, TrueResult, E->getType());
5042 return Success(Result, E);
5043 }
Richard Smithde21b242012-01-31 06:41:30 +00005044
5045 // C++11 [expr.rel]p3:
5046 // Pointers to void (after pointer conversions) can be compared, with a
5047 // result defined as follows: If both pointers represent the same
5048 // address or are both the null pointer value, the result is true if the
5049 // operator is <= or >= and false otherwise; otherwise the result is
5050 // unspecified.
5051 // We interpret this as applying to pointers to *cv* void.
5052 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00005053 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00005054 CCEDiag(E, diag::note_constexpr_void_comparison);
5055
Richard Smith84f6dcf2012-02-02 01:16:57 +00005056 // C++11 [expr.rel]p2:
5057 // - If two pointers point to non-static data members of the same object,
5058 // or to subobjects or array elements fo such members, recursively, the
5059 // pointer to the later declared member compares greater provided the
5060 // two members have the same access control and provided their class is
5061 // not a union.
5062 // [...]
5063 // - Otherwise pointer comparisons are unspecified.
5064 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
5065 E->isRelationalOp()) {
5066 bool WasArrayIndex;
5067 unsigned Mismatch =
5068 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
5069 RHSDesignator, WasArrayIndex);
5070 // At the point where the designators diverge, the comparison has a
5071 // specified value if:
5072 // - we are comparing array indices
5073 // - we are comparing fields of a union, or fields with the same access
5074 // Otherwise, the result is unspecified and thus the comparison is not a
5075 // constant expression.
5076 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
5077 Mismatch < RHSDesignator.Entries.size()) {
5078 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
5079 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
5080 if (!LF && !RF)
5081 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
5082 else if (!LF)
5083 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5084 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
5085 << RF->getParent() << RF;
5086 else if (!RF)
5087 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
5088 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
5089 << LF->getParent() << LF;
5090 else if (!LF->getParent()->isUnion() &&
5091 LF->getAccess() != RF->getAccess())
5092 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
5093 << LF << LF->getAccess() << RF << RF->getAccess()
5094 << LF->getParent();
5095 }
5096 }
5097
Eli Friedman6c31cb42012-04-16 04:30:08 +00005098 // The comparison here must be unsigned, and performed with the same
5099 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00005100 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
5101 uint64_t CompareLHS = LHSOffset.getQuantity();
5102 uint64_t CompareRHS = RHSOffset.getQuantity();
5103 assert(PtrSize <= 64 && "Unexpected pointer width");
5104 uint64_t Mask = ~0ULL >> (64 - PtrSize);
5105 CompareLHS &= Mask;
5106 CompareRHS &= Mask;
5107
Eli Friedman2f5b7c52012-04-16 19:23:57 +00005108 // If there is a base and this is a relational operator, we can only
5109 // compare pointers within the object in question; otherwise, the result
5110 // depends on where the object is located in memory.
5111 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
5112 QualType BaseTy = getType(LHSValue.Base);
5113 if (BaseTy->isIncompleteType())
5114 return Error(E);
5115 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
5116 uint64_t OffsetLimit = Size.getQuantity();
5117 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
5118 return Error(E);
5119 }
5120
Richard Smith8b3497e2011-10-31 01:37:14 +00005121 switch (E->getOpcode()) {
5122 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00005123 case BO_LT: return Success(CompareLHS < CompareRHS, E);
5124 case BO_GT: return Success(CompareLHS > CompareRHS, E);
5125 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
5126 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
5127 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
5128 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00005129 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005130 }
5131 }
Richard Smith7bb00672012-02-01 01:42:44 +00005132
5133 if (LHSTy->isMemberPointerType()) {
5134 assert(E->isEqualityOp() && "unexpected member pointer operation");
5135 assert(RHSTy->isMemberPointerType() && "invalid comparison");
5136
5137 MemberPtr LHSValue, RHSValue;
5138
5139 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
5140 if (!LHSOK && Info.keepEvaluatingAfterFailure())
5141 return false;
5142
5143 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
5144 return false;
5145
5146 // C++11 [expr.eq]p2:
5147 // If both operands are null, they compare equal. Otherwise if only one is
5148 // null, they compare unequal.
5149 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
5150 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
5151 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5152 }
5153
5154 // Otherwise if either is a pointer to a virtual member function, the
5155 // result is unspecified.
5156 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
5157 if (MD->isVirtual())
5158 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5159 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
5160 if (MD->isVirtual())
5161 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
5162
5163 // Otherwise they compare equal if and only if they would refer to the
5164 // same member of the same most derived object or the same subobject if
5165 // they were dereferenced with a hypothetical object of the associated
5166 // class type.
5167 bool Equal = LHSValue == RHSValue;
5168 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
5169 }
5170
Richard Smithab44d9b2012-02-14 22:35:28 +00005171 if (LHSTy->isNullPtrType()) {
5172 assert(E->isComparisonOp() && "unexpected nullptr operation");
5173 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
5174 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
5175 // are compared, the result is true of the operator is <=, >= or ==, and
5176 // false otherwise.
5177 BinaryOperator::Opcode Opcode = E->getOpcode();
5178 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
5179 }
5180
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005181 assert((!LHSTy->isIntegralOrEnumerationType() ||
5182 !RHSTy->isIntegralOrEnumerationType()) &&
5183 "DataRecursiveIntBinOpEvaluator should have handled integral types");
5184 // We can't continue from here for non-integral types.
5185 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00005186}
5187
Ken Dyck160146e2010-01-27 17:10:57 +00005188CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00005189 // C++ [expr.alignof]p3: "When alignof is applied to a reference type, the
5190 // result shall be the alignment of the referenced type."
5191 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5192 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00005193
5194 // __alignof is defined to return the preferred alignment.
5195 return Info.Ctx.toCharUnitsFromBits(
5196 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00005197}
5198
Ken Dyck160146e2010-01-27 17:10:57 +00005199CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00005200 E = E->IgnoreParens();
5201
5202 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00005203 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00005204 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005205 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5206 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00005207
Chris Lattner68061312009-01-24 21:53:27 +00005208 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00005209 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5210 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00005211
Chris Lattner24aeeab2009-01-24 21:09:06 +00005212 return GetAlignOfType(E->getType());
5213}
5214
5215
Peter Collingbournee190dee2011-03-11 19:24:49 +00005216/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
5217/// a result as the expression's type.
5218bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
5219 const UnaryExprOrTypeTraitExpr *E) {
5220 switch(E->getKind()) {
5221 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00005222 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00005223 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005224 else
Ken Dyckdbc01912011-03-11 02:13:43 +00005225 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00005226 }
Eli Friedman64004332009-03-23 04:38:34 +00005227
Peter Collingbournee190dee2011-03-11 19:24:49 +00005228 case UETT_VecStep: {
5229 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00005230
Peter Collingbournee190dee2011-03-11 19:24:49 +00005231 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00005232 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00005233
Peter Collingbournee190dee2011-03-11 19:24:49 +00005234 // The vec_step built-in functions that take a 3-component
5235 // vector return 4. (OpenCL 1.1 spec 6.11.12)
5236 if (n == 3)
5237 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00005238
Peter Collingbournee190dee2011-03-11 19:24:49 +00005239 return Success(n, E);
5240 } else
5241 return Success(1, E);
5242 }
5243
5244 case UETT_SizeOf: {
5245 QualType SrcTy = E->getTypeOfArgument();
5246 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
5247 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00005248 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
5249 SrcTy = Ref->getPointeeType();
5250
Richard Smithd62306a2011-11-10 06:34:14 +00005251 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00005252 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00005253 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005254 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005255 }
5256 }
5257
5258 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005259}
5260
Peter Collingbournee9200682011-05-13 03:29:01 +00005261bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00005262 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00005263 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00005264 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005265 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00005266 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00005267 for (unsigned i = 0; i != n; ++i) {
5268 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
5269 switch (ON.getKind()) {
5270 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00005271 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00005272 APSInt IdxResult;
5273 if (!EvaluateInteger(Idx, IdxResult, Info))
5274 return false;
5275 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
5276 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005277 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005278 CurrentType = AT->getElementType();
5279 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
5280 Result += IdxResult.getSExtValue() * ElementSize;
5281 break;
5282 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005283
Douglas Gregor882211c2010-04-28 22:16:22 +00005284 case OffsetOfExpr::OffsetOfNode::Field: {
5285 FieldDecl *MemberDecl = ON.getField();
5286 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005287 if (!RT)
5288 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005289 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005290 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00005291 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00005292 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00005293 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00005294 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00005295 CurrentType = MemberDecl->getType().getNonReferenceType();
5296 break;
5297 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00005298
Douglas Gregor882211c2010-04-28 22:16:22 +00005299 case OffsetOfExpr::OffsetOfNode::Identifier:
5300 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00005301
Douglas Gregord1702062010-04-29 00:18:15 +00005302 case OffsetOfExpr::OffsetOfNode::Base: {
5303 CXXBaseSpecifier *BaseSpec = ON.getBase();
5304 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005305 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005306
5307 // Find the layout of the class whose base we are looking into.
5308 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00005309 if (!RT)
5310 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005311 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00005312 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00005313 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
5314
5315 // Find the base class itself.
5316 CurrentType = BaseSpec->getType();
5317 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
5318 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005319 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00005320
5321 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00005322 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00005323 break;
5324 }
Douglas Gregor882211c2010-04-28 22:16:22 +00005325 }
5326 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005327 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00005328}
5329
Chris Lattnere13042c2008-07-11 19:10:17 +00005330bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005331 switch (E->getOpcode()) {
5332 default:
5333 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
5334 // See C99 6.6p3.
5335 return Error(E);
5336 case UO_Extension:
5337 // FIXME: Should extension allow i-c-e extension expressions in its scope?
5338 // If so, we could clear the diagnostic ID.
5339 return Visit(E->getSubExpr());
5340 case UO_Plus:
5341 // The result is just the value.
5342 return Visit(E->getSubExpr());
5343 case UO_Minus: {
5344 if (!Visit(E->getSubExpr()))
5345 return false;
5346 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00005347 const APSInt &Value = Result.getInt();
5348 if (Value.isSigned() && Value.isMinSignedValue())
5349 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
5350 E->getType());
5351 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005352 }
5353 case UO_Not: {
5354 if (!Visit(E->getSubExpr()))
5355 return false;
5356 if (!Result.isInt()) return Error(E);
5357 return Success(~Result.getInt(), E);
5358 }
5359 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00005360 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00005361 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00005362 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005363 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00005364 }
Anders Carlsson9c181652008-07-08 14:35:21 +00005365 }
Anders Carlsson9c181652008-07-08 14:35:21 +00005366}
Mike Stump11289f42009-09-09 15:08:12 +00005367
Chris Lattner477c4be2008-07-12 01:15:53 +00005368/// HandleCast - This is used to evaluate implicit or explicit casts where the
5369/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00005370bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
5371 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00005372 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00005373 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00005374
Eli Friedmanc757de22011-03-25 00:43:55 +00005375 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00005376 case CK_BaseToDerived:
5377 case CK_DerivedToBase:
5378 case CK_UncheckedDerivedToBase:
5379 case CK_Dynamic:
5380 case CK_ToUnion:
5381 case CK_ArrayToPointerDecay:
5382 case CK_FunctionToPointerDecay:
5383 case CK_NullToPointer:
5384 case CK_NullToMemberPointer:
5385 case CK_BaseToDerivedMemberPointer:
5386 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00005387 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00005388 case CK_ConstructorConversion:
5389 case CK_IntegralToPointer:
5390 case CK_ToVoid:
5391 case CK_VectorSplat:
5392 case CK_IntegralToFloating:
5393 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00005394 case CK_CPointerToObjCPointerCast:
5395 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00005396 case CK_AnyPointerToBlockPointerCast:
5397 case CK_ObjCObjectLValueCast:
5398 case CK_FloatingRealToComplex:
5399 case CK_FloatingComplexToReal:
5400 case CK_FloatingComplexCast:
5401 case CK_FloatingComplexToIntegralComplex:
5402 case CK_IntegralRealToComplex:
5403 case CK_IntegralComplexCast:
5404 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00005405 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005406 case CK_ZeroToOCLEvent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005407 llvm_unreachable("invalid cast kind for integral value");
5408
Eli Friedman9faf2f92011-03-25 19:07:11 +00005409 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00005410 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005411 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00005412 case CK_ARCProduceObject:
5413 case CK_ARCConsumeObject:
5414 case CK_ARCReclaimReturnedObject:
5415 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00005416 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005417 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005418
Richard Smith4ef685b2012-01-17 21:17:26 +00005419 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00005420 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00005421 case CK_AtomicToNonAtomic:
5422 case CK_NonAtomicToAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00005423 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00005424 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005425
5426 case CK_MemberPointerToBoolean:
5427 case CK_PointerToBoolean:
5428 case CK_IntegralToBoolean:
5429 case CK_FloatingToBoolean:
5430 case CK_FloatingComplexToBoolean:
5431 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00005432 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00005433 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00005434 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005435 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005436 }
5437
Eli Friedmanc757de22011-03-25 00:43:55 +00005438 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00005439 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00005440 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00005441
Eli Friedman742421e2009-02-20 01:15:07 +00005442 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00005443 // Allow casts of address-of-label differences if they are no-ops
5444 // or narrowing. (The narrowing case isn't actually guaranteed to
5445 // be constant-evaluatable except in some narrow cases which are hard
5446 // to detect here. We let it through on the assumption the user knows
5447 // what they are doing.)
5448 if (Result.isAddrLabelDiff())
5449 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00005450 // Only allow casts of lvalues if they are lossless.
5451 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
5452 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005453
Richard Smith911e1422012-01-30 22:27:01 +00005454 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
5455 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00005456 }
Mike Stump11289f42009-09-09 15:08:12 +00005457
Eli Friedmanc757de22011-03-25 00:43:55 +00005458 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005459 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5460
John McCall45d55e42010-05-07 21:00:08 +00005461 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00005462 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00005463 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00005464
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005465 if (LV.getLValueBase()) {
5466 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00005467 // FIXME: Allow a larger integer size than the pointer size, and allow
5468 // narrowing back down to pointer width in subsequent integral casts.
5469 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005470 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005471 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005472
Richard Smithcf74da72011-11-16 07:18:12 +00005473 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005474 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00005475 return true;
5476 }
5477
Ken Dyck02990832010-01-15 12:37:54 +00005478 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
5479 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00005480 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005481 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005482
Eli Friedmanc757de22011-03-25 00:43:55 +00005483 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00005484 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00005485 if (!EvaluateComplex(SubExpr, C, Info))
5486 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00005487 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00005488 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00005489
Eli Friedmanc757de22011-03-25 00:43:55 +00005490 case CK_FloatingToIntegral: {
5491 APFloat F(0.0);
5492 if (!EvaluateFloat(SubExpr, F, Info))
5493 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00005494
Richard Smith357362d2011-12-13 06:39:58 +00005495 APSInt Value;
5496 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
5497 return false;
5498 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005499 }
5500 }
Mike Stump11289f42009-09-09 15:08:12 +00005501
Eli Friedmanc757de22011-03-25 00:43:55 +00005502 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00005503}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005504
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005505bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5506 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00005507 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005508 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5509 return false;
5510 if (!LV.isComplexInt())
5511 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005512 return Success(LV.getComplexIntReal(), E);
5513 }
5514
5515 return Visit(E->getSubExpr());
5516}
5517
Eli Friedman4e7a2412009-02-27 04:45:43 +00005518bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005519 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00005520 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005521 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
5522 return false;
5523 if (!LV.isComplexInt())
5524 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005525 return Success(LV.getComplexIntImag(), E);
5526 }
5527
Richard Smith4a678122011-10-24 18:44:57 +00005528 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00005529 return Success(0, E);
5530}
5531
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005532bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
5533 return Success(E->getPackLength(), E);
5534}
5535
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005536bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
5537 return Success(E->getValue(), E);
5538}
5539
Chris Lattner05706e882008-07-11 18:11:29 +00005540//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00005541// Float Evaluation
5542//===----------------------------------------------------------------------===//
5543
5544namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005545class FloatExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005546 : public ExprEvaluatorBase<FloatExprEvaluator, bool> {
Eli Friedman24c01542008-08-22 00:06:13 +00005547 APFloat &Result;
5548public:
5549 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005550 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00005551
Richard Smith2e312c82012-03-03 22:46:17 +00005552 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005553 Result = V.getFloat();
5554 return true;
5555 }
Eli Friedman24c01542008-08-22 00:06:13 +00005556
Richard Smithfddd3842011-12-30 21:15:51 +00005557 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00005558 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
5559 return true;
5560 }
5561
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005562 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00005563
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005564 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00005565 bool VisitBinaryOperator(const BinaryOperator *E);
5566 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005567 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00005568
John McCallb1fb0d32010-05-07 22:08:54 +00005569 bool VisitUnaryReal(const UnaryOperator *E);
5570 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00005571
Richard Smithfddd3842011-12-30 21:15:51 +00005572 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00005573};
5574} // end anonymous namespace
5575
5576static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005577 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005578 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00005579}
5580
Jay Foad39c79802011-01-12 09:06:06 +00005581static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00005582 QualType ResultTy,
5583 const Expr *Arg,
5584 bool SNaN,
5585 llvm::APFloat &Result) {
5586 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
5587 if (!S) return false;
5588
5589 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
5590
5591 llvm::APInt fill;
5592
5593 // Treat empty strings as if they were zero.
5594 if (S->getString().empty())
5595 fill = llvm::APInt(32, 0);
5596 else if (S->getString().getAsInteger(0, fill))
5597 return false;
5598
5599 if (SNaN)
5600 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
5601 else
5602 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
5603 return true;
5604}
5605
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005606bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005607 switch (E->isBuiltinCall()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005608 default:
5609 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5610
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005611 case Builtin::BI__builtin_huge_val:
5612 case Builtin::BI__builtin_huge_valf:
5613 case Builtin::BI__builtin_huge_vall:
5614 case Builtin::BI__builtin_inf:
5615 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00005616 case Builtin::BI__builtin_infl: {
5617 const llvm::fltSemantics &Sem =
5618 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00005619 Result = llvm::APFloat::getInf(Sem);
5620 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00005621 }
Mike Stump11289f42009-09-09 15:08:12 +00005622
John McCall16291492010-02-28 13:00:19 +00005623 case Builtin::BI__builtin_nans:
5624 case Builtin::BI__builtin_nansf:
5625 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005626 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5627 true, Result))
5628 return Error(E);
5629 return true;
John McCall16291492010-02-28 13:00:19 +00005630
Chris Lattner0b7282e2008-10-06 06:31:58 +00005631 case Builtin::BI__builtin_nan:
5632 case Builtin::BI__builtin_nanf:
5633 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00005634 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00005635 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00005636 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
5637 false, Result))
5638 return Error(E);
5639 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005640
5641 case Builtin::BI__builtin_fabs:
5642 case Builtin::BI__builtin_fabsf:
5643 case Builtin::BI__builtin_fabsl:
5644 if (!EvaluateFloat(E->getArg(0), Result, Info))
5645 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005646
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005647 if (Result.isNegative())
5648 Result.changeSign();
5649 return true;
5650
Mike Stump11289f42009-09-09 15:08:12 +00005651 case Builtin::BI__builtin_copysign:
5652 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005653 case Builtin::BI__builtin_copysignl: {
5654 APFloat RHS(0.);
5655 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
5656 !EvaluateFloat(E->getArg(1), RHS, Info))
5657 return false;
5658 Result.copySign(RHS);
5659 return true;
5660 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005661 }
5662}
5663
John McCallb1fb0d32010-05-07 22:08:54 +00005664bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00005665 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5666 ComplexValue CV;
5667 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5668 return false;
5669 Result = CV.FloatReal;
5670 return true;
5671 }
5672
5673 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00005674}
5675
5676bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00005677 if (E->getSubExpr()->getType()->isAnyComplexType()) {
5678 ComplexValue CV;
5679 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
5680 return false;
5681 Result = CV.FloatImag;
5682 return true;
5683 }
5684
Richard Smith4a678122011-10-24 18:44:57 +00005685 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00005686 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
5687 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00005688 return true;
5689}
5690
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005691bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005692 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005693 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00005694 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00005695 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00005696 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00005697 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
5698 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005699 Result.changeSign();
5700 return true;
5701 }
5702}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00005703
Eli Friedman24c01542008-08-22 00:06:13 +00005704bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005705 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
5706 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00005707
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00005708 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00005709 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
5710 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00005711 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005712 if (!EvaluateFloat(E->getRHS(), RHS, Info) || !LHSOK)
Eli Friedman24c01542008-08-22 00:06:13 +00005713 return false;
5714
5715 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00005716 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00005717 case BO_Mul:
Eli Friedman24c01542008-08-22 00:06:13 +00005718 Result.multiply(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005719 break;
John McCalle3027922010-08-25 11:45:40 +00005720 case BO_Add:
Eli Friedman24c01542008-08-22 00:06:13 +00005721 Result.add(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005722 break;
John McCalle3027922010-08-25 11:45:40 +00005723 case BO_Sub:
Eli Friedman24c01542008-08-22 00:06:13 +00005724 Result.subtract(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005725 break;
John McCalle3027922010-08-25 11:45:40 +00005726 case BO_Div:
Eli Friedman24c01542008-08-22 00:06:13 +00005727 Result.divide(RHS, APFloat::rmNearestTiesToEven);
Richard Smithc8042322012-02-01 05:53:12 +00005728 break;
Eli Friedman24c01542008-08-22 00:06:13 +00005729 }
Richard Smithc8042322012-02-01 05:53:12 +00005730
5731 if (Result.isInfinity() || Result.isNaN())
5732 CCEDiag(E, diag::note_constexpr_float_arithmetic) << Result.isNaN();
5733 return true;
Eli Friedman24c01542008-08-22 00:06:13 +00005734}
5735
5736bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
5737 Result = E->getValue();
5738 return true;
5739}
5740
Peter Collingbournee9200682011-05-13 03:29:01 +00005741bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
5742 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00005743
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005744 switch (E->getCastKind()) {
5745 default:
Richard Smith11562c52011-10-28 17:51:58 +00005746 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005747
5748 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00005749 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00005750 return EvaluateInteger(SubExpr, IntResult, Info) &&
5751 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
5752 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005753 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005754
5755 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00005756 if (!Visit(SubExpr))
5757 return false;
Richard Smith357362d2011-12-13 06:39:58 +00005758 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
5759 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005760 }
John McCalld7646252010-11-14 08:17:51 +00005761
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005762 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00005763 ComplexValue V;
5764 if (!EvaluateComplex(SubExpr, V, Info))
5765 return false;
5766 Result = V.getComplexFloatReal();
5767 return true;
5768 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00005769 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005770}
5771
Eli Friedman24c01542008-08-22 00:06:13 +00005772//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005773// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00005774//===----------------------------------------------------------------------===//
5775
5776namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005777class ComplexExprEvaluator
Peter Collingbournee9200682011-05-13 03:29:01 +00005778 : public ExprEvaluatorBase<ComplexExprEvaluator, bool> {
John McCall93d91dc2010-05-07 17:22:02 +00005779 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00005780
Anders Carlsson537969c2008-11-16 20:27:53 +00005781public:
John McCall93d91dc2010-05-07 17:22:02 +00005782 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005783 : ExprEvaluatorBaseTy(info), Result(Result) {}
5784
Richard Smith2e312c82012-03-03 22:46:17 +00005785 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005786 Result.setFrom(V);
5787 return true;
5788 }
Mike Stump11289f42009-09-09 15:08:12 +00005789
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005790 bool ZeroInitialization(const Expr *E);
5791
Anders Carlsson537969c2008-11-16 20:27:53 +00005792 //===--------------------------------------------------------------------===//
5793 // Visitor Methods
5794 //===--------------------------------------------------------------------===//
5795
Peter Collingbournee9200682011-05-13 03:29:01 +00005796 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005797 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00005798 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00005799 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005800 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00005801};
5802} // end anonymous namespace
5803
John McCall93d91dc2010-05-07 17:22:02 +00005804static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
5805 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005806 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005807 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00005808}
5809
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005810bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00005811 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00005812 if (ElemTy->isRealFloatingType()) {
5813 Result.makeComplexFloat();
5814 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
5815 Result.FloatReal = Zero;
5816 Result.FloatImag = Zero;
5817 } else {
5818 Result.makeComplexInt();
5819 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
5820 Result.IntReal = Zero;
5821 Result.IntImag = Zero;
5822 }
5823 return true;
5824}
5825
Peter Collingbournee9200682011-05-13 03:29:01 +00005826bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
5827 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005828
5829 if (SubExpr->getType()->isRealFloatingType()) {
5830 Result.makeComplexFloat();
5831 APFloat &Imag = Result.FloatImag;
5832 if (!EvaluateFloat(SubExpr, Imag, Info))
5833 return false;
5834
5835 Result.FloatReal = APFloat(Imag.getSemantics());
5836 return true;
5837 } else {
5838 assert(SubExpr->getType()->isIntegerType() &&
5839 "Unexpected imaginary literal.");
5840
5841 Result.makeComplexInt();
5842 APSInt &Imag = Result.IntImag;
5843 if (!EvaluateInteger(SubExpr, Imag, Info))
5844 return false;
5845
5846 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
5847 return true;
5848 }
5849}
5850
Peter Collingbournee9200682011-05-13 03:29:01 +00005851bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005852
John McCallfcef3cf2010-12-14 17:51:41 +00005853 switch (E->getCastKind()) {
5854 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00005855 case CK_BaseToDerived:
5856 case CK_DerivedToBase:
5857 case CK_UncheckedDerivedToBase:
5858 case CK_Dynamic:
5859 case CK_ToUnion:
5860 case CK_ArrayToPointerDecay:
5861 case CK_FunctionToPointerDecay:
5862 case CK_NullToPointer:
5863 case CK_NullToMemberPointer:
5864 case CK_BaseToDerivedMemberPointer:
5865 case CK_DerivedToBaseMemberPointer:
5866 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00005867 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00005868 case CK_ConstructorConversion:
5869 case CK_IntegralToPointer:
5870 case CK_PointerToIntegral:
5871 case CK_PointerToBoolean:
5872 case CK_ToVoid:
5873 case CK_VectorSplat:
5874 case CK_IntegralCast:
5875 case CK_IntegralToBoolean:
5876 case CK_IntegralToFloating:
5877 case CK_FloatingToIntegral:
5878 case CK_FloatingToBoolean:
5879 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00005880 case CK_CPointerToObjCPointerCast:
5881 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00005882 case CK_AnyPointerToBlockPointerCast:
5883 case CK_ObjCObjectLValueCast:
5884 case CK_FloatingComplexToReal:
5885 case CK_FloatingComplexToBoolean:
5886 case CK_IntegralComplexToReal:
5887 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00005888 case CK_ARCProduceObject:
5889 case CK_ARCConsumeObject:
5890 case CK_ARCReclaimReturnedObject:
5891 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00005892 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00005893 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00005894 case CK_ZeroToOCLEvent:
John McCallfcef3cf2010-12-14 17:51:41 +00005895 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00005896
John McCallfcef3cf2010-12-14 17:51:41 +00005897 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00005898 case CK_AtomicToNonAtomic:
5899 case CK_NonAtomicToAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00005900 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00005901 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00005902
5903 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00005904 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00005905 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00005906 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00005907
5908 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005909 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00005910 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005911 return false;
5912
John McCallfcef3cf2010-12-14 17:51:41 +00005913 Result.makeComplexFloat();
5914 Result.FloatImag = APFloat(Real.getSemantics());
5915 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005916 }
5917
John McCallfcef3cf2010-12-14 17:51:41 +00005918 case CK_FloatingComplexCast: {
5919 if (!Visit(E->getSubExpr()))
5920 return false;
5921
5922 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5923 QualType From
5924 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5925
Richard Smith357362d2011-12-13 06:39:58 +00005926 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
5927 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005928 }
5929
5930 case CK_FloatingComplexToIntegralComplex: {
5931 if (!Visit(E->getSubExpr()))
5932 return false;
5933
5934 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5935 QualType From
5936 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5937 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00005938 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
5939 To, Result.IntReal) &&
5940 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
5941 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005942 }
5943
5944 case CK_IntegralRealToComplex: {
5945 APSInt &Real = Result.IntReal;
5946 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
5947 return false;
5948
5949 Result.makeComplexInt();
5950 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
5951 return true;
5952 }
5953
5954 case CK_IntegralComplexCast: {
5955 if (!Visit(E->getSubExpr()))
5956 return false;
5957
5958 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
5959 QualType From
5960 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
5961
Richard Smith911e1422012-01-30 22:27:01 +00005962 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
5963 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005964 return true;
5965 }
5966
5967 case CK_IntegralComplexToFloatingComplex: {
5968 if (!Visit(E->getSubExpr()))
5969 return false;
5970
Ted Kremenek28831752012-08-23 20:46:57 +00005971 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005972 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00005973 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00005974 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00005975 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
5976 To, Result.FloatReal) &&
5977 HandleIntToFloatCast(Info, E, From, Result.IntImag,
5978 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00005979 }
5980 }
5981
5982 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00005983}
5984
John McCall93d91dc2010-05-07 17:22:02 +00005985bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005986 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00005987 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5988
Richard Smith253c2a32012-01-27 01:14:48 +00005989 bool LHSOK = Visit(E->getLHS());
5990 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00005991 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005992
John McCall93d91dc2010-05-07 17:22:02 +00005993 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00005994 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00005995 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00005996
Daniel Dunbar0aa26062009-01-29 01:32:56 +00005997 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
5998 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00005999 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006000 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00006001 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006002 if (Result.isComplexFloat()) {
6003 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
6004 APFloat::rmNearestTiesToEven);
6005 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
6006 APFloat::rmNearestTiesToEven);
6007 } else {
6008 Result.getComplexIntReal() += RHS.getComplexIntReal();
6009 Result.getComplexIntImag() += RHS.getComplexIntImag();
6010 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006011 break;
John McCalle3027922010-08-25 11:45:40 +00006012 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00006013 if (Result.isComplexFloat()) {
6014 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
6015 APFloat::rmNearestTiesToEven);
6016 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
6017 APFloat::rmNearestTiesToEven);
6018 } else {
6019 Result.getComplexIntReal() -= RHS.getComplexIntReal();
6020 Result.getComplexIntImag() -= RHS.getComplexIntImag();
6021 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006022 break;
John McCalle3027922010-08-25 11:45:40 +00006023 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006024 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00006025 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006026 APFloat &LHS_r = LHS.getComplexFloatReal();
6027 APFloat &LHS_i = LHS.getComplexFloatImag();
6028 APFloat &RHS_r = RHS.getComplexFloatReal();
6029 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00006030
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006031 APFloat Tmp = LHS_r;
6032 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6033 Result.getComplexFloatReal() = Tmp;
6034 Tmp = LHS_i;
6035 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6036 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
6037
6038 Tmp = LHS_r;
6039 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6040 Result.getComplexFloatImag() = Tmp;
6041 Tmp = LHS_i;
6042 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6043 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
6044 } else {
John McCall93d91dc2010-05-07 17:22:02 +00006045 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00006046 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006047 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
6048 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00006049 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00006050 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
6051 LHS.getComplexIntImag() * RHS.getComplexIntReal());
6052 }
6053 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006054 case BO_Div:
6055 if (Result.isComplexFloat()) {
6056 ComplexValue LHS = Result;
6057 APFloat &LHS_r = LHS.getComplexFloatReal();
6058 APFloat &LHS_i = LHS.getComplexFloatImag();
6059 APFloat &RHS_r = RHS.getComplexFloatReal();
6060 APFloat &RHS_i = RHS.getComplexFloatImag();
6061 APFloat &Res_r = Result.getComplexFloatReal();
6062 APFloat &Res_i = Result.getComplexFloatImag();
6063
6064 APFloat Den = RHS_r;
6065 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6066 APFloat Tmp = RHS_i;
6067 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6068 Den.add(Tmp, APFloat::rmNearestTiesToEven);
6069
6070 Res_r = LHS_r;
6071 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6072 Tmp = LHS_i;
6073 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6074 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
6075 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
6076
6077 Res_i = LHS_i;
6078 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
6079 Tmp = LHS_r;
6080 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
6081 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
6082 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
6083 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00006084 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
6085 return Error(E, diag::note_expr_divide_by_zero);
6086
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006087 ComplexValue LHS = Result;
6088 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
6089 RHS.getComplexIntImag() * RHS.getComplexIntImag();
6090 Result.getComplexIntReal() =
6091 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
6092 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
6093 Result.getComplexIntImag() =
6094 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
6095 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
6096 }
6097 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006098 }
6099
John McCall93d91dc2010-05-07 17:22:02 +00006100 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00006101}
6102
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006103bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
6104 // Get the operand value into 'Result'.
6105 if (!Visit(E->getSubExpr()))
6106 return false;
6107
6108 switch (E->getOpcode()) {
6109 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00006110 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00006111 case UO_Extension:
6112 return true;
6113 case UO_Plus:
6114 // The result is always just the subexpr.
6115 return true;
6116 case UO_Minus:
6117 if (Result.isComplexFloat()) {
6118 Result.getComplexFloatReal().changeSign();
6119 Result.getComplexFloatImag().changeSign();
6120 }
6121 else {
6122 Result.getComplexIntReal() = -Result.getComplexIntReal();
6123 Result.getComplexIntImag() = -Result.getComplexIntImag();
6124 }
6125 return true;
6126 case UO_Not:
6127 if (Result.isComplexFloat())
6128 Result.getComplexFloatImag().changeSign();
6129 else
6130 Result.getComplexIntImag() = -Result.getComplexIntImag();
6131 return true;
6132 }
6133}
6134
Eli Friedmanc4b251d2012-01-10 04:58:17 +00006135bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6136 if (E->getNumInits() == 2) {
6137 if (E->getType()->isComplexType()) {
6138 Result.makeComplexFloat();
6139 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
6140 return false;
6141 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
6142 return false;
6143 } else {
6144 Result.makeComplexInt();
6145 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
6146 return false;
6147 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
6148 return false;
6149 }
6150 return true;
6151 }
6152 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
6153}
6154
Anders Carlsson537969c2008-11-16 20:27:53 +00006155//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00006156// Void expression evaluation, primarily for a cast to void on the LHS of a
6157// comma operator
6158//===----------------------------------------------------------------------===//
6159
6160namespace {
6161class VoidExprEvaluator
6162 : public ExprEvaluatorBase<VoidExprEvaluator, bool> {
6163public:
6164 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
6165
Richard Smith2e312c82012-03-03 22:46:17 +00006166 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00006167
6168 bool VisitCastExpr(const CastExpr *E) {
6169 switch (E->getCastKind()) {
6170 default:
6171 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6172 case CK_ToVoid:
6173 VisitIgnoredValue(E->getSubExpr());
6174 return true;
6175 }
6176 }
6177};
6178} // end anonymous namespace
6179
6180static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
6181 assert(E->isRValue() && E->getType()->isVoidType());
6182 return VoidExprEvaluator(Info).Visit(E);
6183}
6184
6185//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00006186// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00006187//===----------------------------------------------------------------------===//
6188
Richard Smith2e312c82012-03-03 22:46:17 +00006189static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00006190 // In C, function designators are not lvalues, but we evaluate them as if they
6191 // are.
6192 if (E->isGLValue() || E->getType()->isFunctionType()) {
6193 LValue LV;
6194 if (!EvaluateLValue(E, LV, Info))
6195 return false;
6196 LV.moveInto(Result);
6197 } else if (E->getType()->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006198 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006199 return false;
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006200 } else if (E->getType()->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00006201 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006202 return false;
John McCall45d55e42010-05-07 21:00:08 +00006203 } else if (E->getType()->hasPointerRepresentation()) {
6204 LValue LV;
6205 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006206 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006207 LV.moveInto(Result);
John McCall45d55e42010-05-07 21:00:08 +00006208 } else if (E->getType()->isRealFloatingType()) {
6209 llvm::APFloat F(0.0);
6210 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006211 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006212 Result = APValue(F);
John McCall45d55e42010-05-07 21:00:08 +00006213 } else if (E->getType()->isAnyComplexType()) {
6214 ComplexValue C;
6215 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006216 return false;
Richard Smith725810a2011-10-16 21:26:27 +00006217 C.moveInto(Result);
Richard Smithed5165f2011-11-04 05:33:44 +00006218 } else if (E->getType()->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00006219 MemberPtr P;
6220 if (!EvaluateMemberPointer(E, P, Info))
6221 return false;
6222 P.moveInto(Result);
6223 return true;
Richard Smithfddd3842011-12-30 21:15:51 +00006224 } else if (E->getType()->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006225 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006226 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006227 if (!EvaluateArray(E, LV, Info.CurrentCall->Temporaries[E], Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00006228 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006229 Result = Info.CurrentCall->Temporaries[E];
Richard Smithfddd3842011-12-30 21:15:51 +00006230 } else if (E->getType()->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006231 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006232 LV.set(E, Info.CurrentCall->Index);
Richard Smithd62306a2011-11-10 06:34:14 +00006233 if (!EvaluateRecord(E, LV, Info.CurrentCall->Temporaries[E], Info))
6234 return false;
6235 Result = Info.CurrentCall->Temporaries[E];
Richard Smith42d3af92011-12-07 00:43:50 +00006236 } else if (E->getType()->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006237 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006238 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00006239 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00006240 if (!EvaluateVoid(E, Info))
6241 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006242 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006243 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00006244 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006245 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00006246 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00006247 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006248 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00006249
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00006250 return true;
6251}
6252
Richard Smithb228a862012-02-15 02:18:13 +00006253/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
6254/// cases, the in-place evaluation is essential, since later initializers for
6255/// an object can indirectly refer to subobjects which were initialized earlier.
6256static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
6257 const Expr *E, CheckConstantExpressionKind CCEK,
6258 bool AllowNonLiteralTypes) {
Richard Smith6331c402012-02-13 22:16:19 +00006259 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +00006260 return false;
6261
6262 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00006263 // Evaluate arrays and record types in-place, so that later initializers can
6264 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00006265 if (E->getType()->isArrayType())
6266 return EvaluateArray(E, This, Result, Info);
6267 else if (E->getType()->isRecordType())
6268 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00006269 }
6270
6271 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00006272 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00006273}
6274
Richard Smithf57d8cb2011-12-09 22:58:01 +00006275/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
6276/// lvalue-to-rvalue cast if it is an lvalue.
6277static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
Richard Smithfddd3842011-12-30 21:15:51 +00006278 if (!CheckLiteralType(Info, E))
6279 return false;
6280
Richard Smith2e312c82012-03-03 22:46:17 +00006281 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006282 return false;
6283
6284 if (E->isGLValue()) {
6285 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00006286 LV.setFrom(Info.Ctx, Result);
6287 if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006288 return false;
6289 }
6290
Richard Smith2e312c82012-03-03 22:46:17 +00006291 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00006292 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006293}
Richard Smith11562c52011-10-28 17:51:58 +00006294
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006295static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
6296 const ASTContext &Ctx, bool &IsConst) {
6297 // Fast-path evaluations of integer literals, since we sometimes see files
6298 // containing vast quantities of these.
6299 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
6300 Result.Val = APValue(APSInt(L->getValue(),
6301 L->getType()->isUnsignedIntegerType()));
6302 IsConst = true;
6303 return true;
6304 }
6305
6306 // FIXME: Evaluating values of large array and record types can cause
6307 // performance problems. Only do so in C++11 for now.
6308 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
6309 Exp->getType()->isRecordType()) &&
6310 !Ctx.getLangOpts().CPlusPlus11) {
6311 IsConst = false;
6312 return true;
6313 }
6314 return false;
6315}
6316
6317
Richard Smith7b553f12011-10-29 00:50:52 +00006318/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00006319/// any crazy technique (that has nothing to do with language standards) that
6320/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00006321/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
6322/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00006323bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006324 bool IsConst;
6325 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
6326 return IsConst;
6327
Richard Smithf57d8cb2011-12-09 22:58:01 +00006328 EvalInfo Info(Ctx, Result);
6329 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00006330}
6331
Jay Foad39c79802011-01-12 09:06:06 +00006332bool Expr::EvaluateAsBooleanCondition(bool &Result,
6333 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00006334 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00006335 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00006336 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00006337}
6338
Richard Smith5fab0c92011-12-28 19:48:30 +00006339bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
6340 SideEffectsKind AllowSideEffects) const {
6341 if (!getType()->isIntegralOrEnumerationType())
6342 return false;
6343
Richard Smith11562c52011-10-28 17:51:58 +00006344 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00006345 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
6346 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00006347 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006348
Richard Smith11562c52011-10-28 17:51:58 +00006349 Result = ExprResult.Val.getInt();
6350 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00006351}
6352
Jay Foad39c79802011-01-12 09:06:06 +00006353bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Anders Carlsson43168122009-04-10 04:54:13 +00006354 EvalInfo Info(Ctx, Result);
6355
John McCall45d55e42010-05-07 21:00:08 +00006356 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00006357 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
6358 !CheckLValueConstantExpression(Info, getExprLoc(),
6359 Ctx.getLValueReferenceType(getType()), LV))
6360 return false;
6361
Richard Smith2e312c82012-03-03 22:46:17 +00006362 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00006363 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00006364}
6365
Richard Smithd0b4dd62011-12-19 06:19:21 +00006366bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
6367 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006368 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00006369 // FIXME: Evaluating initializers for large array and record types can cause
6370 // performance problems. Only do so in C++11 for now.
6371 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006372 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00006373 return false;
6374
Richard Smithd0b4dd62011-12-19 06:19:21 +00006375 Expr::EvalStatus EStatus;
6376 EStatus.Diag = &Notes;
6377
6378 EvalInfo InitInfo(Ctx, EStatus);
6379 InitInfo.setEvaluatingDecl(VD, Value);
6380
6381 LValue LVal;
6382 LVal.set(VD);
6383
Richard Smithfddd3842011-12-30 21:15:51 +00006384 // C++11 [basic.start.init]p2:
6385 // Variables with static storage duration or thread storage duration shall be
6386 // zero-initialized before any other initialization takes place.
6387 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006388 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00006389 !VD->getType()->isReferenceType()) {
6390 ImplicitValueInitExpr VIE(VD->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006391 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE, CCEK_Constant,
6392 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00006393 return false;
6394 }
6395
Richard Smithb228a862012-02-15 02:18:13 +00006396 if (!EvaluateInPlace(Value, InitInfo, LVal, this, CCEK_Constant,
6397 /*AllowNonLiteralTypes=*/true) ||
6398 EStatus.HasSideEffects)
6399 return false;
6400
6401 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
6402 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00006403}
6404
Richard Smith7b553f12011-10-29 00:50:52 +00006405/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
6406/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00006407bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00006408 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00006409 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00006410}
Anders Carlsson59689ed2008-11-22 21:04:56 +00006411
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00006412APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006413 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006414 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00006415 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00006416 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00006417 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00006418 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006419 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00006420
Anders Carlsson6736d1a22008-12-19 20:58:05 +00006421 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00006422}
John McCall864e3962010-05-07 05:32:02 +00006423
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00006424void Expr::EvaluateForOverflow(const ASTContext &Ctx,
6425 SmallVectorImpl<PartialDiagnosticAt> *Diags) const {
6426 bool IsConst;
6427 EvalResult EvalResult;
6428 EvalResult.Diag = Diags;
6429 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
6430 EvalInfo Info(Ctx, EvalResult, true);
6431 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
6432 }
6433}
6434
Abramo Bagnaraf8199452010-05-14 17:07:14 +00006435 bool Expr::EvalResult::isGlobalLValue() const {
6436 assert(Val.isLValue());
6437 return IsGlobalLValue(Val.getLValueBase());
6438 }
6439
6440
John McCall864e3962010-05-07 05:32:02 +00006441/// isIntegerConstantExpr - this recursive routine will test if an expression is
6442/// an integer constant expression.
6443
6444/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
6445/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00006446
6447// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00006448// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
6449// and a (possibly null) SourceLocation indicating the location of the problem.
6450//
John McCall864e3962010-05-07 05:32:02 +00006451// Note that to reduce code duplication, this helper does no evaluation
6452// itself; the caller checks whether the expression is evaluatable, and
6453// in the rare cases where CheckICE actually cares about the evaluated
6454// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00006455
Dan Gohman28ade552010-07-26 21:25:24 +00006456namespace {
6457
Richard Smith9e575da2012-12-28 13:25:52 +00006458enum ICEKind {
6459 /// This expression is an ICE.
6460 IK_ICE,
6461 /// This expression is not an ICE, but if it isn't evaluated, it's
6462 /// a legal subexpression for an ICE. This return value is used to handle
6463 /// the comma operator in C99 mode, and non-constant subexpressions.
6464 IK_ICEIfUnevaluated,
6465 /// This expression is not an ICE, and is not a legal subexpression for one.
6466 IK_NotICE
6467};
6468
John McCall864e3962010-05-07 05:32:02 +00006469struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00006470 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00006471 SourceLocation Loc;
6472
Richard Smith9e575da2012-12-28 13:25:52 +00006473 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00006474};
6475
Dan Gohman28ade552010-07-26 21:25:24 +00006476}
6477
Richard Smith9e575da2012-12-28 13:25:52 +00006478static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
6479
6480static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00006481
6482static ICEDiag CheckEvalInICE(const Expr* E, ASTContext &Ctx) {
6483 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00006484 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00006485 !EVResult.Val.isInt())
6486 return ICEDiag(IK_NotICE, E->getLocStart());
6487
John McCall864e3962010-05-07 05:32:02 +00006488 return NoDiag();
6489}
6490
6491static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
6492 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00006493 if (!E->getType()->isIntegralOrEnumerationType())
6494 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006495
6496 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00006497#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00006498#define STMT(Node, Base) case Expr::Node##Class:
6499#define EXPR(Node, Base)
6500#include "clang/AST/StmtNodes.inc"
6501 case Expr::PredefinedExprClass:
6502 case Expr::FloatingLiteralClass:
6503 case Expr::ImaginaryLiteralClass:
6504 case Expr::StringLiteralClass:
6505 case Expr::ArraySubscriptExprClass:
6506 case Expr::MemberExprClass:
6507 case Expr::CompoundAssignOperatorClass:
6508 case Expr::CompoundLiteralExprClass:
6509 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00006510 case Expr::DesignatedInitExprClass:
6511 case Expr::ImplicitValueInitExprClass:
6512 case Expr::ParenListExprClass:
6513 case Expr::VAArgExprClass:
6514 case Expr::AddrLabelExprClass:
6515 case Expr::StmtExprClass:
6516 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00006517 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00006518 case Expr::CXXDynamicCastExprClass:
6519 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00006520 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00006521 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00006522 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00006523 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00006524 case Expr::CXXThisExprClass:
6525 case Expr::CXXThrowExprClass:
6526 case Expr::CXXNewExprClass:
6527 case Expr::CXXDeleteExprClass:
6528 case Expr::CXXPseudoDestructorExprClass:
6529 case Expr::UnresolvedLookupExprClass:
6530 case Expr::DependentScopeDeclRefExprClass:
6531 case Expr::CXXConstructExprClass:
6532 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00006533 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00006534 case Expr::CXXTemporaryObjectExprClass:
6535 case Expr::CXXUnresolvedConstructExprClass:
6536 case Expr::CXXDependentScopeMemberExprClass:
6537 case Expr::UnresolvedMemberExprClass:
6538 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00006539 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006540 case Expr::ObjCArrayLiteralClass:
6541 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00006542 case Expr::ObjCEncodeExprClass:
6543 case Expr::ObjCMessageExprClass:
6544 case Expr::ObjCSelectorExprClass:
6545 case Expr::ObjCProtocolExprClass:
6546 case Expr::ObjCIvarRefExprClass:
6547 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006548 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00006549 case Expr::ObjCIsaExprClass:
6550 case Expr::ShuffleVectorExprClass:
6551 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00006552 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00006553 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00006554 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00006555 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00006556 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00006557 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00006558 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00006559 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00006560 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00006561 case Expr::AtomicExprClass:
Sebastian Redl12757ab2011-09-24 17:48:14 +00006562 case Expr::InitListExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00006563 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00006564 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00006565
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006566 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00006567 case Expr::GNUNullExprClass:
6568 // GCC considers the GNU __null value to be an integral constant expression.
6569 return NoDiag();
6570
John McCall7c454bb2011-07-15 05:09:51 +00006571 case Expr::SubstNonTypeTemplateParmExprClass:
6572 return
6573 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
6574
John McCall864e3962010-05-07 05:32:02 +00006575 case Expr::ParenExprClass:
6576 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00006577 case Expr::GenericSelectionExprClass:
6578 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00006579 case Expr::IntegerLiteralClass:
6580 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00006581 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00006582 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00006583 case Expr::CXXScalarValueInitExprClass:
John McCall864e3962010-05-07 05:32:02 +00006584 case Expr::UnaryTypeTraitExprClass:
Francois Pichet9dfa3ce2010-12-07 00:08:36 +00006585 case Expr::BinaryTypeTraitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00006586 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00006587 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00006588 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00006589 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00006590 return NoDiag();
6591 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00006592 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00006593 // C99 6.6/3 allows function calls within unevaluated subexpressions of
6594 // constant expressions, but they can never be ICEs because an ICE cannot
6595 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00006596 const CallExpr *CE = cast<CallExpr>(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006597 if (CE->isBuiltinCall())
John McCall864e3962010-05-07 05:32:02 +00006598 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006599 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006600 }
Richard Smith6365c912012-02-24 22:12:32 +00006601 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00006602 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
6603 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00006604 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00006605 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00006606 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00006607 // Parameter variables are never constants. Without this check,
6608 // getAnyInitializer() can find a default argument, which leads
6609 // to chaos.
6610 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00006611 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00006612
6613 // C++ 7.1.5.1p2
6614 // A variable of non-volatile const-qualified integral or enumeration
6615 // type initialized by an ICE can be used in ICEs.
6616 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00006617 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00006618 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00006619
Richard Smithd0b4dd62011-12-19 06:19:21 +00006620 const VarDecl *VD;
6621 // Look for a declaration of this variable that has an initializer, and
6622 // check whether it is an ICE.
6623 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
6624 return NoDiag();
6625 else
Richard Smith9e575da2012-12-28 13:25:52 +00006626 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00006627 }
6628 }
Richard Smith9e575da2012-12-28 13:25:52 +00006629 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00006630 }
John McCall864e3962010-05-07 05:32:02 +00006631 case Expr::UnaryOperatorClass: {
6632 const UnaryOperator *Exp = cast<UnaryOperator>(E);
6633 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00006634 case UO_PostInc:
6635 case UO_PostDec:
6636 case UO_PreInc:
6637 case UO_PreDec:
6638 case UO_AddrOf:
6639 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00006640 // C99 6.6/3 allows increment and decrement within unevaluated
6641 // subexpressions of constant expressions, but they can never be ICEs
6642 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00006643 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00006644 case UO_Extension:
6645 case UO_LNot:
6646 case UO_Plus:
6647 case UO_Minus:
6648 case UO_Not:
6649 case UO_Real:
6650 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00006651 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00006652 }
Richard Smith9e575da2012-12-28 13:25:52 +00006653
John McCall864e3962010-05-07 05:32:02 +00006654 // OffsetOf falls through here.
6655 }
6656 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00006657 // Note that per C99, offsetof must be an ICE. And AFAIK, using
6658 // EvaluateAsRValue matches the proposed gcc behavior for cases like
6659 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
6660 // compliance: we should warn earlier for offsetof expressions with
6661 // array subscripts that aren't ICEs, and if the array subscripts
6662 // are ICEs, the value of the offsetof must be an integer constant.
6663 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00006664 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00006665 case Expr::UnaryExprOrTypeTraitExprClass: {
6666 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
6667 if ((Exp->getKind() == UETT_SizeOf) &&
6668 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00006669 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006670 return NoDiag();
6671 }
6672 case Expr::BinaryOperatorClass: {
6673 const BinaryOperator *Exp = cast<BinaryOperator>(E);
6674 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00006675 case BO_PtrMemD:
6676 case BO_PtrMemI:
6677 case BO_Assign:
6678 case BO_MulAssign:
6679 case BO_DivAssign:
6680 case BO_RemAssign:
6681 case BO_AddAssign:
6682 case BO_SubAssign:
6683 case BO_ShlAssign:
6684 case BO_ShrAssign:
6685 case BO_AndAssign:
6686 case BO_XorAssign:
6687 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00006688 // C99 6.6/3 allows assignments within unevaluated subexpressions of
6689 // constant expressions, but they can never be ICEs because an ICE cannot
6690 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00006691 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006692
John McCalle3027922010-08-25 11:45:40 +00006693 case BO_Mul:
6694 case BO_Div:
6695 case BO_Rem:
6696 case BO_Add:
6697 case BO_Sub:
6698 case BO_Shl:
6699 case BO_Shr:
6700 case BO_LT:
6701 case BO_GT:
6702 case BO_LE:
6703 case BO_GE:
6704 case BO_EQ:
6705 case BO_NE:
6706 case BO_And:
6707 case BO_Xor:
6708 case BO_Or:
6709 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00006710 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6711 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00006712 if (Exp->getOpcode() == BO_Div ||
6713 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00006714 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00006715 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00006716 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00006717 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00006718 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00006719 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006720 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00006721 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00006722 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00006723 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006724 }
6725 }
6726 }
John McCalle3027922010-08-25 11:45:40 +00006727 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00006728 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00006729 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
6730 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00006731 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
6732 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006733 } else {
6734 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00006735 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00006736 }
6737 }
Richard Smith9e575da2012-12-28 13:25:52 +00006738 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00006739 }
John McCalle3027922010-08-25 11:45:40 +00006740 case BO_LAnd:
6741 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00006742 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
6743 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006744 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00006745 // Rare case where the RHS has a comma "side-effect"; we need
6746 // to actually check the condition to see whether the side
6747 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00006748 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00006749 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00006750 return RHSResult;
6751 return NoDiag();
6752 }
6753
Richard Smith9e575da2012-12-28 13:25:52 +00006754 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00006755 }
6756 }
6757 }
6758 case Expr::ImplicitCastExprClass:
6759 case Expr::CStyleCastExprClass:
6760 case Expr::CXXFunctionalCastExprClass:
6761 case Expr::CXXStaticCastExprClass:
6762 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00006763 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00006764 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00006765 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00006766 if (isa<ExplicitCastExpr>(E)) {
6767 if (const FloatingLiteral *FL
6768 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
6769 unsigned DestWidth = Ctx.getIntWidth(E->getType());
6770 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
6771 APSInt IgnoredVal(DestWidth, !DestSigned);
6772 bool Ignored;
6773 // If the value does not fit in the destination type, the behavior is
6774 // undefined, so we are not required to treat it as a constant
6775 // expression.
6776 if (FL->getValue().convertToInteger(IgnoredVal,
6777 llvm::APFloat::rmTowardZero,
6778 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00006779 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00006780 return NoDiag();
6781 }
6782 }
Eli Friedman76d4e432011-09-29 21:49:34 +00006783 switch (cast<CastExpr>(E)->getCastKind()) {
6784 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00006785 case CK_AtomicToNonAtomic:
6786 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00006787 case CK_NoOp:
6788 case CK_IntegralToBoolean:
6789 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00006790 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00006791 default:
Richard Smith9e575da2012-12-28 13:25:52 +00006792 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00006793 }
John McCall864e3962010-05-07 05:32:02 +00006794 }
John McCallc07a0c72011-02-17 10:25:35 +00006795 case Expr::BinaryConditionalOperatorClass: {
6796 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
6797 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006798 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00006799 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006800 if (FalseResult.Kind == IK_NotICE) return FalseResult;
6801 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
6802 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00006803 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00006804 return FalseResult;
6805 }
John McCall864e3962010-05-07 05:32:02 +00006806 case Expr::ConditionalOperatorClass: {
6807 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
6808 // If the condition (ignoring parens) is a __builtin_constant_p call,
6809 // then only the true side is actually considered in an integer constant
6810 // expression, and it is fully evaluated. This is an important GNU
6811 // extension. See GCC PR38377 for discussion.
6812 if (const CallExpr *CallCE
6813 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Richard Smith5fab0c92011-12-28 19:48:30 +00006814 if (CallCE->isBuiltinCall() == Builtin::BI__builtin_constant_p)
6815 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00006816 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00006817 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00006818 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00006819
Richard Smithf57d8cb2011-12-09 22:58:01 +00006820 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
6821 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00006822
Richard Smith9e575da2012-12-28 13:25:52 +00006823 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00006824 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00006825 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00006826 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00006827 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00006828 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00006829 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00006830 return NoDiag();
6831 // Rare case where the diagnostics depend on which side is evaluated
6832 // Note that if we get here, CondResult is 0, and at least one of
6833 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00006834 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00006835 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00006836 return TrueResult;
6837 }
6838 case Expr::CXXDefaultArgExprClass:
6839 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00006840 case Expr::CXXDefaultInitExprClass:
6841 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00006842 case Expr::ChooseExprClass: {
6843 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
6844 }
6845 }
6846
David Blaikiee4d798f2012-01-20 21:50:17 +00006847 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00006848}
6849
Richard Smithf57d8cb2011-12-09 22:58:01 +00006850/// Evaluate an expression as a C++11 integral constant expression.
6851static bool EvaluateCPlusPlus11IntegralConstantExpr(ASTContext &Ctx,
6852 const Expr *E,
6853 llvm::APSInt *Value,
6854 SourceLocation *Loc) {
6855 if (!E->getType()->isIntegralOrEnumerationType()) {
6856 if (Loc) *Loc = E->getExprLoc();
6857 return false;
6858 }
6859
Richard Smith66e05fe2012-01-18 05:21:49 +00006860 APValue Result;
6861 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00006862 return false;
6863
Richard Smith66e05fe2012-01-18 05:21:49 +00006864 assert(Result.isInt() && "pointer cast to int is not an ICE");
6865 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00006866 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006867}
6868
Richard Smith92b1ce02011-12-12 09:28:41 +00006869bool Expr::isIntegerConstantExpr(ASTContext &Ctx, SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006870 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006871 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, 0, Loc);
6872
Richard Smith9e575da2012-12-28 13:25:52 +00006873 ICEDiag D = CheckICE(this, Ctx);
6874 if (D.Kind != IK_ICE) {
6875 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00006876 return false;
6877 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00006878 return true;
6879}
6880
6881bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, ASTContext &Ctx,
6882 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006883 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006884 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
6885
6886 if (!isIntegerConstantExpr(Ctx, Loc))
6887 return false;
6888 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00006889 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00006890 return true;
6891}
Richard Smith66e05fe2012-01-18 05:21:49 +00006892
Richard Smith98a0a492012-02-14 21:38:30 +00006893bool Expr::isCXX98IntegralConstantExpr(ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00006894 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00006895}
6896
Richard Smith66e05fe2012-01-18 05:21:49 +00006897bool Expr::isCXX11ConstantExpr(ASTContext &Ctx, APValue *Result,
6898 SourceLocation *Loc) const {
6899 // We support this checking in C++98 mode in order to diagnose compatibility
6900 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00006901 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00006902
Richard Smith98a0a492012-02-14 21:38:30 +00006903 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00006904 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006905 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00006906 Status.Diag = &Diags;
6907 EvalInfo Info(Ctx, Status);
6908
6909 APValue Scratch;
6910 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
6911
6912 if (!Diags.empty()) {
6913 IsConstExpr = false;
6914 if (Loc) *Loc = Diags[0].first;
6915 } else if (!IsConstExpr) {
6916 // FIXME: This shouldn't happen.
6917 if (Loc) *Loc = getExprLoc();
6918 }
6919
6920 return IsConstExpr;
6921}
Richard Smith253c2a32012-01-27 01:14:48 +00006922
6923bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00006924 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00006925 PartialDiagnosticAt> &Diags) {
6926 // FIXME: It would be useful to check constexpr function templates, but at the
6927 // moment the constant expression evaluator cannot cope with the non-rigorous
6928 // ASTs which we build for dependent expressions.
6929 if (FD->isDependentContext())
6930 return true;
6931
6932 Expr::EvalStatus Status;
6933 Status.Diag = &Diags;
6934
6935 EvalInfo Info(FD->getASTContext(), Status);
6936 Info.CheckingPotentialConstantExpression = true;
6937
6938 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
6939 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : 0;
6940
6941 // FIXME: Fabricate an arbitrary expression on the stack and pretend that it
6942 // is a temporary being used as the 'this' pointer.
6943 LValue This;
6944 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00006945 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00006946
Richard Smith253c2a32012-01-27 01:14:48 +00006947 ArrayRef<const Expr*> Args;
6948
6949 SourceLocation Loc = FD->getLocation();
6950
Richard Smith2e312c82012-03-03 22:46:17 +00006951 APValue Scratch;
6952 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
Richard Smith253c2a32012-01-27 01:14:48 +00006953 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith2e312c82012-03-03 22:46:17 +00006954 else
Richard Smith253c2a32012-01-27 01:14:48 +00006955 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : 0,
6956 Args, FD->getBody(), Info, Scratch);
6957
6958 return Diags.empty();
6959}