blob: c1fc7eee31561e5d17445b629c7656ac58a298d4 [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
Richard Smith861b5b52013-05-07 23:34:45 +000026// (under the C++11 / C++1y rules only, at the moment), or, if folding failed
27// too, why the expression could not be folded.
Richard Smith253c2a32012-01-27 01:14:48 +000028//
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();
Richard Smith84401042013-06-03 05:03:02 +000066
67 const Expr *Base = B.get<const Expr*>();
68
69 // For a materialized temporary, the type of the temporary we materialized
70 // may not be the type of the expression.
71 if (const MaterializeTemporaryExpr *MTE =
72 dyn_cast<MaterializeTemporaryExpr>(Base)) {
73 SmallVector<const Expr *, 2> CommaLHSs;
74 SmallVector<SubobjectAdjustment, 2> Adjustments;
75 const Expr *Temp = MTE->GetTemporaryExpr();
76 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
77 Adjustments);
78 // Keep any cv-qualifiers from the reference if we generated a temporary
79 // for it.
80 if (Inner != Temp)
81 return Inner->getType();
82 }
83
84 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000085 }
86
Richard Smithd62306a2011-11-10 06:34:14 +000087 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000088 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000089 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000090 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000091 APValue::BaseOrMemberType Value;
92 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000093 return Value;
94 }
95
96 /// Get an LValue path entry, which is known to not be an array index, as a
97 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000098 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000100 }
101 /// Get an LValue path entry, which is known to not be an array index, as a
102 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000103 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000104 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000105 }
106 /// Determine whether this LValue path entry for a base class names a virtual
107 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000108 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000109 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000110 }
111
Richard Smitha8105bc2012-01-06 16:39:00 +0000112 /// Find the path length and type of the most-derived subobject in the given
113 /// path, and find the size of the containing array, if any.
114 static
115 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
116 ArrayRef<APValue::LValuePathEntry> Path,
117 uint64_t &ArraySize, QualType &Type) {
118 unsigned MostDerivedLength = 0;
119 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000120 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000121 if (Type->isArrayType()) {
122 const ConstantArrayType *CAT =
123 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
124 Type = CAT->getElementType();
125 ArraySize = CAT->getSize().getZExtValue();
126 MostDerivedLength = I + 1;
Richard Smith66c96992012-02-18 22:04:06 +0000127 } else if (Type->isAnyComplexType()) {
128 const ComplexType *CT = Type->castAs<ComplexType>();
129 Type = CT->getElementType();
130 ArraySize = 2;
131 MostDerivedLength = I + 1;
Richard Smitha8105bc2012-01-06 16:39:00 +0000132 } else if (const FieldDecl *FD = getAsField(Path[I])) {
133 Type = FD->getType();
134 ArraySize = 0;
135 MostDerivedLength = I + 1;
136 } else {
Richard Smith80815602011-11-07 05:07:52 +0000137 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000138 ArraySize = 0;
139 }
Richard Smith80815602011-11-07 05:07:52 +0000140 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000141 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000142 }
143
Richard Smitha8105bc2012-01-06 16:39:00 +0000144 // The order of this enum is important for diagnostics.
145 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000146 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000147 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000148 };
149
Richard Smith96e0c102011-11-04 02:25:55 +0000150 /// A path from a glvalue to a subobject of that glvalue.
151 struct SubobjectDesignator {
152 /// True if the subobject was named in a manner not supported by C++11. Such
153 /// lvalues can still be folded, but they are not core constant expressions
154 /// and we cannot perform lvalue-to-rvalue conversions on them.
155 bool Invalid : 1;
156
Richard Smitha8105bc2012-01-06 16:39:00 +0000157 /// Is this a pointer one past the end of an object?
158 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000159
Richard Smitha8105bc2012-01-06 16:39:00 +0000160 /// The length of the path to the most-derived object of which this is a
161 /// subobject.
162 unsigned MostDerivedPathLength : 30;
163
164 /// The size of the array of which the most-derived object is an element, or
165 /// 0 if the most-derived object is not an array element.
166 uint64_t MostDerivedArraySize;
167
168 /// The type of the most derived object referred to by this address.
169 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000170
Richard Smith80815602011-11-07 05:07:52 +0000171 typedef APValue::LValuePathEntry PathEntry;
172
Richard Smith96e0c102011-11-04 02:25:55 +0000173 /// The entries on the path from the glvalue to the designated subobject.
174 SmallVector<PathEntry, 8> Entries;
175
Richard Smitha8105bc2012-01-06 16:39:00 +0000176 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000177
Richard Smitha8105bc2012-01-06 16:39:00 +0000178 explicit SubobjectDesignator(QualType T)
179 : Invalid(false), IsOnePastTheEnd(false), MostDerivedPathLength(0),
180 MostDerivedArraySize(0), MostDerivedType(T) {}
181
182 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
183 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
184 MostDerivedPathLength(0), MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000185 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000186 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000187 ArrayRef<PathEntry> VEntries = V.getLValuePath();
188 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
189 if (V.getLValueBase())
Richard Smitha8105bc2012-01-06 16:39:00 +0000190 MostDerivedPathLength =
191 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
192 V.getLValuePath(), MostDerivedArraySize,
193 MostDerivedType);
Richard Smith80815602011-11-07 05:07:52 +0000194 }
195 }
196
Richard Smith96e0c102011-11-04 02:25:55 +0000197 void setInvalid() {
198 Invalid = true;
199 Entries.clear();
200 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000201
202 /// Determine whether this is a one-past-the-end pointer.
203 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000204 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000205 if (IsOnePastTheEnd)
206 return true;
207 if (MostDerivedArraySize &&
208 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
209 return true;
210 return false;
211 }
212
213 /// Check that this refers to a valid subobject.
214 bool isValidSubobject() const {
215 if (Invalid)
216 return false;
217 return !isOnePastTheEnd();
218 }
219 /// Check that this refers to a valid subobject, and if not, produce a
220 /// relevant diagnostic and set the designator as invalid.
221 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
222
223 /// Update this designator to refer to the first element within this array.
224 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000225 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000226 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000227 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000228
229 // This is a most-derived object.
230 MostDerivedType = CAT->getElementType();
231 MostDerivedArraySize = CAT->getSize().getZExtValue();
232 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000233 }
234 /// Update this designator to refer to the given base or member of this
235 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000236 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000237 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000238 APValue::BaseOrMemberType Value(D, Virtual);
239 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000240 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000241
242 // If this isn't a base class, it's a new most-derived object.
243 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
244 MostDerivedType = FD->getType();
245 MostDerivedArraySize = 0;
246 MostDerivedPathLength = Entries.size();
247 }
Richard Smith96e0c102011-11-04 02:25:55 +0000248 }
Richard Smith66c96992012-02-18 22:04:06 +0000249 /// Update this designator to refer to the given complex component.
250 void addComplexUnchecked(QualType EltTy, bool Imag) {
251 PathEntry Entry;
252 Entry.ArrayIndex = Imag;
253 Entries.push_back(Entry);
254
255 // This is technically a most-derived object, though in practice this
256 // is unlikely to matter.
257 MostDerivedType = EltTy;
258 MostDerivedArraySize = 2;
259 MostDerivedPathLength = Entries.size();
260 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000261 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000262 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000263 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000264 if (Invalid) return;
Richard Smitha8105bc2012-01-06 16:39:00 +0000265 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize) {
Richard Smith80815602011-11-07 05:07:52 +0000266 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000267 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
268 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
269 setInvalid();
270 }
Richard Smith96e0c102011-11-04 02:25:55 +0000271 return;
272 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000273 // [expr.add]p4: For the purposes of these operators, a pointer to a
274 // nonarray object behaves the same as a pointer to the first element of
275 // an array of length one with the type of the object as its element type.
276 if (IsOnePastTheEnd && N == (uint64_t)-1)
277 IsOnePastTheEnd = false;
278 else if (!IsOnePastTheEnd && N == 1)
279 IsOnePastTheEnd = true;
280 else if (N != 0) {
281 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000282 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000283 }
Richard Smith96e0c102011-11-04 02:25:55 +0000284 }
285 };
286
Richard Smith254a73d2011-10-28 22:34:42 +0000287 /// A stack frame in the constexpr call stack.
288 struct CallStackFrame {
289 EvalInfo &Info;
290
291 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000292 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000293
Richard Smithf6f003a2011-12-16 19:06:07 +0000294 /// CallLoc - The location of the call expression for this call.
295 SourceLocation CallLoc;
296
297 /// Callee - The function which was called.
298 const FunctionDecl *Callee;
299
Richard Smithb228a862012-02-15 02:18:13 +0000300 /// Index - The call index of this call.
301 unsigned Index;
302
Richard Smithd62306a2011-11-10 06:34:14 +0000303 /// This - The binding for the this pointer in this call, if any.
304 const LValue *This;
305
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000306 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000307 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000308 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000309
Eli Friedman4830ec82012-06-25 21:21:08 +0000310 // Note that we intentionally use std::map here so that references to
311 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000312 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000313 typedef MapTy::const_iterator temp_iterator;
314 /// Temporaries - Temporary lvalues materialized within this stack frame.
315 MapTy Temporaries;
316
Richard Smithf6f003a2011-12-16 19:06:07 +0000317 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
318 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000319 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000320 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000321
322 APValue *getTemporary(const void *Key) {
323 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000324 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000325 }
326 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000327 };
328
Richard Smith852c9db2013-04-20 22:23:05 +0000329 /// Temporarily override 'this'.
330 class ThisOverrideRAII {
331 public:
332 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
333 : Frame(Frame), OldThis(Frame.This) {
334 if (Enable)
335 Frame.This = NewThis;
336 }
337 ~ThisOverrideRAII() {
338 Frame.This = OldThis;
339 }
340 private:
341 CallStackFrame &Frame;
342 const LValue *OldThis;
343 };
344
Richard Smith92b1ce02011-12-12 09:28:41 +0000345 /// A partial diagnostic which we might know in advance that we are not going
346 /// to emit.
347 class OptionalDiagnostic {
348 PartialDiagnostic *Diag;
349
350 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000351 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
352 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000353
354 template<typename T>
355 OptionalDiagnostic &operator<<(const T &v) {
356 if (Diag)
357 *Diag << v;
358 return *this;
359 }
Richard Smithfe800032012-01-31 04:08:20 +0000360
361 OptionalDiagnostic &operator<<(const APSInt &I) {
362 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000363 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000364 I.toString(Buffer);
365 *Diag << StringRef(Buffer.data(), Buffer.size());
366 }
367 return *this;
368 }
369
370 OptionalDiagnostic &operator<<(const APFloat &F) {
371 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000372 // FIXME: Force the precision of the source value down so we don't
373 // print digits which are usually useless (we don't really care here if
374 // we truncate a digit by accident in edge cases). Ideally,
375 // APFloat::toString would automatically print the shortest
376 // representation which rounds to the correct value, but it's a bit
377 // tricky to implement.
378 unsigned precision =
379 llvm::APFloat::semanticsPrecision(F.getSemantics());
380 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000381 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000382 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000383 *Diag << StringRef(Buffer.data(), Buffer.size());
384 }
385 return *this;
386 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000387 };
388
Richard Smith08d6a2c2013-07-24 07:11:57 +0000389 /// A cleanup, and a flag indicating whether it is lifetime-extended.
390 class Cleanup {
391 llvm::PointerIntPair<APValue*, 1, bool> Value;
392
393 public:
394 Cleanup(APValue *Val, bool IsLifetimeExtended)
395 : Value(Val, IsLifetimeExtended) {}
396
397 bool isLifetimeExtended() const { return Value.getInt(); }
398 void endLifetime() {
399 *Value.getPointer() = APValue();
400 }
401 };
402
Richard Smithb228a862012-02-15 02:18:13 +0000403 /// EvalInfo - This is a private struct used by the evaluator to capture
404 /// information about a subexpression as it is folded. It retains information
405 /// about the AST context, but also maintains information about the folded
406 /// expression.
407 ///
408 /// If an expression could be evaluated, it is still possible it is not a C
409 /// "integer constant expression" or constant expression. If not, this struct
410 /// captures information about how and why not.
411 ///
412 /// One bit of information passed *into* the request for constant folding
413 /// indicates whether the subexpression is "evaluated" or not according to C
414 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
415 /// evaluate the expression regardless of what the RHS is, but C only allows
416 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000417 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000418 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000419
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000420 /// EvalStatus - Contains information about the evaluation.
421 Expr::EvalStatus &EvalStatus;
422
423 /// CurrentCall - The top of the constexpr call stack.
424 CallStackFrame *CurrentCall;
425
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000426 /// CallStackDepth - The number of calls in the call stack right now.
427 unsigned CallStackDepth;
428
Richard Smithb228a862012-02-15 02:18:13 +0000429 /// NextCallIndex - The next call index to assign.
430 unsigned NextCallIndex;
431
Richard Smitha3d3bd22013-05-08 02:12:03 +0000432 /// StepsLeft - The remaining number of evaluation steps we're permitted
433 /// to perform. This is essentially a limit for the number of statements
434 /// we will evaluate.
435 unsigned StepsLeft;
436
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000437 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000438 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000439 CallStackFrame BottomFrame;
440
Richard Smith08d6a2c2013-07-24 07:11:57 +0000441 /// A stack of values whose lifetimes end at the end of some surrounding
442 /// evaluation frame.
443 llvm::SmallVector<Cleanup, 16> CleanupStack;
444
Richard Smithd62306a2011-11-10 06:34:14 +0000445 /// EvaluatingDecl - This is the declaration whose initializer is being
446 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000447 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000448
449 /// EvaluatingDeclValue - This is the value being constructed for the
450 /// declaration whose initializer is being evaluated, if any.
451 APValue *EvaluatingDeclValue;
452
Richard Smith357362d2011-12-13 06:39:58 +0000453 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
454 /// notes attached to it will also be stored, otherwise they will not be.
455 bool HasActiveDiagnostic;
456
Richard Smith6d4c6582013-11-05 22:18:15 +0000457 enum EvaluationMode {
458 /// Evaluate as a constant expression. Stop if we find that the expression
459 /// is not a constant expression.
460 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000461
Richard Smith6d4c6582013-11-05 22:18:15 +0000462 /// Evaluate as a potential constant expression. Keep going if we hit a
463 /// construct that we can't evaluate yet (because we don't yet know the
464 /// value of something) but stop if we hit something that could never be
465 /// a constant expression.
466 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000467
Richard Smith6d4c6582013-11-05 22:18:15 +0000468 /// Fold the expression to a constant. Stop if we hit a side-effect that
469 /// we can't model.
470 EM_ConstantFold,
471
472 /// Evaluate the expression looking for integer overflow and similar
473 /// issues. Don't worry about side-effects, and try to visit all
474 /// subexpressions.
475 EM_EvaluateForOverflow,
476
477 /// Evaluate in any way we know how. Don't worry about side-effects that
478 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000479 EM_IgnoreSideEffects,
480
481 /// Evaluate as a constant expression. Stop if we find that the expression
482 /// is not a constant expression. Some expressions can be retried in the
483 /// optimizer if we don't constant fold them here, but in an unevaluated
484 /// context we try to fold them immediately since the optimizer never
485 /// gets a chance to look at it.
486 EM_ConstantExpressionUnevaluated,
487
488 /// Evaluate as a potential constant expression. Keep going if we hit a
489 /// construct that we can't evaluate yet (because we don't yet know the
490 /// value of something) but stop if we hit something that could never be
491 /// a constant expression. Some expressions can be retried in the
492 /// optimizer if we don't constant fold them here, but in an unevaluated
493 /// context we try to fold them immediately since the optimizer never
494 /// gets a chance to look at it.
495 EM_PotentialConstantExpressionUnevaluated
Richard Smith6d4c6582013-11-05 22:18:15 +0000496 } EvalMode;
497
498 /// Are we checking whether the expression is a potential constant
499 /// expression?
500 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000501 return EvalMode == EM_PotentialConstantExpression ||
502 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000503 }
504
505 /// Are we checking an expression for overflow?
506 // FIXME: We should check for any kind of undefined or suspicious behavior
507 // in such constructs, not just overflow.
508 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
509
510 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000511 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000512 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000513 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000514 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
515 EvaluatingDecl((const ValueDecl *)nullptr),
516 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
517 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000518
Richard Smith7525ff62013-05-09 07:14:00 +0000519 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
520 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000521 EvaluatingDeclValue = &Value;
522 }
523
David Blaikiebbafb8a2012-03-11 07:00:24 +0000524 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000525
Richard Smith357362d2011-12-13 06:39:58 +0000526 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000527 // Don't perform any constexpr calls (other than the call we're checking)
528 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000529 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000530 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000531 if (NextCallIndex == 0) {
532 // NextCallIndex has wrapped around.
533 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
534 return false;
535 }
Richard Smith357362d2011-12-13 06:39:58 +0000536 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
537 return true;
538 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
539 << getLangOpts().ConstexprCallDepth;
540 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000541 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000542
Richard Smithb228a862012-02-15 02:18:13 +0000543 CallStackFrame *getCallFrame(unsigned CallIndex) {
544 assert(CallIndex && "no call index in getCallFrame");
545 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
546 // be null in this loop.
547 CallStackFrame *Frame = CurrentCall;
548 while (Frame->Index > CallIndex)
549 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000550 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000551 }
552
Richard Smitha3d3bd22013-05-08 02:12:03 +0000553 bool nextStep(const Stmt *S) {
554 if (!StepsLeft) {
555 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
556 return false;
557 }
558 --StepsLeft;
559 return true;
560 }
561
Richard Smith357362d2011-12-13 06:39:58 +0000562 private:
563 /// Add a diagnostic to the diagnostics list.
564 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
565 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
566 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
567 return EvalStatus.Diag->back().second;
568 }
569
Richard Smithf6f003a2011-12-16 19:06:07 +0000570 /// Add notes containing a call stack to the current point of evaluation.
571 void addCallStack(unsigned Limit);
572
Richard Smith357362d2011-12-13 06:39:58 +0000573 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000574 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000575 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
576 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000577 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000578 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000579 // If we have a prior diagnostic, it will be noting that the expression
580 // isn't a constant expression. This diagnostic is more important,
581 // unless we require this evaluation to produce a constant expression.
582 //
583 // FIXME: We might want to show both diagnostics to the user in
584 // EM_ConstantFold mode.
585 if (!EvalStatus.Diag->empty()) {
586 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000587 case EM_ConstantFold:
588 case EM_IgnoreSideEffects:
589 case EM_EvaluateForOverflow:
590 if (!EvalStatus.HasSideEffects)
591 break;
592 // We've had side-effects; we want the diagnostic from them, not
593 // some later problem.
Richard Smith6d4c6582013-11-05 22:18:15 +0000594 case EM_ConstantExpression:
595 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000596 case EM_ConstantExpressionUnevaluated:
597 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000598 HasActiveDiagnostic = false;
599 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000600 }
601 }
602
Richard Smithf6f003a2011-12-16 19:06:07 +0000603 unsigned CallStackNotes = CallStackDepth - 1;
604 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
605 if (Limit)
606 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000607 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000608 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000609
Richard Smith357362d2011-12-13 06:39:58 +0000610 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000611 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000612 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
613 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000614 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000615 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000616 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000617 }
Richard Smith357362d2011-12-13 06:39:58 +0000618 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000619 return OptionalDiagnostic();
620 }
621
Richard Smithce1ec5e2012-03-15 04:53:45 +0000622 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
623 = diag::note_invalid_subexpr_in_const_expr,
624 unsigned ExtraNotes = 0) {
625 if (EvalStatus.Diag)
626 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
627 HasActiveDiagnostic = false;
628 return OptionalDiagnostic();
629 }
630
Richard Smith92b1ce02011-12-12 09:28:41 +0000631 /// Diagnose that the evaluation does not produce a C++11 core constant
632 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000633 ///
634 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
635 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000636 template<typename LocArg>
637 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000638 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000639 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000640 // Don't override a previous diagnostic. Don't bother collecting
641 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000642 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000643 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000644 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000645 }
Richard Smith357362d2011-12-13 06:39:58 +0000646 return Diag(Loc, DiagId, ExtraNotes);
647 }
648
649 /// Add a note to a prior diagnostic.
650 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
651 if (!HasActiveDiagnostic)
652 return OptionalDiagnostic();
653 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000654 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000655
656 /// Add a stack of notes to a prior diagnostic.
657 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
658 if (HasActiveDiagnostic) {
659 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
660 Diags.begin(), Diags.end());
661 }
662 }
Richard Smith253c2a32012-01-27 01:14:48 +0000663
Richard Smith6d4c6582013-11-05 22:18:15 +0000664 /// Should we continue evaluation after encountering a side-effect that we
665 /// couldn't model?
666 bool keepEvaluatingAfterSideEffect() {
667 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000668 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000669 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000670 case EM_EvaluateForOverflow:
671 case EM_IgnoreSideEffects:
672 return true;
673
Richard Smith6d4c6582013-11-05 22:18:15 +0000674 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000675 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000676 case EM_ConstantFold:
677 return false;
678 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000679 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000680 }
681
682 /// Note that we have had a side-effect, and determine whether we should
683 /// keep evaluating.
684 bool noteSideEffect() {
685 EvalStatus.HasSideEffects = true;
686 return keepEvaluatingAfterSideEffect();
687 }
688
Richard Smith253c2a32012-01-27 01:14:48 +0000689 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000690 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000691 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000692 if (!StepsLeft)
693 return false;
694
695 switch (EvalMode) {
696 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000697 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000698 case EM_EvaluateForOverflow:
699 return true;
700
701 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000702 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000703 case EM_ConstantFold:
704 case EM_IgnoreSideEffects:
705 return false;
706 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000707 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000708 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000709 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000710
711 /// Object used to treat all foldable expressions as constant expressions.
712 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000713 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000714 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000715 bool HadNoPriorDiags;
716 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000717
Richard Smith6d4c6582013-11-05 22:18:15 +0000718 explicit FoldConstant(EvalInfo &Info, bool Enabled)
719 : Info(Info),
720 Enabled(Enabled),
721 HadNoPriorDiags(Info.EvalStatus.Diag &&
722 Info.EvalStatus.Diag->empty() &&
723 !Info.EvalStatus.HasSideEffects),
724 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000725 if (Enabled &&
726 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
727 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000728 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000729 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000730 void keepDiagnostics() { Enabled = false; }
731 ~FoldConstant() {
732 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000733 !Info.EvalStatus.HasSideEffects)
734 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000735 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000736 }
737 };
Richard Smith17100ba2012-02-16 02:46:34 +0000738
739 /// RAII object used to suppress diagnostics and side-effects from a
740 /// speculative evaluation.
741 class SpeculativeEvaluationRAII {
742 EvalInfo &Info;
743 Expr::EvalStatus Old;
744
745 public:
746 SpeculativeEvaluationRAII(EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +0000747 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Richard Smith17100ba2012-02-16 02:46:34 +0000748 : Info(Info), Old(Info.EvalStatus) {
749 Info.EvalStatus.Diag = NewDiag;
Richard Smith6d4c6582013-11-05 22:18:15 +0000750 // If we're speculatively evaluating, we may have skipped over some
751 // evaluations and missed out a side effect.
752 Info.EvalStatus.HasSideEffects = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000753 }
754 ~SpeculativeEvaluationRAII() {
755 Info.EvalStatus = Old;
756 }
757 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000758
759 /// RAII object wrapping a full-expression or block scope, and handling
760 /// the ending of the lifetime of temporaries created within it.
761 template<bool IsFullExpression>
762 class ScopeRAII {
763 EvalInfo &Info;
764 unsigned OldStackSize;
765 public:
766 ScopeRAII(EvalInfo &Info)
767 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
768 ~ScopeRAII() {
769 // Body moved to a static method to encourage the compiler to inline away
770 // instances of this class.
771 cleanup(Info, OldStackSize);
772 }
773 private:
774 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
775 unsigned NewEnd = OldStackSize;
776 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
777 I != N; ++I) {
778 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
779 // Full-expression cleanup of a lifetime-extended temporary: nothing
780 // to do, just move this cleanup to the right place in the stack.
781 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
782 ++NewEnd;
783 } else {
784 // End the lifetime of the object.
785 Info.CleanupStack[I].endLifetime();
786 }
787 }
788 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
789 Info.CleanupStack.end());
790 }
791 };
792 typedef ScopeRAII<false> BlockScopeRAII;
793 typedef ScopeRAII<true> FullExpressionRAII;
Richard Smithf6f003a2011-12-16 19:06:07 +0000794}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000795
Richard Smitha8105bc2012-01-06 16:39:00 +0000796bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
797 CheckSubobjectKind CSK) {
798 if (Invalid)
799 return false;
800 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000801 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000802 << CSK;
803 setInvalid();
804 return false;
805 }
806 return true;
807}
808
809void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
810 const Expr *E, uint64_t N) {
811 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000812 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000813 << static_cast<int>(N) << /*array*/ 0
814 << static_cast<unsigned>(MostDerivedArraySize);
815 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000816 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000817 << static_cast<int>(N) << /*non-array*/ 1;
818 setInvalid();
819}
820
Richard Smithf6f003a2011-12-16 19:06:07 +0000821CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
822 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000823 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000824 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000825 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000826 Info.CurrentCall = this;
827 ++Info.CallStackDepth;
828}
829
830CallStackFrame::~CallStackFrame() {
831 assert(Info.CurrentCall == this && "calls retired out of order");
832 --Info.CallStackDepth;
833 Info.CurrentCall = Caller;
834}
835
Richard Smith08d6a2c2013-07-24 07:11:57 +0000836APValue &CallStackFrame::createTemporary(const void *Key,
837 bool IsLifetimeExtended) {
838 APValue &Result = Temporaries[Key];
839 assert(Result.isUninit() && "temporary created multiple times");
840 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
841 return Result;
842}
843
Richard Smith84401042013-06-03 05:03:02 +0000844static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000845
846void EvalInfo::addCallStack(unsigned Limit) {
847 // Determine which calls to skip, if any.
848 unsigned ActiveCalls = CallStackDepth - 1;
849 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
850 if (Limit && Limit < ActiveCalls) {
851 SkipStart = Limit / 2 + Limit % 2;
852 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000853 }
854
Richard Smithf6f003a2011-12-16 19:06:07 +0000855 // Walk the call stack and add the diagnostics.
856 unsigned CallIdx = 0;
857 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
858 Frame = Frame->Caller, ++CallIdx) {
859 // Skip this call?
860 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
861 if (CallIdx == SkipStart) {
862 // Note that we're skipping calls.
863 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
864 << unsigned(ActiveCalls - Limit);
865 }
866 continue;
867 }
868
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000869 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000870 llvm::raw_svector_ostream Out(Buffer);
871 describeCall(Frame, Out);
872 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
873 }
874}
875
876namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000877 struct ComplexValue {
878 private:
879 bool IsInt;
880
881 public:
882 APSInt IntReal, IntImag;
883 APFloat FloatReal, FloatImag;
884
885 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
886
887 void makeComplexFloat() { IsInt = false; }
888 bool isComplexFloat() const { return !IsInt; }
889 APFloat &getComplexFloatReal() { return FloatReal; }
890 APFloat &getComplexFloatImag() { return FloatImag; }
891
892 void makeComplexInt() { IsInt = true; }
893 bool isComplexInt() const { return IsInt; }
894 APSInt &getComplexIntReal() { return IntReal; }
895 APSInt &getComplexIntImag() { return IntImag; }
896
Richard Smith2e312c82012-03-03 22:46:17 +0000897 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000898 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000899 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000900 else
Richard Smith2e312c82012-03-03 22:46:17 +0000901 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000902 }
Richard Smith2e312c82012-03-03 22:46:17 +0000903 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000904 assert(v.isComplexFloat() || v.isComplexInt());
905 if (v.isComplexFloat()) {
906 makeComplexFloat();
907 FloatReal = v.getComplexFloatReal();
908 FloatImag = v.getComplexFloatImag();
909 } else {
910 makeComplexInt();
911 IntReal = v.getComplexIntReal();
912 IntImag = v.getComplexIntImag();
913 }
914 }
John McCall93d91dc2010-05-07 17:22:02 +0000915 };
John McCall45d55e42010-05-07 21:00:08 +0000916
917 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000918 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000919 CharUnits Offset;
Richard Smithb228a862012-02-15 02:18:13 +0000920 unsigned CallIndex;
Richard Smith96e0c102011-11-04 02:25:55 +0000921 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000922
Richard Smithce40ad62011-11-12 22:28:03 +0000923 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000924 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000925 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000926 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000927 SubobjectDesignator &getLValueDesignator() { return Designator; }
928 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000929
Richard Smith2e312c82012-03-03 22:46:17 +0000930 void moveInto(APValue &V) const {
931 if (Designator.Invalid)
932 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
933 else
934 V = APValue(Base, Offset, Designator.Entries,
935 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000936 }
Richard Smith2e312c82012-03-03 22:46:17 +0000937 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000938 assert(V.isLValue());
939 Base = V.getLValueBase();
940 Offset = V.getLValueOffset();
Richard Smithb228a862012-02-15 02:18:13 +0000941 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000942 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000943 }
944
Richard Smithb228a862012-02-15 02:18:13 +0000945 void set(APValue::LValueBase B, unsigned I = 0) {
Richard Smithce40ad62011-11-12 22:28:03 +0000946 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000947 Offset = CharUnits::Zero();
Richard Smithb228a862012-02-15 02:18:13 +0000948 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000949 Designator = SubobjectDesignator(getType(B));
950 }
951
952 // Check that this LValue is not based on a null pointer. If it is, produce
953 // a diagnostic and mark the designator as invalid.
954 bool checkNullPointer(EvalInfo &Info, const Expr *E,
955 CheckSubobjectKind CSK) {
956 if (Designator.Invalid)
957 return false;
958 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000959 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000960 << CSK;
961 Designator.setInvalid();
962 return false;
963 }
964 return true;
965 }
966
967 // Check this LValue refers to an object. If not, set the designator to be
968 // invalid and emit a diagnostic.
969 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000970 // Outside C++11, do not build a designator referring to a subobject of
971 // any object: we won't use such a designator for anything.
Richard Smith2bf7fdb2013-01-02 11:42:31 +0000972 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000973 Designator.setInvalid();
Richard Smith6c6bbfa2014-04-08 12:19:28 +0000974 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000975 Designator.checkSubobject(Info, E, CSK);
976 }
977
978 void addDecl(EvalInfo &Info, const Expr *E,
979 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000980 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
981 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +0000982 }
983 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000984 if (checkSubobject(Info, E, CSK_ArrayToPointer))
985 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +0000986 }
Richard Smith66c96992012-02-18 22:04:06 +0000987 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000988 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
989 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +0000990 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000991 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +0000992 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +0000993 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +0000994 }
John McCall45d55e42010-05-07 21:00:08 +0000995 };
Richard Smith027bf112011-11-17 22:56:20 +0000996
997 struct MemberPtr {
998 MemberPtr() {}
999 explicit MemberPtr(const ValueDecl *Decl) :
1000 DeclAndIsDerivedMember(Decl, false), Path() {}
1001
1002 /// The member or (direct or indirect) field referred to by this member
1003 /// pointer, or 0 if this is a null member pointer.
1004 const ValueDecl *getDecl() const {
1005 return DeclAndIsDerivedMember.getPointer();
1006 }
1007 /// Is this actually a member of some type derived from the relevant class?
1008 bool isDerivedMember() const {
1009 return DeclAndIsDerivedMember.getInt();
1010 }
1011 /// Get the class which the declaration actually lives in.
1012 const CXXRecordDecl *getContainingRecord() const {
1013 return cast<CXXRecordDecl>(
1014 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1015 }
1016
Richard Smith2e312c82012-03-03 22:46:17 +00001017 void moveInto(APValue &V) const {
1018 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001019 }
Richard Smith2e312c82012-03-03 22:46:17 +00001020 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001021 assert(V.isMemberPointer());
1022 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1023 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1024 Path.clear();
1025 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1026 Path.insert(Path.end(), P.begin(), P.end());
1027 }
1028
1029 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1030 /// whether the member is a member of some class derived from the class type
1031 /// of the member pointer.
1032 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1033 /// Path - The path of base/derived classes from the member declaration's
1034 /// class (exclusive) to the class type of the member pointer (inclusive).
1035 SmallVector<const CXXRecordDecl*, 4> Path;
1036
1037 /// Perform a cast towards the class of the Decl (either up or down the
1038 /// hierarchy).
1039 bool castBack(const CXXRecordDecl *Class) {
1040 assert(!Path.empty());
1041 const CXXRecordDecl *Expected;
1042 if (Path.size() >= 2)
1043 Expected = Path[Path.size() - 2];
1044 else
1045 Expected = getContainingRecord();
1046 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1047 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1048 // if B does not contain the original member and is not a base or
1049 // derived class of the class containing the original member, the result
1050 // of the cast is undefined.
1051 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1052 // (D::*). We consider that to be a language defect.
1053 return false;
1054 }
1055 Path.pop_back();
1056 return true;
1057 }
1058 /// Perform a base-to-derived member pointer cast.
1059 bool castToDerived(const CXXRecordDecl *Derived) {
1060 if (!getDecl())
1061 return true;
1062 if (!isDerivedMember()) {
1063 Path.push_back(Derived);
1064 return true;
1065 }
1066 if (!castBack(Derived))
1067 return false;
1068 if (Path.empty())
1069 DeclAndIsDerivedMember.setInt(false);
1070 return true;
1071 }
1072 /// Perform a derived-to-base member pointer cast.
1073 bool castToBase(const CXXRecordDecl *Base) {
1074 if (!getDecl())
1075 return true;
1076 if (Path.empty())
1077 DeclAndIsDerivedMember.setInt(true);
1078 if (isDerivedMember()) {
1079 Path.push_back(Base);
1080 return true;
1081 }
1082 return castBack(Base);
1083 }
1084 };
Richard Smith357362d2011-12-13 06:39:58 +00001085
Richard Smith7bb00672012-02-01 01:42:44 +00001086 /// Compare two member pointers, which are assumed to be of the same type.
1087 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1088 if (!LHS.getDecl() || !RHS.getDecl())
1089 return !LHS.getDecl() && !RHS.getDecl();
1090 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1091 return false;
1092 return LHS.Path == RHS.Path;
1093 }
John McCall93d91dc2010-05-07 17:22:02 +00001094}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001095
Richard Smith2e312c82012-03-03 22:46:17 +00001096static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001097static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1098 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001099 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001100static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1101static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001102static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1103 EvalInfo &Info);
1104static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +00001105static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001106static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001107 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001108static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001109static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001110static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +00001111
1112//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001113// Misc utilities
1114//===----------------------------------------------------------------------===//
1115
Richard Smith84401042013-06-03 05:03:02 +00001116/// Produce a string describing the given constexpr call.
1117static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1118 unsigned ArgIndex = 0;
1119 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1120 !isa<CXXConstructorDecl>(Frame->Callee) &&
1121 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1122
1123 if (!IsMemberCall)
1124 Out << *Frame->Callee << '(';
1125
1126 if (Frame->This && IsMemberCall) {
1127 APValue Val;
1128 Frame->This->moveInto(Val);
1129 Val.printPretty(Out, Frame->Info.Ctx,
1130 Frame->This->Designator.MostDerivedType);
1131 // FIXME: Add parens around Val if needed.
1132 Out << "->" << *Frame->Callee << '(';
1133 IsMemberCall = false;
1134 }
1135
1136 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1137 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1138 if (ArgIndex > (unsigned)IsMemberCall)
1139 Out << ", ";
1140
1141 const ParmVarDecl *Param = *I;
1142 const APValue &Arg = Frame->Arguments[ArgIndex];
1143 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1144
1145 if (ArgIndex == 0 && IsMemberCall)
1146 Out << "->" << *Frame->Callee << '(';
1147 }
1148
1149 Out << ')';
1150}
1151
Richard Smithd9f663b2013-04-22 15:31:51 +00001152/// Evaluate an expression to see if it had side-effects, and discard its
1153/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001154/// \return \c true if the caller should keep evaluating.
1155static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001156 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001157 if (!Evaluate(Scratch, Info, E))
1158 // We don't need the value, but we might have skipped a side effect here.
1159 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001160 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001161}
1162
Richard Smith861b5b52013-05-07 23:34:45 +00001163/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1164/// return its existing value.
1165static int64_t getExtValue(const APSInt &Value) {
1166 return Value.isSigned() ? Value.getSExtValue()
1167 : static_cast<int64_t>(Value.getZExtValue());
1168}
1169
Richard Smithd62306a2011-11-10 06:34:14 +00001170/// Should this call expression be treated as a string literal?
1171static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001172 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001173 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1174 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1175}
1176
Richard Smithce40ad62011-11-12 22:28:03 +00001177static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001178 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1179 // constant expression of pointer type that evaluates to...
1180
1181 // ... a null pointer value, or a prvalue core constant expression of type
1182 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001183 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001184
Richard Smithce40ad62011-11-12 22:28:03 +00001185 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1186 // ... the address of an object with static storage duration,
1187 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1188 return VD->hasGlobalStorage();
1189 // ... the address of a function,
1190 return isa<FunctionDecl>(D);
1191 }
1192
1193 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001194 switch (E->getStmtClass()) {
1195 default:
1196 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001197 case Expr::CompoundLiteralExprClass: {
1198 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1199 return CLE->isFileScope() && CLE->isLValue();
1200 }
Richard Smithe6c01442013-06-05 00:46:14 +00001201 case Expr::MaterializeTemporaryExprClass:
1202 // A materialized temporary might have been lifetime-extended to static
1203 // storage duration.
1204 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001205 // A string literal has static storage duration.
1206 case Expr::StringLiteralClass:
1207 case Expr::PredefinedExprClass:
1208 case Expr::ObjCStringLiteralClass:
1209 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001210 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001211 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001212 return true;
1213 case Expr::CallExprClass:
1214 return IsStringLiteralCall(cast<CallExpr>(E));
1215 // For GCC compatibility, &&label has static storage duration.
1216 case Expr::AddrLabelExprClass:
1217 return true;
1218 // A Block literal expression may be used as the initialization value for
1219 // Block variables at global or local static scope.
1220 case Expr::BlockExprClass:
1221 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001222 case Expr::ImplicitValueInitExprClass:
1223 // FIXME:
1224 // We can never form an lvalue with an implicit value initialization as its
1225 // base through expression evaluation, so these only appear in one case: the
1226 // implicit variable declaration we invent when checking whether a constexpr
1227 // constructor can produce a constant expression. We must assume that such
1228 // an expression might be a global lvalue.
1229 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001230 }
John McCall95007602010-05-10 23:27:23 +00001231}
1232
Richard Smithb228a862012-02-15 02:18:13 +00001233static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1234 assert(Base && "no location for a null lvalue");
1235 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1236 if (VD)
1237 Info.Note(VD->getLocation(), diag::note_declared_at);
1238 else
Ted Kremenek28831752012-08-23 20:46:57 +00001239 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001240 diag::note_constexpr_temporary_here);
1241}
1242
Richard Smith80815602011-11-07 05:07:52 +00001243/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001244/// value for an address or reference constant expression. Return true if we
1245/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001246static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1247 QualType Type, const LValue &LVal) {
1248 bool IsReferenceType = Type->isReferenceType();
1249
Richard Smith357362d2011-12-13 06:39:58 +00001250 APValue::LValueBase Base = LVal.getLValueBase();
1251 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1252
Richard Smith0dea49e2012-02-18 04:58:18 +00001253 // Check that the object is a global. Note that the fake 'this' object we
1254 // manufacture when checking potential constant expressions is conservatively
1255 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001256 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001257 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001258 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001259 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1260 << IsReferenceType << !Designator.Entries.empty()
1261 << !!VD << VD;
1262 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001263 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001264 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001265 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001266 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001267 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001268 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001269 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001270 LVal.getLValueCallIndex() == 0) &&
1271 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001272
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001273 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1274 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001275 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001276 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001277 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001278
Hans Wennborg82dd8772014-06-25 22:19:48 +00001279 // A dllimport variable never acts like a constant.
1280 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001281 return false;
1282 }
1283 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1284 // __declspec(dllimport) must be handled very carefully:
1285 // We must never initialize an expression with the thunk in C++.
1286 // Doing otherwise would allow the same id-expression to yield
1287 // different addresses for the same function in different translation
1288 // units. However, this means that we must dynamically initialize the
1289 // expression with the contents of the import address table at runtime.
1290 //
1291 // The C language has no notion of ODR; furthermore, it has no notion of
1292 // dynamic initialization. This means that we are permitted to
1293 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001294 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001295 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001296 }
1297 }
1298
Richard Smitha8105bc2012-01-06 16:39:00 +00001299 // Allow address constant expressions to be past-the-end pointers. This is
1300 // an extension: the standard requires them to point to an object.
1301 if (!IsReferenceType)
1302 return true;
1303
1304 // A reference constant expression must refer to an object.
1305 if (!Base) {
1306 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001307 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001308 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001309 }
1310
Richard Smith357362d2011-12-13 06:39:58 +00001311 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001312 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001313 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001314 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001315 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001316 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001317 }
1318
Richard Smith80815602011-11-07 05:07:52 +00001319 return true;
1320}
1321
Richard Smithfddd3842011-12-30 21:15:51 +00001322/// Check that this core constant expression is of literal type, and if not,
1323/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001324static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001325 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001326 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001327 return true;
1328
Richard Smith7525ff62013-05-09 07:14:00 +00001329 // C++1y: A constant initializer for an object o [...] may also invoke
1330 // constexpr constructors for o and its subobjects even if those objects
1331 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001332 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001333 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001334 return true;
1335
Richard Smithfddd3842011-12-30 21:15:51 +00001336 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001337 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001338 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001339 << E->getType();
1340 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001341 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001342 return false;
1343}
1344
Richard Smith0b0a0b62011-10-29 20:57:55 +00001345/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001346/// constant expression. If not, report an appropriate diagnostic. Does not
1347/// check that the expression is of literal type.
1348static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1349 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001350 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001351 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1352 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001353 return false;
1354 }
1355
Richard Smith77be48a2014-07-31 06:31:19 +00001356 // We allow _Atomic(T) to be initialized from anything that T can be
1357 // initialized from.
1358 if (const AtomicType *AT = Type->getAs<AtomicType>())
1359 Type = AT->getValueType();
1360
Richard Smithb228a862012-02-15 02:18:13 +00001361 // Core issue 1454: For a literal constant expression of array or class type,
1362 // each subobject of its value shall have been initialized by a constant
1363 // expression.
1364 if (Value.isArray()) {
1365 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1366 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1367 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1368 Value.getArrayInitializedElt(I)))
1369 return false;
1370 }
1371 if (!Value.hasArrayFiller())
1372 return true;
1373 return CheckConstantExpression(Info, DiagLoc, EltTy,
1374 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001375 }
Richard Smithb228a862012-02-15 02:18:13 +00001376 if (Value.isUnion() && Value.getUnionField()) {
1377 return CheckConstantExpression(Info, DiagLoc,
1378 Value.getUnionField()->getType(),
1379 Value.getUnionValue());
1380 }
1381 if (Value.isStruct()) {
1382 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1383 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1384 unsigned BaseIndex = 0;
1385 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1386 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1387 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1388 Value.getStructBase(BaseIndex)))
1389 return false;
1390 }
1391 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001392 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001393 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1394 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001395 return false;
1396 }
1397 }
1398
1399 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001400 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001401 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001402 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1403 }
1404
1405 // Everything else is fine.
1406 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001407}
1408
Richard Smith83c68212011-10-31 05:11:32 +00001409const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001410 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001411}
1412
1413static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001414 if (Value.CallIndex)
1415 return false;
1416 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1417 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001418}
1419
Richard Smithcecf1842011-11-01 21:06:14 +00001420static bool IsWeakLValue(const LValue &Value) {
1421 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001422 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001423}
1424
Richard Smith2e312c82012-03-03 22:46:17 +00001425static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001426 // A null base expression indicates a null pointer. These are always
1427 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001428 if (!Value.getLValueBase()) {
1429 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001430 return true;
1431 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001432
Richard Smith027bf112011-11-17 22:56:20 +00001433 // We have a non-null base. These are generally known to be true, but if it's
1434 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001435 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001436 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001437 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001438}
1439
Richard Smith2e312c82012-03-03 22:46:17 +00001440static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001441 switch (Val.getKind()) {
1442 case APValue::Uninitialized:
1443 return false;
1444 case APValue::Int:
1445 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001446 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001447 case APValue::Float:
1448 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001449 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001450 case APValue::ComplexInt:
1451 Result = Val.getComplexIntReal().getBoolValue() ||
1452 Val.getComplexIntImag().getBoolValue();
1453 return true;
1454 case APValue::ComplexFloat:
1455 Result = !Val.getComplexFloatReal().isZero() ||
1456 !Val.getComplexFloatImag().isZero();
1457 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001458 case APValue::LValue:
1459 return EvalPointerValueAsBool(Val, Result);
1460 case APValue::MemberPointer:
1461 Result = Val.getMemberPointerDecl();
1462 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001463 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001464 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001465 case APValue::Struct:
1466 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001467 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001468 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001469 }
1470
Richard Smith11562c52011-10-28 17:51:58 +00001471 llvm_unreachable("unknown APValue kind");
1472}
1473
1474static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1475 EvalInfo &Info) {
1476 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001477 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001478 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001479 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001480 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001481}
1482
Richard Smith357362d2011-12-13 06:39:58 +00001483template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001484static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001485 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001486 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001487 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001488}
1489
1490static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1491 QualType SrcType, const APFloat &Value,
1492 QualType DestType, APSInt &Result) {
1493 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001494 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001495 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001496
Richard Smith357362d2011-12-13 06:39:58 +00001497 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001498 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001499 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1500 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001501 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001502 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001503}
1504
Richard Smith357362d2011-12-13 06:39:58 +00001505static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1506 QualType SrcType, QualType DestType,
1507 APFloat &Result) {
1508 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001509 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001510 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1511 APFloat::rmNearestTiesToEven, &ignored)
1512 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001513 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001514 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001515}
1516
Richard Smith911e1422012-01-30 22:27:01 +00001517static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1518 QualType DestType, QualType SrcType,
1519 APSInt &Value) {
1520 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001521 APSInt Result = Value;
1522 // Figure out if this is a truncate, extend or noop cast.
1523 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001524 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001525 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001526 return Result;
1527}
1528
Richard Smith357362d2011-12-13 06:39:58 +00001529static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1530 QualType SrcType, const APSInt &Value,
1531 QualType DestType, APFloat &Result) {
1532 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1533 if (Result.convertFromAPInt(Value, Value.isSigned(),
1534 APFloat::rmNearestTiesToEven)
1535 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001536 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001537 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001538}
1539
Richard Smith49ca8aa2013-08-06 07:09:20 +00001540static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1541 APValue &Value, const FieldDecl *FD) {
1542 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1543
1544 if (!Value.isInt()) {
1545 // Trying to store a pointer-cast-to-integer into a bitfield.
1546 // FIXME: In this case, we should provide the diagnostic for casting
1547 // a pointer to an integer.
1548 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1549 Info.Diag(E);
1550 return false;
1551 }
1552
1553 APSInt &Int = Value.getInt();
1554 unsigned OldBitWidth = Int.getBitWidth();
1555 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1556 if (NewBitWidth < OldBitWidth)
1557 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1558 return true;
1559}
1560
Eli Friedman803acb32011-12-22 03:51:45 +00001561static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1562 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001563 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001564 if (!Evaluate(SVal, Info, E))
1565 return false;
1566 if (SVal.isInt()) {
1567 Res = SVal.getInt();
1568 return true;
1569 }
1570 if (SVal.isFloat()) {
1571 Res = SVal.getFloat().bitcastToAPInt();
1572 return true;
1573 }
1574 if (SVal.isVector()) {
1575 QualType VecTy = E->getType();
1576 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1577 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1578 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1579 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1580 Res = llvm::APInt::getNullValue(VecSize);
1581 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1582 APValue &Elt = SVal.getVectorElt(i);
1583 llvm::APInt EltAsInt;
1584 if (Elt.isInt()) {
1585 EltAsInt = Elt.getInt();
1586 } else if (Elt.isFloat()) {
1587 EltAsInt = Elt.getFloat().bitcastToAPInt();
1588 } else {
1589 // Don't try to handle vectors of anything other than int or float
1590 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001591 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001592 return false;
1593 }
1594 unsigned BaseEltSize = EltAsInt.getBitWidth();
1595 if (BigEndian)
1596 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1597 else
1598 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1599 }
1600 return true;
1601 }
1602 // Give up if the input isn't an int, float, or vector. For example, we
1603 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001604 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001605 return false;
1606}
1607
Richard Smith43e77732013-05-07 04:50:00 +00001608/// Perform the given integer operation, which is known to need at most BitWidth
1609/// bits, and check for overflow in the original type (if that type was not an
1610/// unsigned type).
1611template<typename Operation>
1612static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1613 const APSInt &LHS, const APSInt &RHS,
1614 unsigned BitWidth, Operation Op) {
1615 if (LHS.isUnsigned())
1616 return Op(LHS, RHS);
1617
1618 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1619 APSInt Result = Value.trunc(LHS.getBitWidth());
1620 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001621 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001622 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1623 diag::warn_integer_constant_overflow)
1624 << Result.toString(10) << E->getType();
1625 else
1626 HandleOverflow(Info, E, Value, E->getType());
1627 }
1628 return Result;
1629}
1630
1631/// Perform the given binary integer operation.
1632static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1633 BinaryOperatorKind Opcode, APSInt RHS,
1634 APSInt &Result) {
1635 switch (Opcode) {
1636 default:
1637 Info.Diag(E);
1638 return false;
1639 case BO_Mul:
1640 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1641 std::multiplies<APSInt>());
1642 return true;
1643 case BO_Add:
1644 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1645 std::plus<APSInt>());
1646 return true;
1647 case BO_Sub:
1648 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1649 std::minus<APSInt>());
1650 return true;
1651 case BO_And: Result = LHS & RHS; return true;
1652 case BO_Xor: Result = LHS ^ RHS; return true;
1653 case BO_Or: Result = LHS | RHS; return true;
1654 case BO_Div:
1655 case BO_Rem:
1656 if (RHS == 0) {
1657 Info.Diag(E, diag::note_expr_divide_by_zero);
1658 return false;
1659 }
1660 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1661 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1662 LHS.isSigned() && LHS.isMinSignedValue())
1663 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1664 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1665 return true;
1666 case BO_Shl: {
1667 if (Info.getLangOpts().OpenCL)
1668 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1669 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1670 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1671 RHS.isUnsigned());
1672 else if (RHS.isSigned() && RHS.isNegative()) {
1673 // During constant-folding, a negative shift is an opposite shift. Such
1674 // a shift is not a constant expression.
1675 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1676 RHS = -RHS;
1677 goto shift_right;
1678 }
1679 shift_left:
1680 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1681 // the shifted type.
1682 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1683 if (SA != RHS) {
1684 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1685 << RHS << E->getType() << LHS.getBitWidth();
1686 } else if (LHS.isSigned()) {
1687 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1688 // operand, and must not overflow the corresponding unsigned type.
1689 if (LHS.isNegative())
1690 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1691 else if (LHS.countLeadingZeros() < SA)
1692 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1693 }
1694 Result = LHS << SA;
1695 return true;
1696 }
1697 case BO_Shr: {
1698 if (Info.getLangOpts().OpenCL)
1699 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1700 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1701 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1702 RHS.isUnsigned());
1703 else if (RHS.isSigned() && RHS.isNegative()) {
1704 // During constant-folding, a negative shift is an opposite shift. Such a
1705 // shift is not a constant expression.
1706 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1707 RHS = -RHS;
1708 goto shift_left;
1709 }
1710 shift_right:
1711 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1712 // shifted type.
1713 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1714 if (SA != RHS)
1715 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1716 << RHS << E->getType() << LHS.getBitWidth();
1717 Result = LHS >> SA;
1718 return true;
1719 }
1720
1721 case BO_LT: Result = LHS < RHS; return true;
1722 case BO_GT: Result = LHS > RHS; return true;
1723 case BO_LE: Result = LHS <= RHS; return true;
1724 case BO_GE: Result = LHS >= RHS; return true;
1725 case BO_EQ: Result = LHS == RHS; return true;
1726 case BO_NE: Result = LHS != RHS; return true;
1727 }
1728}
1729
Richard Smith861b5b52013-05-07 23:34:45 +00001730/// Perform the given binary floating-point operation, in-place, on LHS.
1731static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1732 APFloat &LHS, BinaryOperatorKind Opcode,
1733 const APFloat &RHS) {
1734 switch (Opcode) {
1735 default:
1736 Info.Diag(E);
1737 return false;
1738 case BO_Mul:
1739 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1740 break;
1741 case BO_Add:
1742 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1743 break;
1744 case BO_Sub:
1745 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1746 break;
1747 case BO_Div:
1748 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1749 break;
1750 }
1751
1752 if (LHS.isInfinity() || LHS.isNaN())
1753 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1754 return true;
1755}
1756
Richard Smitha8105bc2012-01-06 16:39:00 +00001757/// Cast an lvalue referring to a base subobject to a derived class, by
1758/// truncating the lvalue's path to the given length.
1759static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1760 const RecordDecl *TruncatedType,
1761 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001762 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001763
1764 // Check we actually point to a derived class object.
1765 if (TruncatedElements == D.Entries.size())
1766 return true;
1767 assert(TruncatedElements >= D.MostDerivedPathLength &&
1768 "not casting to a derived class");
1769 if (!Result.checkSubobject(Info, E, CSK_Derived))
1770 return false;
1771
1772 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001773 const RecordDecl *RD = TruncatedType;
1774 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001775 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001776 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1777 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001778 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001779 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001780 else
Richard Smithd62306a2011-11-10 06:34:14 +00001781 Result.Offset -= Layout.getBaseClassOffset(Base);
1782 RD = Base;
1783 }
Richard Smith027bf112011-11-17 22:56:20 +00001784 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001785 return true;
1786}
1787
John McCalld7bca762012-05-01 00:38:49 +00001788static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001789 const CXXRecordDecl *Derived,
1790 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001791 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001792 if (!RL) {
1793 if (Derived->isInvalidDecl()) return false;
1794 RL = &Info.Ctx.getASTRecordLayout(Derived);
1795 }
1796
Richard Smithd62306a2011-11-10 06:34:14 +00001797 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001798 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001799 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001800}
1801
Richard Smitha8105bc2012-01-06 16:39:00 +00001802static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001803 const CXXRecordDecl *DerivedDecl,
1804 const CXXBaseSpecifier *Base) {
1805 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1806
John McCalld7bca762012-05-01 00:38:49 +00001807 if (!Base->isVirtual())
1808 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001809
Richard Smitha8105bc2012-01-06 16:39:00 +00001810 SubobjectDesignator &D = Obj.Designator;
1811 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001812 return false;
1813
Richard Smitha8105bc2012-01-06 16:39:00 +00001814 // Extract most-derived object and corresponding type.
1815 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1816 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1817 return false;
1818
1819 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001820 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001821 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1822 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001823 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001824 return true;
1825}
1826
Richard Smith84401042013-06-03 05:03:02 +00001827static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1828 QualType Type, LValue &Result) {
1829 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1830 PathE = E->path_end();
1831 PathI != PathE; ++PathI) {
1832 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1833 *PathI))
1834 return false;
1835 Type = (*PathI)->getType();
1836 }
1837 return true;
1838}
1839
Richard Smithd62306a2011-11-10 06:34:14 +00001840/// Update LVal to refer to the given field, which must be a member of the type
1841/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001842static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001843 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00001844 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001845 if (!RL) {
1846 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001847 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001848 }
Richard Smithd62306a2011-11-10 06:34:14 +00001849
1850 unsigned I = FD->getFieldIndex();
1851 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001852 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001853 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001854}
1855
Richard Smith1b78b3d2012-01-25 22:15:11 +00001856/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001857static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001858 LValue &LVal,
1859 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00001860 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00001861 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00001862 return false;
1863 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001864}
1865
Richard Smithd62306a2011-11-10 06:34:14 +00001866/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001867static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1868 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001869 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1870 // extension.
1871 if (Type->isVoidType() || Type->isFunctionType()) {
1872 Size = CharUnits::One();
1873 return true;
1874 }
1875
1876 if (!Type->isConstantSizeType()) {
1877 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001878 // FIXME: Better diagnostic.
1879 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001880 return false;
1881 }
1882
1883 Size = Info.Ctx.getTypeSizeInChars(Type);
1884 return true;
1885}
1886
1887/// Update a pointer value to model pointer arithmetic.
1888/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001889/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001890/// \param LVal - The pointer value to be updated.
1891/// \param EltTy - The pointee type represented by LVal.
1892/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001893static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1894 LValue &LVal, QualType EltTy,
1895 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001896 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001897 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001898 return false;
1899
1900 // Compute the new offset in the appropriate width.
1901 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001902 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001903 return true;
1904}
1905
Richard Smith66c96992012-02-18 22:04:06 +00001906/// Update an lvalue to refer to a component of a complex number.
1907/// \param Info - Information about the ongoing evaluation.
1908/// \param LVal - The lvalue to be updated.
1909/// \param EltTy - The complex number's component type.
1910/// \param Imag - False for the real component, true for the imaginary.
1911static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1912 LValue &LVal, QualType EltTy,
1913 bool Imag) {
1914 if (Imag) {
1915 CharUnits SizeOfComponent;
1916 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1917 return false;
1918 LVal.Offset += SizeOfComponent;
1919 }
1920 LVal.addComplex(Info, E, EltTy, Imag);
1921 return true;
1922}
1923
Richard Smith27908702011-10-24 17:54:18 +00001924/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001925///
1926/// \param Info Information about the ongoing evaluation.
1927/// \param E An expression to be used when printing diagnostics.
1928/// \param VD The variable whose initializer should be obtained.
1929/// \param Frame The frame in which the variable was created. Must be null
1930/// if this variable is not local to the evaluation.
1931/// \param Result Filled in with a pointer to the value of the variable.
1932static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1933 const VarDecl *VD, CallStackFrame *Frame,
1934 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001935 // If this is a parameter to an active constexpr function call, perform
1936 // argument substitution.
1937 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001938 // Assume arguments of a potential constant expression are unknown
1939 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00001940 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00001941 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001942 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001943 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001944 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001945 }
Richard Smith3229b742013-05-05 21:17:10 +00001946 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001947 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001948 }
Richard Smith27908702011-10-24 17:54:18 +00001949
Richard Smithd9f663b2013-04-22 15:31:51 +00001950 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001951 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001952 Result = Frame->getTemporary(VD);
1953 assert(Result && "missing value for local variable");
1954 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001955 }
1956
Richard Smithd0b4dd62011-12-19 06:19:21 +00001957 // Dig out the initializer, and use the declaration which it's attached to.
1958 const Expr *Init = VD->getAnyInitializer(VD);
1959 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00001960 // If we're checking a potential constant expression, the variable could be
1961 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00001962 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00001963 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00001964 return false;
1965 }
1966
Richard Smithd62306a2011-11-10 06:34:14 +00001967 // If we're currently evaluating the initializer of this declaration, use that
1968 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00001969 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00001970 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00001971 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001972 }
1973
Richard Smithcecf1842011-11-01 21:06:14 +00001974 // Never evaluate the initializer of a weak variable. We can't be sure that
1975 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00001976 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001977 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00001978 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001979 }
Richard Smithcecf1842011-11-01 21:06:14 +00001980
Richard Smithd0b4dd62011-12-19 06:19:21 +00001981 // Check that we can fold the initializer. In C++, we will have already done
1982 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001983 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001984 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001985 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001986 Notes.size() + 1) << VD;
1987 Info.Note(VD->getLocation(), diag::note_declared_at);
1988 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00001989 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00001990 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001991 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00001992 Notes.size() + 1) << VD;
1993 Info.Note(VD->getLocation(), diag::note_declared_at);
1994 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00001995 }
Richard Smith27908702011-10-24 17:54:18 +00001996
Richard Smith3229b742013-05-05 21:17:10 +00001997 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00001998 return true;
Richard Smith27908702011-10-24 17:54:18 +00001999}
2000
Richard Smith11562c52011-10-28 17:51:58 +00002001static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002002 Qualifiers Quals = T.getQualifiers();
2003 return Quals.hasConst() && !Quals.hasVolatile();
2004}
2005
Richard Smithe97cbd72011-11-11 04:05:33 +00002006/// Get the base index of the given base class within an APValue representing
2007/// the given derived class.
2008static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2009 const CXXRecordDecl *Base) {
2010 Base = Base->getCanonicalDecl();
2011 unsigned Index = 0;
2012 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2013 E = Derived->bases_end(); I != E; ++I, ++Index) {
2014 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2015 return Index;
2016 }
2017
2018 llvm_unreachable("base class missing from derived class's bases list");
2019}
2020
Richard Smith3da88fa2013-04-26 14:36:30 +00002021/// Extract the value of a character from a string literal.
2022static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2023 uint64_t Index) {
Richard Smith14a94132012-02-17 03:35:37 +00002024 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
Richard Smith3da88fa2013-04-26 14:36:30 +00002025 const StringLiteral *S = cast<StringLiteral>(Lit);
2026 const ConstantArrayType *CAT =
2027 Info.Ctx.getAsConstantArrayType(S->getType());
2028 assert(CAT && "string literal isn't an array");
2029 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002030 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002031
2032 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002033 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002034 if (Index < S->getLength())
2035 Value = S->getCodeUnit(Index);
2036 return Value;
2037}
2038
Richard Smith3da88fa2013-04-26 14:36:30 +00002039// Expand a string literal into an array of characters.
2040static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2041 APValue &Result) {
2042 const StringLiteral *S = cast<StringLiteral>(Lit);
2043 const ConstantArrayType *CAT =
2044 Info.Ctx.getAsConstantArrayType(S->getType());
2045 assert(CAT && "string literal isn't an array");
2046 QualType CharType = CAT->getElementType();
2047 assert(CharType->isIntegerType() && "unexpected character type");
2048
2049 unsigned Elts = CAT->getSize().getZExtValue();
2050 Result = APValue(APValue::UninitArray(),
2051 std::min(S->getLength(), Elts), Elts);
2052 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2053 CharType->isUnsignedIntegerType());
2054 if (Result.hasArrayFiller())
2055 Result.getArrayFiller() = APValue(Value);
2056 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2057 Value = S->getCodeUnit(I);
2058 Result.getArrayInitializedElt(I) = APValue(Value);
2059 }
2060}
2061
2062// Expand an array so that it has more than Index filled elements.
2063static void expandArray(APValue &Array, unsigned Index) {
2064 unsigned Size = Array.getArraySize();
2065 assert(Index < Size);
2066
2067 // Always at least double the number of elements for which we store a value.
2068 unsigned OldElts = Array.getArrayInitializedElts();
2069 unsigned NewElts = std::max(Index+1, OldElts * 2);
2070 NewElts = std::min(Size, std::max(NewElts, 8u));
2071
2072 // Copy the data across.
2073 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2074 for (unsigned I = 0; I != OldElts; ++I)
2075 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2076 for (unsigned I = OldElts; I != NewElts; ++I)
2077 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2078 if (NewValue.hasArrayFiller())
2079 NewValue.getArrayFiller() = Array.getArrayFiller();
2080 Array.swap(NewValue);
2081}
2082
Richard Smithb01fe402014-09-16 01:24:02 +00002083/// Determine whether a type would actually be read by an lvalue-to-rvalue
2084/// conversion. If it's of class type, we may assume that the copy operation
2085/// is trivial. Note that this is never true for a union type with fields
2086/// (because the copy always "reads" the active member) and always true for
2087/// a non-class type.
2088static bool isReadByLvalueToRvalueConversion(QualType T) {
2089 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2090 if (!RD || (RD->isUnion() && !RD->field_empty()))
2091 return true;
2092 if (RD->isEmpty())
2093 return false;
2094
2095 for (auto *Field : RD->fields())
2096 if (isReadByLvalueToRvalueConversion(Field->getType()))
2097 return true;
2098
2099 for (auto &BaseSpec : RD->bases())
2100 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2101 return true;
2102
2103 return false;
2104}
2105
2106/// Diagnose an attempt to read from any unreadable field within the specified
2107/// type, which might be a class type.
2108static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2109 QualType T) {
2110 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2111 if (!RD)
2112 return false;
2113
2114 if (!RD->hasMutableFields())
2115 return false;
2116
2117 for (auto *Field : RD->fields()) {
2118 // If we're actually going to read this field in some way, then it can't
2119 // be mutable. If we're in a union, then assigning to a mutable field
2120 // (even an empty one) can change the active member, so that's not OK.
2121 // FIXME: Add core issue number for the union case.
2122 if (Field->isMutable() &&
2123 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2124 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2125 Info.Note(Field->getLocation(), diag::note_declared_at);
2126 return true;
2127 }
2128
2129 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2130 return true;
2131 }
2132
2133 for (auto &BaseSpec : RD->bases())
2134 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2135 return true;
2136
2137 // All mutable fields were empty, and thus not actually read.
2138 return false;
2139}
2140
Richard Smith861b5b52013-05-07 23:34:45 +00002141/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002142enum AccessKinds {
2143 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002144 AK_Assign,
2145 AK_Increment,
2146 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002147};
2148
Richard Smith3229b742013-05-05 21:17:10 +00002149/// A handle to a complete object (an object that is not a subobject of
2150/// another object).
2151struct CompleteObject {
2152 /// The value of the complete object.
2153 APValue *Value;
2154 /// The type of the complete object.
2155 QualType Type;
2156
Craig Topper36250ad2014-05-12 05:36:57 +00002157 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002158 CompleteObject(APValue *Value, QualType Type)
2159 : Value(Value), Type(Type) {
2160 assert(Value && "missing value for complete object");
2161 }
2162
David Blaikie7d170102013-05-15 07:37:26 +00002163 LLVM_EXPLICIT operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002164};
2165
Richard Smith3da88fa2013-04-26 14:36:30 +00002166/// Find the designated sub-object of an rvalue.
2167template<typename SubobjectHandler>
2168typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002169findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002170 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002171 if (Sub.Invalid)
2172 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002173 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002174 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002175 if (Info.getLangOpts().CPlusPlus11)
2176 Info.Diag(E, diag::note_constexpr_access_past_end)
2177 << handler.AccessKind;
2178 else
2179 Info.Diag(E);
2180 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002181 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002182
Richard Smith3229b742013-05-05 21:17:10 +00002183 APValue *O = Obj.Value;
2184 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002185 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002186
Richard Smithd62306a2011-11-10 06:34:14 +00002187 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002188 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2189 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002190 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002191 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2192 return handler.failed();
2193 }
2194
Richard Smith49ca8aa2013-08-06 07:09:20 +00002195 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002196 // If we are reading an object of class type, there may still be more
2197 // things we need to check: if there are any mutable subobjects, we
2198 // cannot perform this read. (This only happens when performing a trivial
2199 // copy or assignment.)
2200 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2201 diagnoseUnreadableFields(Info, E, ObjType))
2202 return handler.failed();
2203
Richard Smith49ca8aa2013-08-06 07:09:20 +00002204 if (!handler.found(*O, ObjType))
2205 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002206
Richard Smith49ca8aa2013-08-06 07:09:20 +00002207 // If we modified a bit-field, truncate it to the right width.
2208 if (handler.AccessKind != AK_Read &&
2209 LastField && LastField->isBitField() &&
2210 !truncateBitfieldValue(Info, E, *O, LastField))
2211 return false;
2212
2213 return true;
2214 }
2215
Craig Topper36250ad2014-05-12 05:36:57 +00002216 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002217 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002218 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002219 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002220 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002221 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002222 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002223 // Note, it should not be possible to form a pointer with a valid
2224 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002225 if (Info.getLangOpts().CPlusPlus11)
2226 Info.Diag(E, diag::note_constexpr_access_past_end)
2227 << handler.AccessKind;
2228 else
2229 Info.Diag(E);
2230 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002231 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002232
2233 ObjType = CAT->getElementType();
2234
Richard Smith14a94132012-02-17 03:35:37 +00002235 // An array object is represented as either an Array APValue or as an
2236 // LValue which refers to a string literal.
2237 if (O->isLValue()) {
2238 assert(I == N - 1 && "extracting subobject of character?");
2239 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002240 if (handler.AccessKind != AK_Read)
2241 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2242 *O);
2243 else
2244 return handler.foundString(*O, ObjType, Index);
2245 }
2246
2247 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002248 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002249 else if (handler.AccessKind != AK_Read) {
2250 expandArray(*O, Index);
2251 O = &O->getArrayInitializedElt(Index);
2252 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002253 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002254 } else if (ObjType->isAnyComplexType()) {
2255 // Next subobject is a complex number.
2256 uint64_t Index = Sub.Entries[I].ArrayIndex;
2257 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002258 if (Info.getLangOpts().CPlusPlus11)
2259 Info.Diag(E, diag::note_constexpr_access_past_end)
2260 << handler.AccessKind;
2261 else
2262 Info.Diag(E);
2263 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002264 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002265
2266 bool WasConstQualified = ObjType.isConstQualified();
2267 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2268 if (WasConstQualified)
2269 ObjType.addConst();
2270
Richard Smith66c96992012-02-18 22:04:06 +00002271 assert(I == N - 1 && "extracting subobject of scalar?");
2272 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002273 return handler.found(Index ? O->getComplexIntImag()
2274 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002275 } else {
2276 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002277 return handler.found(Index ? O->getComplexFloatImag()
2278 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002279 }
Richard Smithd62306a2011-11-10 06:34:14 +00002280 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002281 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002282 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002283 << Field;
2284 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002285 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002286 }
2287
Richard Smithd62306a2011-11-10 06:34:14 +00002288 // Next subobject is a class, struct or union field.
2289 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2290 if (RD->isUnion()) {
2291 const FieldDecl *UnionField = O->getUnionField();
2292 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002293 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002294 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2295 << handler.AccessKind << Field << !UnionField << UnionField;
2296 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002297 }
Richard Smithd62306a2011-11-10 06:34:14 +00002298 O = &O->getUnionValue();
2299 } else
2300 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002301
2302 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002303 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002304 if (WasConstQualified && !Field->isMutable())
2305 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002306
2307 if (ObjType.isVolatileQualified()) {
2308 if (Info.getLangOpts().CPlusPlus) {
2309 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002310 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2311 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002312 Info.Note(Field->getLocation(), diag::note_declared_at);
2313 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002314 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002315 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002316 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002317 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002318
2319 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002320 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002321 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002322 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2323 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2324 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002325
2326 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002327 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002328 if (WasConstQualified)
2329 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002330 }
2331 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002332}
2333
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002334namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002335struct ExtractSubobjectHandler {
2336 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002337 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002338
2339 static const AccessKinds AccessKind = AK_Read;
2340
2341 typedef bool result_type;
2342 bool failed() { return false; }
2343 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002344 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002345 return true;
2346 }
2347 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002348 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002349 return true;
2350 }
2351 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002352 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002353 return true;
2354 }
2355 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002356 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002357 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2358 return true;
2359 }
2360};
Richard Smith3229b742013-05-05 21:17:10 +00002361} // end anonymous namespace
2362
Richard Smith3da88fa2013-04-26 14:36:30 +00002363const AccessKinds ExtractSubobjectHandler::AccessKind;
2364
2365/// Extract the designated sub-object of an rvalue.
2366static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002367 const CompleteObject &Obj,
2368 const SubobjectDesignator &Sub,
2369 APValue &Result) {
2370 ExtractSubobjectHandler Handler = { Info, Result };
2371 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002372}
2373
Richard Smith3229b742013-05-05 21:17:10 +00002374namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002375struct ModifySubobjectHandler {
2376 EvalInfo &Info;
2377 APValue &NewVal;
2378 const Expr *E;
2379
2380 typedef bool result_type;
2381 static const AccessKinds AccessKind = AK_Assign;
2382
2383 bool checkConst(QualType QT) {
2384 // Assigning to a const object has undefined behavior.
2385 if (QT.isConstQualified()) {
2386 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2387 return false;
2388 }
2389 return true;
2390 }
2391
2392 bool failed() { return false; }
2393 bool found(APValue &Subobj, QualType SubobjType) {
2394 if (!checkConst(SubobjType))
2395 return false;
2396 // We've been given ownership of NewVal, so just swap it in.
2397 Subobj.swap(NewVal);
2398 return true;
2399 }
2400 bool found(APSInt &Value, QualType SubobjType) {
2401 if (!checkConst(SubobjType))
2402 return false;
2403 if (!NewVal.isInt()) {
2404 // Maybe trying to write a cast pointer value into a complex?
2405 Info.Diag(E);
2406 return false;
2407 }
2408 Value = NewVal.getInt();
2409 return true;
2410 }
2411 bool found(APFloat &Value, QualType SubobjType) {
2412 if (!checkConst(SubobjType))
2413 return false;
2414 Value = NewVal.getFloat();
2415 return true;
2416 }
2417 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2418 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2419 }
2420};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002421} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002422
Richard Smith3229b742013-05-05 21:17:10 +00002423const AccessKinds ModifySubobjectHandler::AccessKind;
2424
Richard Smith3da88fa2013-04-26 14:36:30 +00002425/// Update the designated sub-object of an rvalue to the given value.
2426static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002427 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002428 const SubobjectDesignator &Sub,
2429 APValue &NewVal) {
2430 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002431 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002432}
2433
Richard Smith84f6dcf2012-02-02 01:16:57 +00002434/// Find the position where two subobject designators diverge, or equivalently
2435/// the length of the common initial subsequence.
2436static unsigned FindDesignatorMismatch(QualType ObjType,
2437 const SubobjectDesignator &A,
2438 const SubobjectDesignator &B,
2439 bool &WasArrayIndex) {
2440 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2441 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002442 if (!ObjType.isNull() &&
2443 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002444 // Next subobject is an array element.
2445 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2446 WasArrayIndex = true;
2447 return I;
2448 }
Richard Smith66c96992012-02-18 22:04:06 +00002449 if (ObjType->isAnyComplexType())
2450 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2451 else
2452 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002453 } else {
2454 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2455 WasArrayIndex = false;
2456 return I;
2457 }
2458 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2459 // Next subobject is a field.
2460 ObjType = FD->getType();
2461 else
2462 // Next subobject is a base class.
2463 ObjType = QualType();
2464 }
2465 }
2466 WasArrayIndex = false;
2467 return I;
2468}
2469
2470/// Determine whether the given subobject designators refer to elements of the
2471/// same array object.
2472static bool AreElementsOfSameArray(QualType ObjType,
2473 const SubobjectDesignator &A,
2474 const SubobjectDesignator &B) {
2475 if (A.Entries.size() != B.Entries.size())
2476 return false;
2477
2478 bool IsArray = A.MostDerivedArraySize != 0;
2479 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2480 // A is a subobject of the array element.
2481 return false;
2482
2483 // If A (and B) designates an array element, the last entry will be the array
2484 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2485 // of length 1' case, and the entire path must match.
2486 bool WasArrayIndex;
2487 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2488 return CommonLength >= A.Entries.size() - IsArray;
2489}
2490
Richard Smith3229b742013-05-05 21:17:10 +00002491/// Find the complete object to which an LValue refers.
2492CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
2493 const LValue &LVal, QualType LValType) {
2494 if (!LVal.Base) {
2495 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2496 return CompleteObject();
2497 }
2498
Craig Topper36250ad2014-05-12 05:36:57 +00002499 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002500 if (LVal.CallIndex) {
2501 Frame = Info.getCallFrame(LVal.CallIndex);
2502 if (!Frame) {
2503 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2504 << AK << LVal.Base.is<const ValueDecl*>();
2505 NoteLValueLocation(Info, LVal.Base);
2506 return CompleteObject();
2507 }
Richard Smith3229b742013-05-05 21:17:10 +00002508 }
2509
2510 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2511 // is not a constant expression (even if the object is non-volatile). We also
2512 // apply this rule to C++98, in order to conform to the expected 'volatile'
2513 // semantics.
2514 if (LValType.isVolatileQualified()) {
2515 if (Info.getLangOpts().CPlusPlus)
2516 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2517 << AK << LValType;
2518 else
2519 Info.Diag(E);
2520 return CompleteObject();
2521 }
2522
2523 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002524 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002525 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002526
2527 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2528 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2529 // In C++11, constexpr, non-volatile variables initialized with constant
2530 // expressions are constant expressions too. Inside constexpr functions,
2531 // parameters are constant expressions even if they're non-const.
2532 // In C++1y, objects local to a constant expression (those with a Frame) are
2533 // both readable and writable inside constant expressions.
2534 // In C, such things can also be folded, although they are not ICEs.
2535 const VarDecl *VD = dyn_cast<VarDecl>(D);
2536 if (VD) {
2537 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2538 VD = VDef;
2539 }
2540 if (!VD || VD->isInvalidDecl()) {
2541 Info.Diag(E);
2542 return CompleteObject();
2543 }
2544
2545 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002546 if (BaseType.isVolatileQualified()) {
2547 if (Info.getLangOpts().CPlusPlus) {
2548 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2549 << AK << 1 << VD;
2550 Info.Note(VD->getLocation(), diag::note_declared_at);
2551 } else {
2552 Info.Diag(E);
2553 }
2554 return CompleteObject();
2555 }
2556
2557 // Unless we're looking at a local variable or argument in a constexpr call,
2558 // the variable we're reading must be const.
2559 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002560 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002561 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2562 // OK, we can read and modify an object if we're in the process of
2563 // evaluating its initializer, because its lifetime began in this
2564 // evaluation.
2565 } else if (AK != AK_Read) {
2566 // All the remaining cases only permit reading.
2567 Info.Diag(E, diag::note_constexpr_modify_global);
2568 return CompleteObject();
2569 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002570 // OK, we can read this variable.
2571 } else if (BaseType->isIntegralOrEnumerationType()) {
2572 if (!BaseType.isConstQualified()) {
2573 if (Info.getLangOpts().CPlusPlus) {
2574 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2575 Info.Note(VD->getLocation(), diag::note_declared_at);
2576 } else {
2577 Info.Diag(E);
2578 }
2579 return CompleteObject();
2580 }
2581 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2582 // We support folding of const floating-point types, in order to make
2583 // static const data members of such types (supported as an extension)
2584 // more useful.
2585 if (Info.getLangOpts().CPlusPlus11) {
2586 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2587 Info.Note(VD->getLocation(), diag::note_declared_at);
2588 } else {
2589 Info.CCEDiag(E);
2590 }
2591 } else {
2592 // FIXME: Allow folding of values of any literal type in all languages.
2593 if (Info.getLangOpts().CPlusPlus11) {
2594 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2595 Info.Note(VD->getLocation(), diag::note_declared_at);
2596 } else {
2597 Info.Diag(E);
2598 }
2599 return CompleteObject();
2600 }
2601 }
2602
2603 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2604 return CompleteObject();
2605 } else {
2606 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2607
2608 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002609 if (const MaterializeTemporaryExpr *MTE =
2610 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2611 assert(MTE->getStorageDuration() == SD_Static &&
2612 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002613
Richard Smithe6c01442013-06-05 00:46:14 +00002614 // Per C++1y [expr.const]p2:
2615 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2616 // - a [...] glvalue of integral or enumeration type that refers to
2617 // a non-volatile const object [...]
2618 // [...]
2619 // - a [...] glvalue of literal type that refers to a non-volatile
2620 // object whose lifetime began within the evaluation of e.
2621 //
2622 // C++11 misses the 'began within the evaluation of e' check and
2623 // instead allows all temporaries, including things like:
2624 // int &&r = 1;
2625 // int x = ++r;
2626 // constexpr int k = r;
2627 // Therefore we use the C++1y rules in C++11 too.
2628 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2629 const ValueDecl *ED = MTE->getExtendingDecl();
2630 if (!(BaseType.isConstQualified() &&
2631 BaseType->isIntegralOrEnumerationType()) &&
2632 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2633 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2634 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2635 return CompleteObject();
2636 }
2637
2638 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2639 assert(BaseVal && "got reference to unevaluated temporary");
2640 } else {
2641 Info.Diag(E);
2642 return CompleteObject();
2643 }
2644 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002645 BaseVal = Frame->getTemporary(Base);
2646 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002647 }
Richard Smith3229b742013-05-05 21:17:10 +00002648
2649 // Volatile temporary objects cannot be accessed in constant expressions.
2650 if (BaseType.isVolatileQualified()) {
2651 if (Info.getLangOpts().CPlusPlus) {
2652 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2653 << AK << 0;
2654 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2655 } else {
2656 Info.Diag(E);
2657 }
2658 return CompleteObject();
2659 }
2660 }
2661
Richard Smith7525ff62013-05-09 07:14:00 +00002662 // During the construction of an object, it is not yet 'const'.
2663 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2664 // and this doesn't do quite the right thing for const subobjects of the
2665 // object under construction.
2666 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2667 BaseType = Info.Ctx.getCanonicalType(BaseType);
2668 BaseType.removeLocalConst();
2669 }
2670
Richard Smith6d4c6582013-11-05 22:18:15 +00002671 // In C++1y, we can't safely access any mutable state when we might be
2672 // evaluating after an unmodeled side effect or an evaluation failure.
2673 //
2674 // FIXME: Not all local state is mutable. Allow local constant subobjects
2675 // to be read here (but take care with 'mutable' fields).
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002676 if (Frame && Info.getLangOpts().CPlusPlus14 &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002677 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002678 return CompleteObject();
2679
2680 return CompleteObject(BaseVal, BaseType);
2681}
2682
Richard Smith243ef902013-05-05 23:31:59 +00002683/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2684/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2685/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002686///
2687/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002688/// \param Conv - The expression for which we are performing the conversion.
2689/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002690/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2691/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002692/// \param LVal - The glvalue on which we are attempting to perform this action.
2693/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002694static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002695 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002696 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002697 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002698 return false;
2699
Richard Smith3229b742013-05-05 21:17:10 +00002700 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002701 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
Richard Smith3229b742013-05-05 21:17:10 +00002702 if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
2703 !Type.isVolatileQualified()) {
2704 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2705 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2706 // initializer until now for such expressions. Such an expression can't be
2707 // an ICE in C, so this only matters for fold.
2708 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2709 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002710 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002711 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002712 }
Richard Smith3229b742013-05-05 21:17:10 +00002713 APValue Lit;
2714 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2715 return false;
2716 CompleteObject LitObj(&Lit, Base->getType());
2717 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
2718 } else if (isa<StringLiteral>(Base)) {
2719 // We represent a string literal array as an lvalue pointing at the
2720 // corresponding expression, rather than building an array of chars.
2721 // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
2722 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2723 CompleteObject StrObj(&Str, Base->getType());
2724 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002725 }
Richard Smith11562c52011-10-28 17:51:58 +00002726 }
2727
Richard Smith3229b742013-05-05 21:17:10 +00002728 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2729 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002730}
2731
2732/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002733static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002734 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002735 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002736 return false;
2737
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002738 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith3229b742013-05-05 21:17:10 +00002739 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002740 return false;
2741 }
2742
Richard Smith3229b742013-05-05 21:17:10 +00002743 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2744 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002745}
2746
Richard Smith243ef902013-05-05 23:31:59 +00002747static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2748 return T->isSignedIntegerType() &&
2749 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2750}
2751
2752namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002753struct CompoundAssignSubobjectHandler {
2754 EvalInfo &Info;
2755 const Expr *E;
2756 QualType PromotedLHSType;
2757 BinaryOperatorKind Opcode;
2758 const APValue &RHS;
2759
2760 static const AccessKinds AccessKind = AK_Assign;
2761
2762 typedef bool result_type;
2763
2764 bool checkConst(QualType QT) {
2765 // Assigning to a const object has undefined behavior.
2766 if (QT.isConstQualified()) {
2767 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2768 return false;
2769 }
2770 return true;
2771 }
2772
2773 bool failed() { return false; }
2774 bool found(APValue &Subobj, QualType SubobjType) {
2775 switch (Subobj.getKind()) {
2776 case APValue::Int:
2777 return found(Subobj.getInt(), SubobjType);
2778 case APValue::Float:
2779 return found(Subobj.getFloat(), SubobjType);
2780 case APValue::ComplexInt:
2781 case APValue::ComplexFloat:
2782 // FIXME: Implement complex compound assignment.
2783 Info.Diag(E);
2784 return false;
2785 case APValue::LValue:
2786 return foundPointer(Subobj, SubobjType);
2787 default:
2788 // FIXME: can this happen?
2789 Info.Diag(E);
2790 return false;
2791 }
2792 }
2793 bool found(APSInt &Value, QualType SubobjType) {
2794 if (!checkConst(SubobjType))
2795 return false;
2796
2797 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2798 // We don't support compound assignment on integer-cast-to-pointer
2799 // values.
2800 Info.Diag(E);
2801 return false;
2802 }
2803
2804 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2805 SubobjType, Value);
2806 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2807 return false;
2808 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2809 return true;
2810 }
2811 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002812 return checkConst(SubobjType) &&
2813 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2814 Value) &&
2815 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2816 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002817 }
2818 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2819 if (!checkConst(SubobjType))
2820 return false;
2821
2822 QualType PointeeType;
2823 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2824 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002825
2826 if (PointeeType.isNull() || !RHS.isInt() ||
2827 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002828 Info.Diag(E);
2829 return false;
2830 }
2831
Richard Smith861b5b52013-05-07 23:34:45 +00002832 int64_t Offset = getExtValue(RHS.getInt());
2833 if (Opcode == BO_Sub)
2834 Offset = -Offset;
2835
2836 LValue LVal;
2837 LVal.setFrom(Info.Ctx, Subobj);
2838 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2839 return false;
2840 LVal.moveInto(Subobj);
2841 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002842 }
2843 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2844 llvm_unreachable("shouldn't encounter string elements here");
2845 }
2846};
2847} // end anonymous namespace
2848
2849const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2850
2851/// Perform a compound assignment of LVal <op>= RVal.
2852static bool handleCompoundAssignment(
2853 EvalInfo &Info, const Expr *E,
2854 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2855 BinaryOperatorKind Opcode, const APValue &RVal) {
2856 if (LVal.Designator.Invalid)
2857 return false;
2858
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002859 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith43e77732013-05-07 04:50:00 +00002860 Info.Diag(E);
2861 return false;
2862 }
2863
2864 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2865 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2866 RVal };
2867 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2868}
2869
2870namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002871struct IncDecSubobjectHandler {
2872 EvalInfo &Info;
2873 const Expr *E;
2874 AccessKinds AccessKind;
2875 APValue *Old;
2876
2877 typedef bool result_type;
2878
2879 bool checkConst(QualType QT) {
2880 // Assigning to a const object has undefined behavior.
2881 if (QT.isConstQualified()) {
2882 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2883 return false;
2884 }
2885 return true;
2886 }
2887
2888 bool failed() { return false; }
2889 bool found(APValue &Subobj, QualType SubobjType) {
2890 // Stash the old value. Also clear Old, so we don't clobber it later
2891 // if we're post-incrementing a complex.
2892 if (Old) {
2893 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00002894 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00002895 }
2896
2897 switch (Subobj.getKind()) {
2898 case APValue::Int:
2899 return found(Subobj.getInt(), SubobjType);
2900 case APValue::Float:
2901 return found(Subobj.getFloat(), SubobjType);
2902 case APValue::ComplexInt:
2903 return found(Subobj.getComplexIntReal(),
2904 SubobjType->castAs<ComplexType>()->getElementType()
2905 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2906 case APValue::ComplexFloat:
2907 return found(Subobj.getComplexFloatReal(),
2908 SubobjType->castAs<ComplexType>()->getElementType()
2909 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2910 case APValue::LValue:
2911 return foundPointer(Subobj, SubobjType);
2912 default:
2913 // FIXME: can this happen?
2914 Info.Diag(E);
2915 return false;
2916 }
2917 }
2918 bool found(APSInt &Value, QualType SubobjType) {
2919 if (!checkConst(SubobjType))
2920 return false;
2921
2922 if (!SubobjType->isIntegerType()) {
2923 // We don't support increment / decrement on integer-cast-to-pointer
2924 // values.
2925 Info.Diag(E);
2926 return false;
2927 }
2928
2929 if (Old) *Old = APValue(Value);
2930
2931 // bool arithmetic promotes to int, and the conversion back to bool
2932 // doesn't reduce mod 2^n, so special-case it.
2933 if (SubobjType->isBooleanType()) {
2934 if (AccessKind == AK_Increment)
2935 Value = 1;
2936 else
2937 Value = !Value;
2938 return true;
2939 }
2940
2941 bool WasNegative = Value.isNegative();
2942 if (AccessKind == AK_Increment) {
2943 ++Value;
2944
2945 if (!WasNegative && Value.isNegative() &&
2946 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2947 APSInt ActualValue(Value, /*IsUnsigned*/true);
2948 HandleOverflow(Info, E, ActualValue, SubobjType);
2949 }
2950 } else {
2951 --Value;
2952
2953 if (WasNegative && !Value.isNegative() &&
2954 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2955 unsigned BitWidth = Value.getBitWidth();
2956 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2957 ActualValue.setBit(BitWidth);
2958 HandleOverflow(Info, E, ActualValue, SubobjType);
2959 }
2960 }
2961 return true;
2962 }
2963 bool found(APFloat &Value, QualType SubobjType) {
2964 if (!checkConst(SubobjType))
2965 return false;
2966
2967 if (Old) *Old = APValue(Value);
2968
2969 APFloat One(Value.getSemantics(), 1);
2970 if (AccessKind == AK_Increment)
2971 Value.add(One, APFloat::rmNearestTiesToEven);
2972 else
2973 Value.subtract(One, APFloat::rmNearestTiesToEven);
2974 return true;
2975 }
2976 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2977 if (!checkConst(SubobjType))
2978 return false;
2979
2980 QualType PointeeType;
2981 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2982 PointeeType = PT->getPointeeType();
2983 else {
2984 Info.Diag(E);
2985 return false;
2986 }
2987
2988 LValue LVal;
2989 LVal.setFrom(Info.Ctx, Subobj);
2990 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
2991 AccessKind == AK_Increment ? 1 : -1))
2992 return false;
2993 LVal.moveInto(Subobj);
2994 return true;
2995 }
2996 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2997 llvm_unreachable("shouldn't encounter string elements here");
2998 }
2999};
3000} // end anonymous namespace
3001
3002/// Perform an increment or decrement on LVal.
3003static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3004 QualType LValType, bool IsIncrement, APValue *Old) {
3005 if (LVal.Designator.Invalid)
3006 return false;
3007
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003008 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith243ef902013-05-05 23:31:59 +00003009 Info.Diag(E);
3010 return false;
3011 }
3012
3013 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3014 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3015 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3016 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3017}
3018
Richard Smithe97cbd72011-11-11 04:05:33 +00003019/// Build an lvalue for the object argument of a member function call.
3020static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3021 LValue &This) {
3022 if (Object->getType()->isPointerType())
3023 return EvaluatePointer(Object, This, Info);
3024
3025 if (Object->isGLValue())
3026 return EvaluateLValue(Object, This, Info);
3027
Richard Smithd9f663b2013-04-22 15:31:51 +00003028 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003029 return EvaluateTemporary(Object, This, Info);
3030
Richard Smith3e79a572014-06-11 19:53:12 +00003031 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003032 return false;
3033}
3034
3035/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3036/// lvalue referring to the result.
3037///
3038/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003039/// \param LV - An lvalue referring to the base of the member pointer.
3040/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003041/// \param IncludeMember - Specifies whether the member itself is included in
3042/// the resulting LValue subobject designator. This is not possible when
3043/// creating a bound member function.
3044/// \return The field or method declaration to which the member pointer refers,
3045/// or 0 if evaluation fails.
3046static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003047 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003048 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003049 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003050 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003051 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003052 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003053 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003054
3055 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3056 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003057 if (!MemPtr.getDecl()) {
3058 // FIXME: Specific diagnostic.
3059 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003060 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003061 }
Richard Smith253c2a32012-01-27 01:14:48 +00003062
Richard Smith027bf112011-11-17 22:56:20 +00003063 if (MemPtr.isDerivedMember()) {
3064 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003065 // The end of the derived-to-base path for the base object must match the
3066 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003067 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003068 LV.Designator.Entries.size()) {
3069 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003070 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003071 }
Richard Smith027bf112011-11-17 22:56:20 +00003072 unsigned PathLengthToMember =
3073 LV.Designator.Entries.size() - MemPtr.Path.size();
3074 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3075 const CXXRecordDecl *LVDecl = getAsBaseClass(
3076 LV.Designator.Entries[PathLengthToMember + I]);
3077 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003078 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3079 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003080 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003081 }
Richard Smith027bf112011-11-17 22:56:20 +00003082 }
3083
3084 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003085 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003086 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003087 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003088 } else if (!MemPtr.Path.empty()) {
3089 // Extend the LValue path with the member pointer's path.
3090 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3091 MemPtr.Path.size() + IncludeMember);
3092
3093 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003094 if (const PointerType *PT = LVType->getAs<PointerType>())
3095 LVType = PT->getPointeeType();
3096 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3097 assert(RD && "member pointer access on non-class-type expression");
3098 // The first class in the path is that of the lvalue.
3099 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3100 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003101 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003102 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003103 RD = Base;
3104 }
3105 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003106 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3107 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003108 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003109 }
3110
3111 // Add the member. Note that we cannot build bound member functions here.
3112 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003113 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003114 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003115 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003116 } else if (const IndirectFieldDecl *IFD =
3117 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003118 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003119 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003120 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003121 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003122 }
Richard Smith027bf112011-11-17 22:56:20 +00003123 }
3124
3125 return MemPtr.getDecl();
3126}
3127
Richard Smith84401042013-06-03 05:03:02 +00003128static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3129 const BinaryOperator *BO,
3130 LValue &LV,
3131 bool IncludeMember = true) {
3132 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3133
3134 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3135 if (Info.keepEvaluatingAfterFailure()) {
3136 MemberPtr MemPtr;
3137 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3138 }
Craig Topper36250ad2014-05-12 05:36:57 +00003139 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003140 }
3141
3142 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3143 BO->getRHS(), IncludeMember);
3144}
3145
Richard Smith027bf112011-11-17 22:56:20 +00003146/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3147/// the provided lvalue, which currently refers to the base object.
3148static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3149 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003150 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003151 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003152 return false;
3153
Richard Smitha8105bc2012-01-06 16:39:00 +00003154 QualType TargetQT = E->getType();
3155 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3156 TargetQT = PT->getPointeeType();
3157
3158 // Check this cast lands within the final derived-to-base subobject path.
3159 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003160 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003161 << D.MostDerivedType << TargetQT;
3162 return false;
3163 }
3164
Richard Smith027bf112011-11-17 22:56:20 +00003165 // Check the type of the final cast. We don't need to check the path,
3166 // since a cast can only be formed if the path is unique.
3167 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003168 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3169 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003170 if (NewEntriesSize == D.MostDerivedPathLength)
3171 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3172 else
Richard Smith027bf112011-11-17 22:56:20 +00003173 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003174 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003175 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003176 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003177 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003178 }
Richard Smith027bf112011-11-17 22:56:20 +00003179
3180 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003181 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003182}
3183
Mike Stump876387b2009-10-27 22:09:17 +00003184namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003185enum EvalStmtResult {
3186 /// Evaluation failed.
3187 ESR_Failed,
3188 /// Hit a 'return' statement.
3189 ESR_Returned,
3190 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003191 ESR_Succeeded,
3192 /// Hit a 'continue' statement.
3193 ESR_Continue,
3194 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003195 ESR_Break,
3196 /// Still scanning for 'case' or 'default' statement.
3197 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003198};
3199}
3200
Richard Smithd9f663b2013-04-22 15:31:51 +00003201static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3202 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3203 // We don't need to evaluate the initializer for a static local.
3204 if (!VD->hasLocalStorage())
3205 return true;
3206
3207 LValue Result;
3208 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003209 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003210
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003211 const Expr *InitE = VD->getInit();
3212 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003213 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3214 << false << VD->getType();
3215 Val = APValue();
3216 return false;
3217 }
3218
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003219 if (InitE->isValueDependent())
3220 return false;
3221
3222 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003223 // Wipe out any partially-computed value, to allow tracking that this
3224 // evaluation failed.
3225 Val = APValue();
3226 return false;
3227 }
3228 }
3229
3230 return true;
3231}
3232
Richard Smith4e18ca52013-05-06 05:56:11 +00003233/// Evaluate a condition (either a variable declaration or an expression).
3234static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3235 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003236 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003237 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3238 return false;
3239 return EvaluateAsBooleanCondition(Cond, Result, Info);
3240}
3241
3242static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003243 const Stmt *S,
3244 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003245
3246/// Evaluate the body of a loop, and translate the result as appropriate.
3247static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003248 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003249 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003250 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003251 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003252 case ESR_Break:
3253 return ESR_Succeeded;
3254 case ESR_Succeeded:
3255 case ESR_Continue:
3256 return ESR_Continue;
3257 case ESR_Failed:
3258 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003259 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003260 return ESR;
3261 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003262 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003263}
3264
Richard Smith496ddcf2013-05-12 17:32:42 +00003265/// Evaluate a switch statement.
3266static EvalStmtResult EvaluateSwitch(APValue &Result, EvalInfo &Info,
3267 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003268 BlockScopeRAII Scope(Info);
3269
Richard Smith496ddcf2013-05-12 17:32:42 +00003270 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003271 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003272 {
3273 FullExpressionRAII Scope(Info);
3274 if (SS->getConditionVariable() &&
3275 !EvaluateDecl(Info, SS->getConditionVariable()))
3276 return ESR_Failed;
3277 if (!EvaluateInteger(SS->getCond(), Value, Info))
3278 return ESR_Failed;
3279 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003280
3281 // Find the switch case corresponding to the value of the condition.
3282 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003283 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003284 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3285 SC = SC->getNextSwitchCase()) {
3286 if (isa<DefaultStmt>(SC)) {
3287 Found = SC;
3288 continue;
3289 }
3290
3291 const CaseStmt *CS = cast<CaseStmt>(SC);
3292 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3293 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3294 : LHS;
3295 if (LHS <= Value && Value <= RHS) {
3296 Found = SC;
3297 break;
3298 }
3299 }
3300
3301 if (!Found)
3302 return ESR_Succeeded;
3303
3304 // Search the switch body for the switch case and evaluate it from there.
3305 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3306 case ESR_Break:
3307 return ESR_Succeeded;
3308 case ESR_Succeeded:
3309 case ESR_Continue:
3310 case ESR_Failed:
3311 case ESR_Returned:
3312 return ESR;
3313 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003314 // This can only happen if the switch case is nested within a statement
3315 // expression. We have no intention of supporting that.
3316 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3317 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003318 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003319 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003320}
3321
Richard Smith254a73d2011-10-28 22:34:42 +00003322// Evaluate a statement.
Richard Smith2e312c82012-03-03 22:46:17 +00003323static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003324 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003325 if (!Info.nextStep(S))
3326 return ESR_Failed;
3327
Richard Smith496ddcf2013-05-12 17:32:42 +00003328 // If we're hunting down a 'case' or 'default' label, recurse through
3329 // substatements until we hit the label.
3330 if (Case) {
3331 // FIXME: We don't start the lifetime of objects whose initialization we
3332 // jump over. However, such objects must be of class type with a trivial
3333 // default constructor that initialize all subobjects, so must be empty,
3334 // so this almost never matters.
3335 switch (S->getStmtClass()) {
3336 case Stmt::CompoundStmtClass:
3337 // FIXME: Precompute which substatement of a compound statement we
3338 // would jump to, and go straight there rather than performing a
3339 // linear scan each time.
3340 case Stmt::LabelStmtClass:
3341 case Stmt::AttributedStmtClass:
3342 case Stmt::DoStmtClass:
3343 break;
3344
3345 case Stmt::CaseStmtClass:
3346 case Stmt::DefaultStmtClass:
3347 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003348 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003349 break;
3350
3351 case Stmt::IfStmtClass: {
3352 // FIXME: Precompute which side of an 'if' we would jump to, and go
3353 // straight there rather than scanning both sides.
3354 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003355
3356 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3357 // preceded by our switch label.
3358 BlockScopeRAII Scope(Info);
3359
Richard Smith496ddcf2013-05-12 17:32:42 +00003360 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3361 if (ESR != ESR_CaseNotFound || !IS->getElse())
3362 return ESR;
3363 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3364 }
3365
3366 case Stmt::WhileStmtClass: {
3367 EvalStmtResult ESR =
3368 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3369 if (ESR != ESR_Continue)
3370 return ESR;
3371 break;
3372 }
3373
3374 case Stmt::ForStmtClass: {
3375 const ForStmt *FS = cast<ForStmt>(S);
3376 EvalStmtResult ESR =
3377 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3378 if (ESR != ESR_Continue)
3379 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003380 if (FS->getInc()) {
3381 FullExpressionRAII IncScope(Info);
3382 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3383 return ESR_Failed;
3384 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003385 break;
3386 }
3387
3388 case Stmt::DeclStmtClass:
3389 // FIXME: If the variable has initialization that can't be jumped over,
3390 // bail out of any immediately-surrounding compound-statement too.
3391 default:
3392 return ESR_CaseNotFound;
3393 }
3394 }
3395
Richard Smith254a73d2011-10-28 22:34:42 +00003396 switch (S->getStmtClass()) {
3397 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003398 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003399 // Don't bother evaluating beyond an expression-statement which couldn't
3400 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003401 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003402 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003403 return ESR_Failed;
3404 return ESR_Succeeded;
3405 }
3406
3407 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003408 return ESR_Failed;
3409
3410 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003411 return ESR_Succeeded;
3412
Richard Smithd9f663b2013-04-22 15:31:51 +00003413 case Stmt::DeclStmtClass: {
3414 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003415 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003416 // Each declaration initialization is its own full-expression.
3417 // FIXME: This isn't quite right; if we're performing aggregate
3418 // initialization, each braced subexpression is its own full-expression.
3419 FullExpressionRAII Scope(Info);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003420 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003421 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003422 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003423 return ESR_Succeeded;
3424 }
3425
Richard Smith357362d2011-12-13 06:39:58 +00003426 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003427 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003428 FullExpressionRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003429 if (RetExpr && !Evaluate(Result, Info, RetExpr))
Richard Smith357362d2011-12-13 06:39:58 +00003430 return ESR_Failed;
3431 return ESR_Returned;
3432 }
Richard Smith254a73d2011-10-28 22:34:42 +00003433
3434 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003435 BlockScopeRAII Scope(Info);
3436
Richard Smith254a73d2011-10-28 22:34:42 +00003437 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003438 for (const auto *BI : CS->body()) {
3439 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003440 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003441 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003442 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003443 return ESR;
3444 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003445 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003446 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003447
3448 case Stmt::IfStmtClass: {
3449 const IfStmt *IS = cast<IfStmt>(S);
3450
3451 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003452 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003453 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003454 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003455 return ESR_Failed;
3456
3457 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3458 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3459 if (ESR != ESR_Succeeded)
3460 return ESR;
3461 }
3462 return ESR_Succeeded;
3463 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003464
3465 case Stmt::WhileStmtClass: {
3466 const WhileStmt *WS = cast<WhileStmt>(S);
3467 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003468 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003469 bool Continue;
3470 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3471 Continue))
3472 return ESR_Failed;
3473 if (!Continue)
3474 break;
3475
3476 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3477 if (ESR != ESR_Continue)
3478 return ESR;
3479 }
3480 return ESR_Succeeded;
3481 }
3482
3483 case Stmt::DoStmtClass: {
3484 const DoStmt *DS = cast<DoStmt>(S);
3485 bool Continue;
3486 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003487 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003488 if (ESR != ESR_Continue)
3489 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003490 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003491
Richard Smith08d6a2c2013-07-24 07:11:57 +00003492 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003493 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3494 return ESR_Failed;
3495 } while (Continue);
3496 return ESR_Succeeded;
3497 }
3498
3499 case Stmt::ForStmtClass: {
3500 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003501 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003502 if (FS->getInit()) {
3503 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3504 if (ESR != ESR_Succeeded)
3505 return ESR;
3506 }
3507 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003508 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003509 bool Continue = true;
3510 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3511 FS->getCond(), Continue))
3512 return ESR_Failed;
3513 if (!Continue)
3514 break;
3515
3516 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3517 if (ESR != ESR_Continue)
3518 return ESR;
3519
Richard Smith08d6a2c2013-07-24 07:11:57 +00003520 if (FS->getInc()) {
3521 FullExpressionRAII IncScope(Info);
3522 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3523 return ESR_Failed;
3524 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003525 }
3526 return ESR_Succeeded;
3527 }
3528
Richard Smith896e0d72013-05-06 06:51:17 +00003529 case Stmt::CXXForRangeStmtClass: {
3530 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003531 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003532
3533 // Initialize the __range variable.
3534 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3535 if (ESR != ESR_Succeeded)
3536 return ESR;
3537
3538 // Create the __begin and __end iterators.
3539 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3540 if (ESR != ESR_Succeeded)
3541 return ESR;
3542
3543 while (true) {
3544 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003545 {
3546 bool Continue = true;
3547 FullExpressionRAII CondExpr(Info);
3548 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3549 return ESR_Failed;
3550 if (!Continue)
3551 break;
3552 }
Richard Smith896e0d72013-05-06 06:51:17 +00003553
3554 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003555 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003556 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3557 if (ESR != ESR_Succeeded)
3558 return ESR;
3559
3560 // Loop body.
3561 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3562 if (ESR != ESR_Continue)
3563 return ESR;
3564
3565 // Increment: ++__begin
3566 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3567 return ESR_Failed;
3568 }
3569
3570 return ESR_Succeeded;
3571 }
3572
Richard Smith496ddcf2013-05-12 17:32:42 +00003573 case Stmt::SwitchStmtClass:
3574 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3575
Richard Smith4e18ca52013-05-06 05:56:11 +00003576 case Stmt::ContinueStmtClass:
3577 return ESR_Continue;
3578
3579 case Stmt::BreakStmtClass:
3580 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003581
3582 case Stmt::LabelStmtClass:
3583 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3584
3585 case Stmt::AttributedStmtClass:
3586 // As a general principle, C++11 attributes can be ignored without
3587 // any semantic impact.
3588 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3589 Case);
3590
3591 case Stmt::CaseStmtClass:
3592 case Stmt::DefaultStmtClass:
3593 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003594 }
3595}
3596
Richard Smithcc36f692011-12-22 02:22:31 +00003597/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3598/// default constructor. If so, we'll fold it whether or not it's marked as
3599/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3600/// so we need special handling.
3601static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003602 const CXXConstructorDecl *CD,
3603 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003604 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3605 return false;
3606
Richard Smith66e05fe2012-01-18 05:21:49 +00003607 // Value-initialization does not call a trivial default constructor, so such a
3608 // call is a core constant expression whether or not the constructor is
3609 // constexpr.
3610 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003611 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003612 // FIXME: If DiagDecl is an implicitly-declared special member function,
3613 // we should be much more explicit about why it's not constexpr.
3614 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3615 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3616 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003617 } else {
3618 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3619 }
3620 }
3621 return true;
3622}
3623
Richard Smith357362d2011-12-13 06:39:58 +00003624/// CheckConstexprFunction - Check that a function can be called in a constant
3625/// expression.
3626static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3627 const FunctionDecl *Declaration,
3628 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003629 // Potential constant expressions can contain calls to declared, but not yet
3630 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003631 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003632 Declaration->isConstexpr())
3633 return false;
3634
Richard Smith0838f3a2013-05-14 05:18:44 +00003635 // Bail out with no diagnostic if the function declaration itself is invalid.
3636 // We will have produced a relevant diagnostic while parsing it.
3637 if (Declaration->isInvalidDecl())
3638 return false;
3639
Richard Smith357362d2011-12-13 06:39:58 +00003640 // Can we evaluate this function call?
3641 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3642 return true;
3643
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003644 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003645 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003646 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3647 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003648 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3649 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3650 << DiagDecl;
3651 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3652 } else {
3653 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3654 }
3655 return false;
3656}
3657
Richard Smithd62306a2011-11-10 06:34:14 +00003658namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003659typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003660}
3661
3662/// EvaluateArgs - Evaluate the arguments to a function call.
3663static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3664 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003665 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003666 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003667 I != E; ++I) {
3668 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3669 // If we're checking for a potential constant expression, evaluate all
3670 // initializers even if some of them fail.
3671 if (!Info.keepEvaluatingAfterFailure())
3672 return false;
3673 Success = false;
3674 }
3675 }
3676 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003677}
3678
Richard Smith254a73d2011-10-28 22:34:42 +00003679/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003680static bool HandleFunctionCall(SourceLocation CallLoc,
3681 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003682 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith2e312c82012-03-03 22:46:17 +00003683 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003684 ArgVector ArgValues(Args.size());
3685 if (!EvaluateArgs(Args, ArgValues, Info))
3686 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003687
Richard Smith253c2a32012-01-27 01:14:48 +00003688 if (!Info.CheckCallLimit(CallLoc))
3689 return false;
3690
3691 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003692
3693 // For a trivial copy or move assignment, perform an APValue copy. This is
3694 // essential for unions, where the operations performed by the assignment
3695 // operator cannot be represented as statements.
3696 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
3697 if (MD && MD->isDefaulted() && MD->isTrivial()) {
3698 assert(This &&
3699 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3700 LValue RHS;
3701 RHS.setFrom(Info.Ctx, ArgValues[0]);
3702 APValue RHSValue;
3703 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3704 RHS, RHSValue))
3705 return false;
3706 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3707 RHSValue))
3708 return false;
3709 This->moveInto(Result);
3710 return true;
3711 }
3712
Richard Smithd9f663b2013-04-22 15:31:51 +00003713 EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003714 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003715 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003716 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003717 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003718 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003719 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003720}
3721
Richard Smithd62306a2011-11-10 06:34:14 +00003722/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003723static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003724 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003725 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003726 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003727 ArgVector ArgValues(Args.size());
3728 if (!EvaluateArgs(Args, ArgValues, Info))
3729 return false;
3730
Richard Smith253c2a32012-01-27 01:14:48 +00003731 if (!Info.CheckCallLimit(CallLoc))
3732 return false;
3733
Richard Smith3607ffe2012-02-13 03:54:03 +00003734 const CXXRecordDecl *RD = Definition->getParent();
3735 if (RD->getNumVBases()) {
3736 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3737 return false;
3738 }
3739
Richard Smith253c2a32012-01-27 01:14:48 +00003740 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003741
3742 // If it's a delegating constructor, just delegate.
3743 if (Definition->isDelegatingConstructor()) {
3744 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003745 {
3746 FullExpressionRAII InitScope(Info);
3747 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3748 return false;
3749 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003750 return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003751 }
3752
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003753 // For a trivial copy or move constructor, perform an APValue copy. This is
3754 // essential for unions, where the operations performed by the constructor
3755 // cannot be represented by ctor-initializers.
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003756 if (Definition->isDefaulted() &&
Douglas Gregor093d4be2012-02-24 07:55:51 +00003757 ((Definition->isCopyConstructor() && Definition->isTrivial()) ||
3758 (Definition->isMoveConstructor() && Definition->isTrivial()))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003759 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003760 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003761 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003762 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003763 }
3764
3765 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003766 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003767 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003768 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00003769
John McCalld7bca762012-05-01 00:38:49 +00003770 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003771 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3772
Richard Smith08d6a2c2013-07-24 07:11:57 +00003773 // A scope for temporaries lifetime-extended by reference members.
3774 BlockScopeRAII LifetimeExtendedScope(Info);
3775
Richard Smith253c2a32012-01-27 01:14:48 +00003776 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003777 unsigned BasesSeen = 0;
3778#ifndef NDEBUG
3779 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3780#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003781 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00003782 LValue Subobject = This;
3783 APValue *Value = &Result;
3784
3785 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00003786 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00003787 if (I->isBaseInitializer()) {
3788 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00003789#ifndef NDEBUG
3790 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003791 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003792 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3793 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3794 "base class initializers not in expected order");
3795 ++BaseIt;
3796#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003797 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00003798 BaseType->getAsCXXRecordDecl(), &Layout))
3799 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003800 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003801 } else if ((FD = I->getMember())) {
3802 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003803 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003804 if (RD->isUnion()) {
3805 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003806 Value = &Result.getUnionValue();
3807 } else {
3808 Value = &Result.getStructField(FD->getFieldIndex());
3809 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003810 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003811 // Walk the indirect field decl's chain to find the object to initialize,
3812 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00003813 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003814 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003815 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3816 // Switch the union field if it differs. This happens if we had
3817 // preceding zero-initialization, and we're now initializing a union
3818 // subobject other than the first.
3819 // FIXME: In this case, the values of the other subobjects are
3820 // specified, since zero-initialization sets all padding bits to zero.
3821 if (Value->isUninit() ||
3822 (Value->isUnion() && Value->getUnionField() != FD)) {
3823 if (CD->isUnion())
3824 *Value = APValue(FD);
3825 else
3826 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003827 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00003828 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003829 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00003830 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003831 if (CD->isUnion())
3832 Value = &Value->getUnionValue();
3833 else
3834 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003835 }
Richard Smithd62306a2011-11-10 06:34:14 +00003836 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003837 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003838 }
Richard Smith253c2a32012-01-27 01:14:48 +00003839
Richard Smith08d6a2c2013-07-24 07:11:57 +00003840 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003841 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3842 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00003843 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003844 // If we're checking for a potential constant expression, evaluate all
3845 // initializers even if some of them fail.
3846 if (!Info.keepEvaluatingAfterFailure())
3847 return false;
3848 Success = false;
3849 }
Richard Smithd62306a2011-11-10 06:34:14 +00003850 }
3851
Richard Smithd9f663b2013-04-22 15:31:51 +00003852 return Success &&
3853 EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003854}
3855
Eli Friedman9a156e52008-11-12 09:44:48 +00003856//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003857// Generic Evaluation
3858//===----------------------------------------------------------------------===//
3859namespace {
3860
Aaron Ballman68af21c2014-01-03 19:26:43 +00003861template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00003862class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00003863 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00003864private:
Aaron Ballman68af21c2014-01-03 19:26:43 +00003865 bool DerivedSuccess(const APValue &V, const Expr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00003866 return static_cast<Derived*>(this)->Success(V, E);
3867 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003868 bool DerivedZeroInitialization(const Expr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00003869 return static_cast<Derived*>(this)->ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003870 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003871
Richard Smith17100ba2012-02-16 02:46:34 +00003872 // Check whether a conditional operator with a non-constant condition is a
3873 // potential constant expression. If neither arm is a potential constant
3874 // expression, then the conditional operator is not either.
3875 template<typename ConditionalOperator>
3876 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003877 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003878
3879 // Speculatively evaluate both arms.
3880 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003881 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003882 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3883
3884 StmtVisitorTy::Visit(E->getFalseExpr());
3885 if (Diag.empty())
3886 return;
3887
3888 Diag.clear();
3889 StmtVisitorTy::Visit(E->getTrueExpr());
3890 if (Diag.empty())
3891 return;
3892 }
3893
3894 Error(E, diag::note_constexpr_conditional_never_const);
3895 }
3896
3897
3898 template<typename ConditionalOperator>
3899 bool HandleConditionalOperator(const ConditionalOperator *E) {
3900 bool BoolResult;
3901 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003902 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00003903 CheckPotentialConstantConditional(E);
3904 return false;
3905 }
3906
3907 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3908 return StmtVisitorTy::Visit(EvalExpr);
3909 }
3910
Peter Collingbournee9200682011-05-13 03:29:01 +00003911protected:
3912 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00003913 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00003914 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
3915
Richard Smith92b1ce02011-12-12 09:28:41 +00003916 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003917 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003918 }
3919
Aaron Ballman68af21c2014-01-03 19:26:43 +00003920 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00003921
3922public:
3923 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
3924
3925 EvalInfo &getEvalInfo() { return Info; }
3926
Richard Smithf57d8cb2011-12-09 22:58:01 +00003927 /// Report an evaluation error. This should only be called when an error is
3928 /// first discovered. When propagating an error, just return false.
3929 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003930 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00003931 return false;
3932 }
3933 bool Error(const Expr *E) {
3934 return Error(E, diag::note_invalid_subexpr_in_const_expr);
3935 }
3936
Aaron Ballman68af21c2014-01-03 19:26:43 +00003937 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00003938 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00003939 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003940 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00003941 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003942 }
3943
Aaron Ballman68af21c2014-01-03 19:26:43 +00003944 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003945 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003946 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003947 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003948 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003949 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003950 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00003951 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003952 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00003953 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003954 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00003955 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003956 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00003957 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003958 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00003959 // The initializer may not have been parsed yet, or might be erroneous.
3960 if (!E->getExpr())
3961 return Error(E);
3962 return StmtVisitorTy::Visit(E->getExpr());
3963 }
Richard Smith5894a912011-12-19 22:12:41 +00003964 // We cannot create any objects for which cleanups are required, so there is
3965 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00003966 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00003967 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00003968
Aaron Ballman68af21c2014-01-03 19:26:43 +00003969 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003970 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
3971 return static_cast<Derived*>(this)->VisitCastExpr(E);
3972 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003973 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00003974 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
3975 return static_cast<Derived*>(this)->VisitCastExpr(E);
3976 }
3977
Aaron Ballman68af21c2014-01-03 19:26:43 +00003978 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00003979 switch (E->getOpcode()) {
3980 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00003981 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00003982
3983 case BO_Comma:
3984 VisitIgnoredValue(E->getLHS());
3985 return StmtVisitorTy::Visit(E->getRHS());
3986
3987 case BO_PtrMemD:
3988 case BO_PtrMemI: {
3989 LValue Obj;
3990 if (!HandleMemberPointerAccess(Info, E, Obj))
3991 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00003992 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00003993 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00003994 return false;
3995 return DerivedSuccess(Result, E);
3996 }
3997 }
3998 }
3999
Aaron Ballman68af21c2014-01-03 19:26:43 +00004000 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004001 // Evaluate and cache the common expression. We treat it as a temporary,
4002 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004003 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004004 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004005 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004006
Richard Smith17100ba2012-02-16 02:46:34 +00004007 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004008 }
4009
Aaron Ballman68af21c2014-01-03 19:26:43 +00004010 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004011 bool IsBcpCall = false;
4012 // If the condition (ignoring parens) is a __builtin_constant_p call,
4013 // the result is a constant expression if it can be folded without
4014 // side-effects. This is an important GNU extension. See GCC PR38377
4015 // for discussion.
4016 if (const CallExpr *CallCE =
4017 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004018 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004019 IsBcpCall = true;
4020
4021 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4022 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004023 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004024 return false;
4025
Richard Smith6d4c6582013-11-05 22:18:15 +00004026 FoldConstant Fold(Info, IsBcpCall);
4027 if (!HandleConditionalOperator(E)) {
4028 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004029 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004030 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004031
4032 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004033 }
4034
Aaron Ballman68af21c2014-01-03 19:26:43 +00004035 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004036 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4037 return DerivedSuccess(*Value, E);
4038
4039 const Expr *Source = E->getSourceExpr();
4040 if (!Source)
4041 return Error(E);
4042 if (Source == E) { // sanity checking.
4043 assert(0 && "OpaqueValueExpr recursively refers to itself");
4044 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004045 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004046 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004047 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004048
Aaron Ballman68af21c2014-01-03 19:26:43 +00004049 bool VisitCallExpr(const CallExpr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004050 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004051 QualType CalleeType = Callee->getType();
4052
Craig Topper36250ad2014-05-12 05:36:57 +00004053 const FunctionDecl *FD = nullptr;
4054 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004055 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004056 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004057
Richard Smithe97cbd72011-11-11 04:05:33 +00004058 // Extract function decl and 'this' pointer from the callee.
4059 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004060 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004061 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4062 // Explicit bound member calls, such as x.f() or p->g();
4063 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004064 return false;
4065 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004066 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004067 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004068 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4069 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004070 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4071 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004072 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004073 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004074 return Error(Callee);
4075
4076 FD = dyn_cast<FunctionDecl>(Member);
4077 if (!FD)
4078 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004079 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004080 LValue Call;
4081 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004082 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004083
Richard Smitha8105bc2012-01-06 16:39:00 +00004084 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004085 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004086 FD = dyn_cast_or_null<FunctionDecl>(
4087 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004088 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004089 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004090
4091 // Overloaded operator calls to member functions are represented as normal
4092 // calls with '*this' as the first argument.
4093 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4094 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004095 // FIXME: When selecting an implicit conversion for an overloaded
4096 // operator delete, we sometimes try to evaluate calls to conversion
4097 // operators without a 'this' parameter!
4098 if (Args.empty())
4099 return Error(E);
4100
Richard Smithe97cbd72011-11-11 04:05:33 +00004101 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4102 return false;
4103 This = &ThisVal;
4104 Args = Args.slice(1);
4105 }
4106
4107 // Don't call function pointers which have been cast to some other type.
4108 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004109 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004110 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004111 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004112
Richard Smith47b34932012-02-01 02:39:43 +00004113 if (This && !This->checkSubobject(Info, E, CSK_This))
4114 return false;
4115
Richard Smith3607ffe2012-02-13 03:54:03 +00004116 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4117 // calls to such functions in constant expressions.
4118 if (This && !HasQualifier &&
4119 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4120 return Error(E, diag::note_constexpr_virtual_call);
4121
Craig Topper36250ad2014-05-12 05:36:57 +00004122 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004123 Stmt *Body = FD->getBody(Definition);
Richard Smith2e312c82012-03-03 22:46:17 +00004124 APValue Result;
Richard Smith254a73d2011-10-28 22:34:42 +00004125
Richard Smith357362d2011-12-13 06:39:58 +00004126 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith253c2a32012-01-27 01:14:48 +00004127 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body,
4128 Info, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004129 return false;
4130
Richard Smithb228a862012-02-15 02:18:13 +00004131 return DerivedSuccess(Result, E);
Richard Smith254a73d2011-10-28 22:34:42 +00004132 }
4133
Aaron Ballman68af21c2014-01-03 19:26:43 +00004134 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004135 return StmtVisitorTy::Visit(E->getInitializer());
4136 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004137 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004138 if (E->getNumInits() == 0)
4139 return DerivedZeroInitialization(E);
4140 if (E->getNumInits() == 1)
4141 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004142 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004143 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004144 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004145 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004146 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004147 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004148 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004149 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004150 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004151 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004152 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004153
Richard Smithd62306a2011-11-10 06:34:14 +00004154 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004155 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004156 assert(!E->isArrow() && "missing call to bound member function?");
4157
Richard Smith2e312c82012-03-03 22:46:17 +00004158 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004159 if (!Evaluate(Val, Info, E->getBase()))
4160 return false;
4161
4162 QualType BaseTy = E->getBase()->getType();
4163
4164 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004165 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004166 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004167 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004168 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4169
Richard Smith3229b742013-05-05 21:17:10 +00004170 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004171 SubobjectDesignator Designator(BaseTy);
4172 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004173
Richard Smith3229b742013-05-05 21:17:10 +00004174 APValue Result;
4175 return extractSubobject(Info, E, Obj, Designator, Result) &&
4176 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004177 }
4178
Aaron Ballman68af21c2014-01-03 19:26:43 +00004179 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004180 switch (E->getCastKind()) {
4181 default:
4182 break;
4183
Richard Smitha23ab512013-05-23 00:30:41 +00004184 case CK_AtomicToNonAtomic: {
4185 APValue AtomicVal;
4186 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4187 return false;
4188 return DerivedSuccess(AtomicVal, E);
4189 }
4190
Richard Smith11562c52011-10-28 17:51:58 +00004191 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004192 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004193 return StmtVisitorTy::Visit(E->getSubExpr());
4194
4195 case CK_LValueToRValue: {
4196 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004197 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4198 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004199 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004200 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004201 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004202 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004203 return false;
4204 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004205 }
4206 }
4207
Richard Smithf57d8cb2011-12-09 22:58:01 +00004208 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004209 }
4210
Aaron Ballman68af21c2014-01-03 19:26:43 +00004211 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004212 return VisitUnaryPostIncDec(UO);
4213 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004214 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004215 return VisitUnaryPostIncDec(UO);
4216 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004217 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004218 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004219 return Error(UO);
4220
4221 LValue LVal;
4222 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4223 return false;
4224 APValue RVal;
4225 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4226 UO->isIncrementOp(), &RVal))
4227 return false;
4228 return DerivedSuccess(RVal, UO);
4229 }
4230
Aaron Ballman68af21c2014-01-03 19:26:43 +00004231 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004232 // We will have checked the full-expressions inside the statement expression
4233 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004234 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004235 return Error(E);
4236
Richard Smith08d6a2c2013-07-24 07:11:57 +00004237 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004238 const CompoundStmt *CS = E->getSubStmt();
4239 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4240 BE = CS->body_end();
4241 /**/; ++BI) {
4242 if (BI + 1 == BE) {
4243 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4244 if (!FinalExpr) {
4245 Info.Diag((*BI)->getLocStart(),
4246 diag::note_constexpr_stmt_expr_unsupported);
4247 return false;
4248 }
4249 return this->Visit(FinalExpr);
4250 }
4251
4252 APValue ReturnValue;
4253 EvalStmtResult ESR = EvaluateStmt(ReturnValue, Info, *BI);
4254 if (ESR != ESR_Succeeded) {
4255 // FIXME: If the statement-expression terminated due to 'return',
4256 // 'break', or 'continue', it would be nice to propagate that to
4257 // the outer statement evaluation rather than bailing out.
4258 if (ESR != ESR_Failed)
4259 Info.Diag((*BI)->getLocStart(),
4260 diag::note_constexpr_stmt_expr_unsupported);
4261 return false;
4262 }
4263 }
4264 }
4265
Richard Smith4a678122011-10-24 18:44:57 +00004266 /// Visit a value which is evaluated, but whose value is ignored.
4267 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004268 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004269 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004270};
4271
4272}
4273
4274//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004275// Common base class for lvalue and temporary evaluation.
4276//===----------------------------------------------------------------------===//
4277namespace {
4278template<class Derived>
4279class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004280 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004281protected:
4282 LValue &Result;
4283 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004284 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004285
4286 bool Success(APValue::LValueBase B) {
4287 Result.set(B);
4288 return true;
4289 }
4290
4291public:
4292 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4293 ExprEvaluatorBaseTy(Info), Result(Result) {}
4294
Richard Smith2e312c82012-03-03 22:46:17 +00004295 bool Success(const APValue &V, const Expr *E) {
4296 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004297 return true;
4298 }
Richard Smith027bf112011-11-17 22:56:20 +00004299
Richard Smith027bf112011-11-17 22:56:20 +00004300 bool VisitMemberExpr(const MemberExpr *E) {
4301 // Handle non-static data members.
4302 QualType BaseTy;
4303 if (E->isArrow()) {
4304 if (!EvaluatePointer(E->getBase(), Result, this->Info))
4305 return false;
Ted Kremenek28831752012-08-23 20:46:57 +00004306 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004307 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004308 assert(E->getBase()->getType()->isRecordType());
Richard Smith357362d2011-12-13 06:39:58 +00004309 if (!EvaluateTemporary(E->getBase(), Result, this->Info))
4310 return false;
4311 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004312 } else {
4313 if (!this->Visit(E->getBase()))
4314 return false;
4315 BaseTy = E->getBase()->getType();
4316 }
Richard Smith027bf112011-11-17 22:56:20 +00004317
Richard Smith1b78b3d2012-01-25 22:15:11 +00004318 const ValueDecl *MD = E->getMemberDecl();
4319 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4320 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4321 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4322 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004323 if (!HandleLValueMember(this->Info, E, Result, FD))
4324 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004325 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004326 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4327 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004328 } else
4329 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004330
Richard Smith1b78b3d2012-01-25 22:15:11 +00004331 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004332 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004333 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004334 RefValue))
4335 return false;
4336 return Success(RefValue, E);
4337 }
4338 return true;
4339 }
4340
4341 bool VisitBinaryOperator(const BinaryOperator *E) {
4342 switch (E->getOpcode()) {
4343 default:
4344 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4345
4346 case BO_PtrMemD:
4347 case BO_PtrMemI:
4348 return HandleMemberPointerAccess(this->Info, E, Result);
4349 }
4350 }
4351
4352 bool VisitCastExpr(const CastExpr *E) {
4353 switch (E->getCastKind()) {
4354 default:
4355 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4356
4357 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004358 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004359 if (!this->Visit(E->getSubExpr()))
4360 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004361
4362 // Now figure out the necessary offset to add to the base LV to get from
4363 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004364 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4365 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004366 }
4367 }
4368};
4369}
4370
4371//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004372// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004373//
4374// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4375// function designators (in C), decl references to void objects (in C), and
4376// temporaries (if building with -Wno-address-of-temporary).
4377//
4378// LValue evaluation produces values comprising a base expression of one of the
4379// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004380// - Declarations
4381// * VarDecl
4382// * FunctionDecl
4383// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004384// * CompoundLiteralExpr in C
4385// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004386// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004387// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004388// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004389// * ObjCEncodeExpr
4390// * AddrLabelExpr
4391// * BlockExpr
4392// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004393// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004394// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004395// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004396// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4397// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004398// * A MaterializeTemporaryExpr that has static storage duration, with no
4399// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004400// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004401//===----------------------------------------------------------------------===//
4402namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004403class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004404 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004405public:
Richard Smith027bf112011-11-17 22:56:20 +00004406 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4407 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004408
Richard Smith11562c52011-10-28 17:51:58 +00004409 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004410 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004411
Peter Collingbournee9200682011-05-13 03:29:01 +00004412 bool VisitDeclRefExpr(const DeclRefExpr *E);
4413 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004414 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004415 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4416 bool VisitMemberExpr(const MemberExpr *E);
4417 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4418 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004419 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004420 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004421 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4422 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004423 bool VisitUnaryReal(const UnaryOperator *E);
4424 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004425 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4426 return VisitUnaryPreIncDec(UO);
4427 }
4428 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4429 return VisitUnaryPreIncDec(UO);
4430 }
Richard Smith3229b742013-05-05 21:17:10 +00004431 bool VisitBinAssign(const BinaryOperator *BO);
4432 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004433
Peter Collingbournee9200682011-05-13 03:29:01 +00004434 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004435 switch (E->getCastKind()) {
4436 default:
Richard Smith027bf112011-11-17 22:56:20 +00004437 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004438
Eli Friedmance3e02a2011-10-11 00:13:24 +00004439 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004440 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004441 if (!Visit(E->getSubExpr()))
4442 return false;
4443 Result.Designator.setInvalid();
4444 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004445
Richard Smith027bf112011-11-17 22:56:20 +00004446 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004447 if (!Visit(E->getSubExpr()))
4448 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004449 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004450 }
4451 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004452};
4453} // end anonymous namespace
4454
Richard Smith11562c52011-10-28 17:51:58 +00004455/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004456/// expressions which are not glvalues, in two cases:
4457/// * function designators in C, and
4458/// * "extern void" objects
4459static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4460 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4461 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004462 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004463}
4464
Peter Collingbournee9200682011-05-13 03:29:01 +00004465bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004466 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004467 return Success(FD);
4468 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004469 return VisitVarDecl(E, VD);
4470 return Error(E);
4471}
Richard Smith733237d2011-10-24 23:14:33 +00004472
Richard Smith11562c52011-10-28 17:51:58 +00004473bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004474 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004475 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4476 Frame = Info.CurrentCall;
4477
Richard Smithfec09922011-11-01 16:57:24 +00004478 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004479 if (Frame) {
4480 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004481 return true;
4482 }
Richard Smithce40ad62011-11-12 22:28:03 +00004483 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004484 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004485
Richard Smith3229b742013-05-05 21:17:10 +00004486 APValue *V;
4487 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004488 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004489 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004490 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004491 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4492 return false;
4493 }
Richard Smith3229b742013-05-05 21:17:10 +00004494 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004495}
4496
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004497bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4498 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004499 // Walk through the expression to find the materialized temporary itself.
4500 SmallVector<const Expr *, 2> CommaLHSs;
4501 SmallVector<SubobjectAdjustment, 2> Adjustments;
4502 const Expr *Inner = E->GetTemporaryExpr()->
4503 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004504
Richard Smith84401042013-06-03 05:03:02 +00004505 // If we passed any comma operators, evaluate their LHSs.
4506 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4507 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4508 return false;
4509
Richard Smithe6c01442013-06-05 00:46:14 +00004510 // A materialized temporary with static storage duration can appear within the
4511 // result of a constant expression evaluation, so we need to preserve its
4512 // value for use outside this evaluation.
4513 APValue *Value;
4514 if (E->getStorageDuration() == SD_Static) {
4515 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004516 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004517 Result.set(E);
4518 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004519 Value = &Info.CurrentCall->
4520 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004521 Result.set(E, Info.CurrentCall->Index);
4522 }
4523
Richard Smithea4ad5d2013-06-06 08:19:16 +00004524 QualType Type = Inner->getType();
4525
Richard Smith84401042013-06-03 05:03:02 +00004526 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004527 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4528 (E->getStorageDuration() == SD_Static &&
4529 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4530 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004531 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004532 }
Richard Smith84401042013-06-03 05:03:02 +00004533
4534 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004535 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4536 --I;
4537 switch (Adjustments[I].Kind) {
4538 case SubobjectAdjustment::DerivedToBaseAdjustment:
4539 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4540 Type, Result))
4541 return false;
4542 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4543 break;
4544
4545 case SubobjectAdjustment::FieldAdjustment:
4546 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4547 return false;
4548 Type = Adjustments[I].Field->getType();
4549 break;
4550
4551 case SubobjectAdjustment::MemberPointerAdjustment:
4552 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4553 Adjustments[I].Ptr.RHS))
4554 return false;
4555 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4556 break;
4557 }
4558 }
4559
4560 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004561}
4562
Peter Collingbournee9200682011-05-13 03:29:01 +00004563bool
4564LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004565 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4566 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4567 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004568 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004569}
4570
Richard Smith6e525142011-12-27 12:18:28 +00004571bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004572 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004573 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004574
4575 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4576 << E->getExprOperand()->getType()
4577 << E->getExprOperand()->getSourceRange();
4578 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004579}
4580
Francois Pichet0066db92012-04-16 04:08:35 +00004581bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4582 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004583}
Francois Pichet0066db92012-04-16 04:08:35 +00004584
Peter Collingbournee9200682011-05-13 03:29:01 +00004585bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004586 // Handle static data members.
4587 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4588 VisitIgnoredValue(E->getBase());
4589 return VisitVarDecl(E, VD);
4590 }
4591
Richard Smith254a73d2011-10-28 22:34:42 +00004592 // Handle static member functions.
4593 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4594 if (MD->isStatic()) {
4595 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004596 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004597 }
4598 }
4599
Richard Smithd62306a2011-11-10 06:34:14 +00004600 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004601 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004602}
4603
Peter Collingbournee9200682011-05-13 03:29:01 +00004604bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004605 // FIXME: Deal with vectors as array subscript bases.
4606 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004607 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004608
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004609 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004610 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004611
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004612 APSInt Index;
4613 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004614 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004615
Richard Smith861b5b52013-05-07 23:34:45 +00004616 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4617 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004618}
Eli Friedman9a156e52008-11-12 09:44:48 +00004619
Peter Collingbournee9200682011-05-13 03:29:01 +00004620bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004621 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004622}
4623
Richard Smith66c96992012-02-18 22:04:06 +00004624bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4625 if (!Visit(E->getSubExpr()))
4626 return false;
4627 // __real is a no-op on scalar lvalues.
4628 if (E->getSubExpr()->getType()->isAnyComplexType())
4629 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4630 return true;
4631}
4632
4633bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4634 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4635 "lvalue __imag__ on scalar?");
4636 if (!Visit(E->getSubExpr()))
4637 return false;
4638 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4639 return true;
4640}
4641
Richard Smith243ef902013-05-05 23:31:59 +00004642bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004643 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004644 return Error(UO);
4645
4646 if (!this->Visit(UO->getSubExpr()))
4647 return false;
4648
Richard Smith243ef902013-05-05 23:31:59 +00004649 return handleIncDec(
4650 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004651 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004652}
4653
4654bool LValueExprEvaluator::VisitCompoundAssignOperator(
4655 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004656 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004657 return Error(CAO);
4658
Richard Smith3229b742013-05-05 21:17:10 +00004659 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004660
4661 // The overall lvalue result is the result of evaluating the LHS.
4662 if (!this->Visit(CAO->getLHS())) {
4663 if (Info.keepEvaluatingAfterFailure())
4664 Evaluate(RHS, this->Info, CAO->getRHS());
4665 return false;
4666 }
4667
Richard Smith3229b742013-05-05 21:17:10 +00004668 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4669 return false;
4670
Richard Smith43e77732013-05-07 04:50:00 +00004671 return handleCompoundAssignment(
4672 this->Info, CAO,
4673 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4674 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004675}
4676
4677bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004678 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004679 return Error(E);
4680
Richard Smith3229b742013-05-05 21:17:10 +00004681 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004682
4683 if (!this->Visit(E->getLHS())) {
4684 if (Info.keepEvaluatingAfterFailure())
4685 Evaluate(NewVal, this->Info, E->getRHS());
4686 return false;
4687 }
4688
Richard Smith3229b742013-05-05 21:17:10 +00004689 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4690 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004691
4692 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004693 NewVal);
4694}
4695
Eli Friedman9a156e52008-11-12 09:44:48 +00004696//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004697// Pointer Evaluation
4698//===----------------------------------------------------------------------===//
4699
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004700namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004701class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004702 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004703 LValue &Result;
4704
Peter Collingbournee9200682011-05-13 03:29:01 +00004705 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004706 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004707 return true;
4708 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004709public:
Mike Stump11289f42009-09-09 15:08:12 +00004710
John McCall45d55e42010-05-07 21:00:08 +00004711 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004712 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004713
Richard Smith2e312c82012-03-03 22:46:17 +00004714 bool Success(const APValue &V, const Expr *E) {
4715 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004716 return true;
4717 }
Richard Smithfddd3842011-12-30 21:15:51 +00004718 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004719 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004720 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004721
John McCall45d55e42010-05-07 21:00:08 +00004722 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004723 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004724 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004725 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004726 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004727 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Ted Kremeneke65b0862012-03-06 20:05:56 +00004728 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004729 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004730 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004731 bool VisitCallExpr(const CallExpr *E);
4732 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004733 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004734 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004735 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004736 }
Richard Smithd62306a2011-11-10 06:34:14 +00004737 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004738 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004739 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004740 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00004741 if (!Info.CurrentCall->This) {
4742 if (Info.getLangOpts().CPlusPlus11)
4743 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4744 else
4745 Info.Diag(E);
4746 return false;
4747 }
Richard Smithd62306a2011-11-10 06:34:14 +00004748 Result = *Info.CurrentCall->This;
4749 return true;
4750 }
John McCallc07a0c72011-02-17 10:25:35 +00004751
Eli Friedman449fe542009-03-23 04:56:01 +00004752 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004753};
Chris Lattner05706e882008-07-11 18:11:29 +00004754} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004755
John McCall45d55e42010-05-07 21:00:08 +00004756static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004757 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004758 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004759}
4760
John McCall45d55e42010-05-07 21:00:08 +00004761bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004762 if (E->getOpcode() != BO_Add &&
4763 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004764 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004765
Chris Lattner05706e882008-07-11 18:11:29 +00004766 const Expr *PExp = E->getLHS();
4767 const Expr *IExp = E->getRHS();
4768 if (IExp->getType()->isPointerType())
4769 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004770
Richard Smith253c2a32012-01-27 01:14:48 +00004771 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4772 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004773 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004774
John McCall45d55e42010-05-07 21:00:08 +00004775 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004776 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004777 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004778
4779 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004780 if (E->getOpcode() == BO_Sub)
4781 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004782
Ted Kremenek28831752012-08-23 20:46:57 +00004783 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004784 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4785 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004786}
Eli Friedman9a156e52008-11-12 09:44:48 +00004787
John McCall45d55e42010-05-07 21:00:08 +00004788bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4789 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004790}
Mike Stump11289f42009-09-09 15:08:12 +00004791
Peter Collingbournee9200682011-05-13 03:29:01 +00004792bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4793 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004794
Eli Friedman847a2bc2009-12-27 05:43:15 +00004795 switch (E->getCastKind()) {
4796 default:
4797 break;
4798
John McCalle3027922010-08-25 11:45:40 +00004799 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004800 case CK_CPointerToObjCPointerCast:
4801 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004802 case CK_AnyPointerToBlockPointerCast:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004803 if (!Visit(SubExpr))
4804 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004805 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4806 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4807 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004808 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004809 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004810 if (SubExpr->getType()->isVoidPointerType())
4811 CCEDiag(E, diag::note_constexpr_invalid_cast)
4812 << 3 << SubExpr->getType();
4813 else
4814 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4815 }
Richard Smith96e0c102011-11-04 02:25:55 +00004816 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004817
Anders Carlsson18275092010-10-31 20:41:46 +00004818 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004819 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004820 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004821 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004822 if (!Result.Base && Result.Offset.isZero())
4823 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004824
Richard Smithd62306a2011-11-10 06:34:14 +00004825 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004826 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004827 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4828 castAs<PointerType>()->getPointeeType(),
4829 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004830
Richard Smith027bf112011-11-17 22:56:20 +00004831 case CK_BaseToDerived:
4832 if (!Visit(E->getSubExpr()))
4833 return false;
4834 if (!Result.Base && Result.Offset.isZero())
4835 return true;
4836 return HandleBaseToDerivedCast(Info, E, Result);
4837
Richard Smith0b0a0b62011-10-29 20:57:55 +00004838 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004839 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004840 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004841
John McCalle3027922010-08-25 11:45:40 +00004842 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004843 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4844
Richard Smith2e312c82012-03-03 22:46:17 +00004845 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004846 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004847 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004848
John McCall45d55e42010-05-07 21:00:08 +00004849 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004850 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4851 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00004852 Result.Base = (Expr*)nullptr;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004853 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004854 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004855 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004856 return true;
4857 } else {
4858 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004859 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004860 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004861 }
4862 }
John McCalle3027922010-08-25 11:45:40 +00004863 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004864 if (SubExpr->isGLValue()) {
4865 if (!EvaluateLValue(SubExpr, Result, Info))
4866 return false;
4867 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004868 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004869 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004870 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004871 return false;
4872 }
Richard Smith96e0c102011-11-04 02:25:55 +00004873 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004874 if (const ConstantArrayType *CAT
4875 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4876 Result.addArray(Info, E, CAT);
4877 else
4878 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004879 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004880
John McCalle3027922010-08-25 11:45:40 +00004881 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004882 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004883 }
4884
Richard Smith11562c52011-10-28 17:51:58 +00004885 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004886}
Chris Lattner05706e882008-07-11 18:11:29 +00004887
Peter Collingbournee9200682011-05-13 03:29:01 +00004888bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004889 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00004890 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00004891
Alp Tokera724cff2013-12-28 21:59:02 +00004892 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00004893 case Builtin::BI__builtin_addressof:
4894 return EvaluateLValue(E->getArg(0), Result, Info);
4895
4896 default:
4897 return ExprEvaluatorBaseTy::VisitCallExpr(E);
4898 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004899}
Chris Lattner05706e882008-07-11 18:11:29 +00004900
4901//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004902// Member Pointer Evaluation
4903//===----------------------------------------------------------------------===//
4904
4905namespace {
4906class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004907 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00004908 MemberPtr &Result;
4909
4910 bool Success(const ValueDecl *D) {
4911 Result = MemberPtr(D);
4912 return true;
4913 }
4914public:
4915
4916 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
4917 : ExprEvaluatorBaseTy(Info), Result(Result) {}
4918
Richard Smith2e312c82012-03-03 22:46:17 +00004919 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004920 Result.setFrom(V);
4921 return true;
4922 }
Richard Smithfddd3842011-12-30 21:15:51 +00004923 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004924 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00004925 }
4926
4927 bool VisitCastExpr(const CastExpr *E);
4928 bool VisitUnaryAddrOf(const UnaryOperator *E);
4929};
4930} // end anonymous namespace
4931
4932static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
4933 EvalInfo &Info) {
4934 assert(E->isRValue() && E->getType()->isMemberPointerType());
4935 return MemberPointerExprEvaluator(Info, Result).Visit(E);
4936}
4937
4938bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
4939 switch (E->getCastKind()) {
4940 default:
4941 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4942
4943 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004944 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004945 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004946
4947 case CK_BaseToDerivedMemberPointer: {
4948 if (!Visit(E->getSubExpr()))
4949 return false;
4950 if (E->path_empty())
4951 return true;
4952 // Base-to-derived member pointer casts store the path in derived-to-base
4953 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
4954 // the wrong end of the derived->base arc, so stagger the path by one class.
4955 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
4956 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
4957 PathI != PathE; ++PathI) {
4958 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4959 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
4960 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004961 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004962 }
4963 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
4964 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004965 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004966 return true;
4967 }
4968
4969 case CK_DerivedToBaseMemberPointer:
4970 if (!Visit(E->getSubExpr()))
4971 return false;
4972 for (CastExpr::path_const_iterator PathI = E->path_begin(),
4973 PathE = E->path_end(); PathI != PathE; ++PathI) {
4974 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
4975 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
4976 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004977 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004978 }
4979 return true;
4980 }
4981}
4982
4983bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4984 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
4985 // member can be formed.
4986 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
4987}
4988
4989//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00004990// Record Evaluation
4991//===----------------------------------------------------------------------===//
4992
4993namespace {
4994 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004995 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00004996 const LValue &This;
4997 APValue &Result;
4998 public:
4999
5000 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5001 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5002
Richard Smith2e312c82012-03-03 22:46:17 +00005003 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005004 Result = V;
5005 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005006 }
Richard Smithfddd3842011-12-30 21:15:51 +00005007 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005008
Richard Smithe97cbd72011-11-11 04:05:33 +00005009 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005010 bool VisitInitListExpr(const InitListExpr *E);
5011 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005012 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005013 };
5014}
5015
Richard Smithfddd3842011-12-30 21:15:51 +00005016/// Perform zero-initialization on an object of non-union class type.
5017/// C++11 [dcl.init]p5:
5018/// To zero-initialize an object or reference of type T means:
5019/// [...]
5020/// -- if T is a (possibly cv-qualified) non-union class type,
5021/// each non-static data member and each base-class subobject is
5022/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005023static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5024 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005025 const LValue &This, APValue &Result) {
5026 assert(!RD->isUnion() && "Expected non-union class type");
5027 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5028 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005029 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005030
John McCalld7bca762012-05-01 00:38:49 +00005031 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005032 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5033
5034 if (CD) {
5035 unsigned Index = 0;
5036 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005037 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005038 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5039 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005040 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5041 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005042 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005043 Result.getStructBase(Index)))
5044 return false;
5045 }
5046 }
5047
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005048 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005049 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005050 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005051 continue;
5052
5053 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005054 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005055 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005056
David Blaikie2d7c57e2012-04-30 02:36:29 +00005057 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005058 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005059 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005060 return false;
5061 }
5062
5063 return true;
5064}
5065
5066bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
5067 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005068 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005069 if (RD->isUnion()) {
5070 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5071 // object's first non-static named data member is zero-initialized
5072 RecordDecl::field_iterator I = RD->field_begin();
5073 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005074 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005075 return true;
5076 }
5077
5078 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005079 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005080 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005081 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005082 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005083 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005084 }
5085
Richard Smith5d108602012-02-17 00:44:16 +00005086 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005087 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005088 return false;
5089 }
5090
Richard Smitha8105bc2012-01-06 16:39:00 +00005091 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005092}
5093
Richard Smithe97cbd72011-11-11 04:05:33 +00005094bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5095 switch (E->getCastKind()) {
5096 default:
5097 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5098
5099 case CK_ConstructorConversion:
5100 return Visit(E->getSubExpr());
5101
5102 case CK_DerivedToBase:
5103 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005104 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005105 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005106 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005107 if (!DerivedObject.isStruct())
5108 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005109
5110 // Derived-to-base rvalue conversion: just slice off the derived part.
5111 APValue *Value = &DerivedObject;
5112 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5113 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5114 PathE = E->path_end(); PathI != PathE; ++PathI) {
5115 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5116 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5117 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5118 RD = Base;
5119 }
5120 Result = *Value;
5121 return true;
5122 }
5123 }
5124}
5125
Richard Smithd62306a2011-11-10 06:34:14 +00005126bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5127 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005128 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005129 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5130
5131 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005132 const FieldDecl *Field = E->getInitializedFieldInUnion();
5133 Result = APValue(Field);
5134 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005135 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005136
5137 // If the initializer list for a union does not contain any elements, the
5138 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005139 // FIXME: The element should be initialized from an initializer list.
5140 // Is this difference ever observable for initializer lists which
5141 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005142 ImplicitValueInitExpr VIE(Field->getType());
5143 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5144
Richard Smithd62306a2011-11-10 06:34:14 +00005145 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005146 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5147 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005148
5149 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5150 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5151 isa<CXXDefaultInitExpr>(InitExpr));
5152
Richard Smithb228a862012-02-15 02:18:13 +00005153 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005154 }
5155
5156 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5157 "initializer list for class with base classes");
Aaron Ballman62e47c42014-03-10 13:43:55 +00005158 Result = APValue(APValue::UninitStruct(), 0,
5159 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005160 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005161 bool Success = true;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005162 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005163 // Anonymous bit-fields are not considered members of the class for
5164 // purposes of aggregate initialization.
5165 if (Field->isUnnamedBitfield())
5166 continue;
5167
5168 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005169
Richard Smith253c2a32012-01-27 01:14:48 +00005170 bool HaveInit = ElementNo < E->getNumInits();
5171
5172 // FIXME: Diagnostics here should point to the end of the initializer
5173 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005174 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005175 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005176 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005177
5178 // Perform an implicit value-initialization for members beyond the end of
5179 // the initializer list.
5180 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005181 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005182
Richard Smith852c9db2013-04-20 22:23:05 +00005183 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5184 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5185 isa<CXXDefaultInitExpr>(Init));
5186
Richard Smith49ca8aa2013-08-06 07:09:20 +00005187 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5188 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5189 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005190 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005191 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005192 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005193 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005194 }
5195 }
5196
Richard Smith253c2a32012-01-27 01:14:48 +00005197 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005198}
5199
5200bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5201 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005202 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5203
Richard Smithfddd3842011-12-30 21:15:51 +00005204 bool ZeroInit = E->requiresZeroInitialization();
5205 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005206 // If we've already performed zero-initialization, we're already done.
5207 if (!Result.isUninit())
5208 return true;
5209
Richard Smithda3f4fd2014-03-05 23:32:50 +00005210 // We can get here in two different ways:
5211 // 1) We're performing value-initialization, and should zero-initialize
5212 // the object, or
5213 // 2) We're performing default-initialization of an object with a trivial
5214 // constexpr default constructor, in which case we should start the
5215 // lifetimes of all the base subobjects (there can be no data member
5216 // subobjects in this case) per [basic.life]p1.
5217 // Either way, ZeroInitialization is appropriate.
5218 return ZeroInitialization(E);
Richard Smithcc36f692011-12-22 02:22:31 +00005219 }
5220
Craig Topper36250ad2014-05-12 05:36:57 +00005221 const FunctionDecl *Definition = nullptr;
Richard Smithd62306a2011-11-10 06:34:14 +00005222 FD->getBody(Definition);
5223
Richard Smith357362d2011-12-13 06:39:58 +00005224 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5225 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005226
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005227 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005228 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005229 if (const MaterializeTemporaryExpr *ME
5230 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5231 return Visit(ME->GetTemporaryExpr());
5232
Richard Smithfddd3842011-12-30 21:15:51 +00005233 if (ZeroInit && !ZeroInitialization(E))
5234 return false;
5235
Craig Topper5fc8fc22014-08-27 06:28:36 +00005236 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005237 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005238 cast<CXXConstructorDecl>(Definition), Info,
5239 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005240}
5241
Richard Smithcc1b96d2013-06-12 22:31:48 +00005242bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5243 const CXXStdInitializerListExpr *E) {
5244 const ConstantArrayType *ArrayType =
5245 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5246
5247 LValue Array;
5248 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5249 return false;
5250
5251 // Get a pointer to the first element of the array.
5252 Array.addArray(Info, E, ArrayType);
5253
5254 // FIXME: Perform the checks on the field types in SemaInit.
5255 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5256 RecordDecl::field_iterator Field = Record->field_begin();
5257 if (Field == Record->field_end())
5258 return Error(E);
5259
5260 // Start pointer.
5261 if (!Field->getType()->isPointerType() ||
5262 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5263 ArrayType->getElementType()))
5264 return Error(E);
5265
5266 // FIXME: What if the initializer_list type has base classes, etc?
5267 Result = APValue(APValue::UninitStruct(), 0, 2);
5268 Array.moveInto(Result.getStructField(0));
5269
5270 if (++Field == Record->field_end())
5271 return Error(E);
5272
5273 if (Field->getType()->isPointerType() &&
5274 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5275 ArrayType->getElementType())) {
5276 // End pointer.
5277 if (!HandleLValueArrayAdjustment(Info, E, Array,
5278 ArrayType->getElementType(),
5279 ArrayType->getSize().getZExtValue()))
5280 return false;
5281 Array.moveInto(Result.getStructField(1));
5282 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5283 // Length.
5284 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5285 else
5286 return Error(E);
5287
5288 if (++Field != Record->field_end())
5289 return Error(E);
5290
5291 return true;
5292}
5293
Richard Smithd62306a2011-11-10 06:34:14 +00005294static bool EvaluateRecord(const Expr *E, const LValue &This,
5295 APValue &Result, EvalInfo &Info) {
5296 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005297 "can't evaluate expression as a record rvalue");
5298 return RecordExprEvaluator(Info, This, Result).Visit(E);
5299}
5300
5301//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005302// Temporary Evaluation
5303//
5304// Temporaries are represented in the AST as rvalues, but generally behave like
5305// lvalues. The full-object of which the temporary is a subobject is implicitly
5306// materialized so that a reference can bind to it.
5307//===----------------------------------------------------------------------===//
5308namespace {
5309class TemporaryExprEvaluator
5310 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5311public:
5312 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5313 LValueExprEvaluatorBaseTy(Info, Result) {}
5314
5315 /// Visit an expression which constructs the value of this temporary.
5316 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005317 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005318 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5319 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005320 }
5321
5322 bool VisitCastExpr(const CastExpr *E) {
5323 switch (E->getCastKind()) {
5324 default:
5325 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5326
5327 case CK_ConstructorConversion:
5328 return VisitConstructExpr(E->getSubExpr());
5329 }
5330 }
5331 bool VisitInitListExpr(const InitListExpr *E) {
5332 return VisitConstructExpr(E);
5333 }
5334 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5335 return VisitConstructExpr(E);
5336 }
5337 bool VisitCallExpr(const CallExpr *E) {
5338 return VisitConstructExpr(E);
5339 }
5340};
5341} // end anonymous namespace
5342
5343/// Evaluate an expression of record type as a temporary.
5344static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005345 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005346 return TemporaryExprEvaluator(Info, Result).Visit(E);
5347}
5348
5349//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005350// Vector Evaluation
5351//===----------------------------------------------------------------------===//
5352
5353namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005354 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005355 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005356 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005357 public:
Mike Stump11289f42009-09-09 15:08:12 +00005358
Richard Smith2d406342011-10-22 21:10:00 +00005359 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5360 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005361
Richard Smith2d406342011-10-22 21:10:00 +00005362 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5363 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5364 // FIXME: remove this APValue copy.
5365 Result = APValue(V.data(), V.size());
5366 return true;
5367 }
Richard Smith2e312c82012-03-03 22:46:17 +00005368 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005369 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005370 Result = V;
5371 return true;
5372 }
Richard Smithfddd3842011-12-30 21:15:51 +00005373 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005374
Richard Smith2d406342011-10-22 21:10:00 +00005375 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005376 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005377 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005378 bool VisitInitListExpr(const InitListExpr *E);
5379 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005380 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005381 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005382 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005383 };
5384} // end anonymous namespace
5385
5386static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005387 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005388 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005389}
5390
Richard Smith2d406342011-10-22 21:10:00 +00005391bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5392 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005393 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005394
Richard Smith161f09a2011-12-06 22:44:34 +00005395 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005396 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005397
Eli Friedmanc757de22011-03-25 00:43:55 +00005398 switch (E->getCastKind()) {
5399 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005400 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005401 if (SETy->isIntegerType()) {
5402 APSInt IntResult;
5403 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005404 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005405 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005406 } else if (SETy->isRealFloatingType()) {
5407 APFloat F(0.0);
5408 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005409 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005410 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005411 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005412 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005413 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005414
5415 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005416 SmallVector<APValue, 4> Elts(NElts, Val);
5417 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005418 }
Eli Friedman803acb32011-12-22 03:51:45 +00005419 case CK_BitCast: {
5420 // Evaluate the operand into an APInt we can extract from.
5421 llvm::APInt SValInt;
5422 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5423 return false;
5424 // Extract the elements
5425 QualType EltTy = VTy->getElementType();
5426 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5427 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5428 SmallVector<APValue, 4> Elts;
5429 if (EltTy->isRealFloatingType()) {
5430 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005431 unsigned FloatEltSize = EltSize;
5432 if (&Sem == &APFloat::x87DoubleExtended)
5433 FloatEltSize = 80;
5434 for (unsigned i = 0; i < NElts; i++) {
5435 llvm::APInt Elt;
5436 if (BigEndian)
5437 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5438 else
5439 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005440 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005441 }
5442 } else if (EltTy->isIntegerType()) {
5443 for (unsigned i = 0; i < NElts; i++) {
5444 llvm::APInt Elt;
5445 if (BigEndian)
5446 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5447 else
5448 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5449 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5450 }
5451 } else {
5452 return Error(E);
5453 }
5454 return Success(Elts, E);
5455 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005456 default:
Richard Smith11562c52011-10-28 17:51:58 +00005457 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005458 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005459}
5460
Richard Smith2d406342011-10-22 21:10:00 +00005461bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005462VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005463 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005464 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005465 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005466
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005467 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005468 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005469
Eli Friedmanb9c71292012-01-03 23:24:20 +00005470 // The number of initializers can be less than the number of
5471 // vector elements. For OpenCL, this can be due to nested vector
5472 // initialization. For GCC compatibility, missing trailing elements
5473 // should be initialized with zeroes.
5474 unsigned CountInits = 0, CountElts = 0;
5475 while (CountElts < NumElements) {
5476 // Handle nested vector initialization.
5477 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005478 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005479 APValue v;
5480 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5481 return Error(E);
5482 unsigned vlen = v.getVectorLength();
5483 for (unsigned j = 0; j < vlen; j++)
5484 Elements.push_back(v.getVectorElt(j));
5485 CountElts += vlen;
5486 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005487 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005488 if (CountInits < NumInits) {
5489 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005490 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005491 } else // trailing integer zero.
5492 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5493 Elements.push_back(APValue(sInt));
5494 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005495 } else {
5496 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005497 if (CountInits < NumInits) {
5498 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005499 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005500 } else // trailing float zero.
5501 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5502 Elements.push_back(APValue(f));
5503 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005504 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005505 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005506 }
Richard Smith2d406342011-10-22 21:10:00 +00005507 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005508}
5509
Richard Smith2d406342011-10-22 21:10:00 +00005510bool
Richard Smithfddd3842011-12-30 21:15:51 +00005511VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005512 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005513 QualType EltTy = VT->getElementType();
5514 APValue ZeroElement;
5515 if (EltTy->isIntegerType())
5516 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5517 else
5518 ZeroElement =
5519 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5520
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005521 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005522 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005523}
5524
Richard Smith2d406342011-10-22 21:10:00 +00005525bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005526 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005527 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005528}
5529
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005530//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005531// Array Evaluation
5532//===----------------------------------------------------------------------===//
5533
5534namespace {
5535 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005536 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005537 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005538 APValue &Result;
5539 public:
5540
Richard Smithd62306a2011-11-10 06:34:14 +00005541 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5542 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005543
5544 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005545 assert((V.isArray() || V.isLValue()) &&
5546 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005547 Result = V;
5548 return true;
5549 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005550
Richard Smithfddd3842011-12-30 21:15:51 +00005551 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005552 const ConstantArrayType *CAT =
5553 Info.Ctx.getAsConstantArrayType(E->getType());
5554 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005555 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005556
5557 Result = APValue(APValue::UninitArray(), 0,
5558 CAT->getSize().getZExtValue());
5559 if (!Result.hasArrayFiller()) return true;
5560
Richard Smithfddd3842011-12-30 21:15:51 +00005561 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005562 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005563 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005564 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005565 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005566 }
5567
Richard Smithf3e9e432011-11-07 09:22:26 +00005568 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005569 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005570 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5571 const LValue &Subobject,
5572 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005573 };
5574} // end anonymous namespace
5575
Richard Smithd62306a2011-11-10 06:34:14 +00005576static bool EvaluateArray(const Expr *E, const LValue &This,
5577 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005578 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005579 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005580}
5581
5582bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5583 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5584 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005585 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005586
Richard Smithca2cfbf2011-12-22 01:07:19 +00005587 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5588 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005589 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005590 LValue LV;
5591 if (!EvaluateLValue(E->getInit(0), LV, Info))
5592 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005593 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005594 LV.moveInto(Val);
5595 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005596 }
5597
Richard Smith253c2a32012-01-27 01:14:48 +00005598 bool Success = true;
5599
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005600 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5601 "zero-initialized array shouldn't have any initialized elts");
5602 APValue Filler;
5603 if (Result.isArray() && Result.hasArrayFiller())
5604 Filler = Result.getArrayFiller();
5605
Richard Smith9543c5e2013-04-22 14:44:29 +00005606 unsigned NumEltsToInit = E->getNumInits();
5607 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005608 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00005609
5610 // If the initializer might depend on the array index, run it for each
5611 // array element. For now, just whitelist non-class value-initialization.
5612 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5613 NumEltsToInit = NumElts;
5614
5615 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005616
5617 // If the array was previously zero-initialized, preserve the
5618 // zero-initialized values.
5619 if (!Filler.isUninit()) {
5620 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5621 Result.getArrayInitializedElt(I) = Filler;
5622 if (Result.hasArrayFiller())
5623 Result.getArrayFiller() = Filler;
5624 }
5625
Richard Smithd62306a2011-11-10 06:34:14 +00005626 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005627 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005628 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5629 const Expr *Init =
5630 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005631 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005632 Info, Subobject, Init) ||
5633 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005634 CAT->getElementType(), 1)) {
5635 if (!Info.keepEvaluatingAfterFailure())
5636 return false;
5637 Success = false;
5638 }
Richard Smithd62306a2011-11-10 06:34:14 +00005639 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005640
Richard Smith9543c5e2013-04-22 14:44:29 +00005641 if (!Result.hasArrayFiller())
5642 return Success;
5643
5644 // If we get here, we have a trivial filler, which we can just evaluate
5645 // once and splat over the rest of the array elements.
5646 assert(FillerExpr && "no array filler for incomplete init list");
5647 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5648 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005649}
5650
Richard Smith027bf112011-11-17 22:56:20 +00005651bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005652 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5653}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005654
Richard Smith9543c5e2013-04-22 14:44:29 +00005655bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5656 const LValue &Subobject,
5657 APValue *Value,
5658 QualType Type) {
5659 bool HadZeroInit = !Value->isUninit();
5660
5661 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5662 unsigned N = CAT->getSize().getZExtValue();
5663
5664 // Preserve the array filler if we had prior zero-initialization.
5665 APValue Filler =
5666 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5667 : APValue();
5668
5669 *Value = APValue(APValue::UninitArray(), N, N);
5670
5671 if (HadZeroInit)
5672 for (unsigned I = 0; I != N; ++I)
5673 Value->getArrayInitializedElt(I) = Filler;
5674
5675 // Initialize the elements.
5676 LValue ArrayElt = Subobject;
5677 ArrayElt.addArray(Info, E, CAT);
5678 for (unsigned I = 0; I != N; ++I)
5679 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5680 CAT->getElementType()) ||
5681 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5682 CAT->getElementType(), 1))
5683 return false;
5684
5685 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005686 }
Richard Smith027bf112011-11-17 22:56:20 +00005687
Richard Smith9543c5e2013-04-22 14:44:29 +00005688 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005689 return Error(E);
5690
Richard Smith027bf112011-11-17 22:56:20 +00005691 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005692
Richard Smithfddd3842011-12-30 21:15:51 +00005693 bool ZeroInit = E->requiresZeroInitialization();
5694 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005695 if (HadZeroInit)
5696 return true;
5697
Richard Smithda3f4fd2014-03-05 23:32:50 +00005698 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5699 ImplicitValueInitExpr VIE(Type);
5700 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithcc36f692011-12-22 02:22:31 +00005701 }
5702
Craig Topper36250ad2014-05-12 05:36:57 +00005703 const FunctionDecl *Definition = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005704 FD->getBody(Definition);
5705
Richard Smith357362d2011-12-13 06:39:58 +00005706 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5707 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005708
Richard Smith9eae7232012-01-12 18:54:33 +00005709 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005710 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005711 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005712 return false;
5713 }
5714
Craig Topper5fc8fc22014-08-27 06:28:36 +00005715 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005716 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005717 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005718 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005719}
5720
Richard Smithf3e9e432011-11-07 09:22:26 +00005721//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005722// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005723//
5724// As a GNU extension, we support casting pointers to sufficiently-wide integer
5725// types and back in constant folding. Integer values are thus represented
5726// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005727//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005728
5729namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005730class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005731 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00005732 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005733public:
Richard Smith2e312c82012-03-03 22:46:17 +00005734 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005735 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005736
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005737 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005738 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005739 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005740 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005741 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005742 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005743 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005744 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005745 return true;
5746 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005747 bool Success(const llvm::APSInt &SI, const Expr *E) {
5748 return Success(SI, E, Result);
5749 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005750
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005751 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005752 assert(E->getType()->isIntegralOrEnumerationType() &&
5753 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005754 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005755 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005756 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005757 Result.getInt().setIsUnsigned(
5758 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005759 return true;
5760 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005761 bool Success(const llvm::APInt &I, const Expr *E) {
5762 return Success(I, E, Result);
5763 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005764
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005765 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005766 assert(E->getType()->isIntegralOrEnumerationType() &&
5767 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005768 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005769 return true;
5770 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005771 bool Success(uint64_t Value, const Expr *E) {
5772 return Success(Value, E, Result);
5773 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005774
Ken Dyckdbc01912011-03-11 02:13:43 +00005775 bool Success(CharUnits Size, const Expr *E) {
5776 return Success(Size.getQuantity(), E);
5777 }
5778
Richard Smith2e312c82012-03-03 22:46:17 +00005779 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005780 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005781 Result = V;
5782 return true;
5783 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005784 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005785 }
Mike Stump11289f42009-09-09 15:08:12 +00005786
Richard Smithfddd3842011-12-30 21:15:51 +00005787 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005788
Peter Collingbournee9200682011-05-13 03:29:01 +00005789 //===--------------------------------------------------------------------===//
5790 // Visitor Methods
5791 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005792
Chris Lattner7174bf32008-07-12 00:38:25 +00005793 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005794 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005795 }
5796 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005797 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00005798 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005799
5800 bool CheckReferencedDecl(const Expr *E, const Decl *D);
5801 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00005802 if (CheckReferencedDecl(E, E->getDecl()))
5803 return true;
5804
5805 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005806 }
5807 bool VisitMemberExpr(const MemberExpr *E) {
5808 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00005809 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005810 return true;
5811 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005812
5813 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005814 }
5815
Peter Collingbournee9200682011-05-13 03:29:01 +00005816 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005817 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00005818 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00005819 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00005820
Peter Collingbournee9200682011-05-13 03:29:01 +00005821 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00005822 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00005823
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005824 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005825 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005826 }
Mike Stump11289f42009-09-09 15:08:12 +00005827
Ted Kremeneke65b0862012-03-06 20:05:56 +00005828 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
5829 return Success(E->getValue(), E);
5830 }
5831
Richard Smith4ce706a2011-10-11 21:43:33 +00005832 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00005833 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00005834 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005835 }
5836
Douglas Gregor29c42f22012-02-24 07:38:34 +00005837 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
5838 return Success(E->getValue(), E);
5839 }
5840
John Wiegley6242b6a2011-04-28 00:16:57 +00005841 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
5842 return Success(E->getValue(), E);
5843 }
5844
John Wiegleyf9f65842011-04-25 06:54:41 +00005845 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
5846 return Success(E->getValue(), E);
5847 }
5848
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00005849 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005850 bool VisitUnaryImag(const UnaryOperator *E);
5851
Sebastian Redl5f0180d2010-09-10 20:55:47 +00005852 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00005853 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00005854
Chris Lattnerf8d7f722008-07-11 21:24:13 +00005855private:
Ken Dyck160146e2010-01-27 17:10:57 +00005856 CharUnits GetAlignOfExpr(const Expr *E);
5857 CharUnits GetAlignOfType(QualType T);
Richard Smithce40ad62011-11-12 22:28:03 +00005858 static QualType GetObjectType(APValue::LValueBase B);
Peter Collingbournee9200682011-05-13 03:29:01 +00005859 bool TryEvaluateBuiltinObjectSize(const CallExpr *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00005860 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00005861};
Chris Lattner05706e882008-07-11 18:11:29 +00005862} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005863
Richard Smith11562c52011-10-28 17:51:58 +00005864/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
5865/// produce either the integer value or a pointer.
5866///
5867/// GCC has a heinous extension which folds casts between pointer types and
5868/// pointer-sized integral types. We support this by allowing the evaluation of
5869/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
5870/// Some simple arithmetic on such values is supported (they are treated much
5871/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00005872static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00005873 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005874 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00005875 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00005876}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005877
Richard Smithf57d8cb2011-12-09 22:58:01 +00005878static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00005879 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005880 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00005881 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005882 if (!Val.isInt()) {
5883 // FIXME: It would be better to produce the diagnostic for casting
5884 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00005885 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005886 return false;
5887 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005888 Result = Val.getInt();
5889 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005890}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005891
Richard Smithf57d8cb2011-12-09 22:58:01 +00005892/// Check whether the given declaration can be directly converted to an integral
5893/// rvalue. If not, no diagnostic is produced; there are other things we can
5894/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00005895bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00005896 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005897 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005898 // Check for signedness/width mismatches between E type and ECD value.
5899 bool SameSign = (ECD->getInitVal().isSigned()
5900 == E->getType()->isSignedIntegerOrEnumerationType());
5901 bool SameWidth = (ECD->getInitVal().getBitWidth()
5902 == Info.Ctx.getIntWidth(E->getType()));
5903 if (SameSign && SameWidth)
5904 return Success(ECD->getInitVal(), E);
5905 else {
5906 // Get rid of mismatch (otherwise Success assertions will fail)
5907 // by computing a new value matching the type of E.
5908 llvm::APSInt Val = ECD->getInitVal();
5909 if (!SameSign)
5910 Val.setIsSigned(!ECD->getInitVal().isSigned());
5911 if (!SameWidth)
5912 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
5913 return Success(Val, E);
5914 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00005915 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005916 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00005917}
5918
Chris Lattner86ee2862008-10-06 06:40:35 +00005919/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
5920/// as GCC.
5921static int EvaluateBuiltinClassifyType(const CallExpr *E) {
5922 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00005923 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00005924 enum gcc_type_class {
5925 no_type_class = -1,
5926 void_type_class, integer_type_class, char_type_class,
5927 enumeral_type_class, boolean_type_class,
5928 pointer_type_class, reference_type_class, offset_type_class,
5929 real_type_class, complex_type_class,
5930 function_type_class, method_type_class,
5931 record_type_class, union_type_class,
5932 array_type_class, string_type_class,
5933 lang_type_class
5934 };
Mike Stump11289f42009-09-09 15:08:12 +00005935
5936 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00005937 // ideal, however it is what gcc does.
5938 if (E->getNumArgs() == 0)
5939 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00005940
Chris Lattner86ee2862008-10-06 06:40:35 +00005941 QualType ArgTy = E->getArg(0)->getType();
5942 if (ArgTy->isVoidType())
5943 return void_type_class;
5944 else if (ArgTy->isEnumeralType())
5945 return enumeral_type_class;
5946 else if (ArgTy->isBooleanType())
5947 return boolean_type_class;
5948 else if (ArgTy->isCharType())
5949 return string_type_class; // gcc doesn't appear to use char_type_class
5950 else if (ArgTy->isIntegerType())
5951 return integer_type_class;
5952 else if (ArgTy->isPointerType())
5953 return pointer_type_class;
5954 else if (ArgTy->isReferenceType())
5955 return reference_type_class;
5956 else if (ArgTy->isRealType())
5957 return real_type_class;
5958 else if (ArgTy->isComplexType())
5959 return complex_type_class;
5960 else if (ArgTy->isFunctionType())
5961 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00005962 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00005963 return record_type_class;
5964 else if (ArgTy->isUnionType())
5965 return union_type_class;
5966 else if (ArgTy->isArrayType())
5967 return array_type_class;
5968 else if (ArgTy->isUnionType())
5969 return union_type_class;
5970 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00005971 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00005972}
5973
Richard Smith5fab0c92011-12-28 19:48:30 +00005974/// EvaluateBuiltinConstantPForLValue - Determine the result of
5975/// __builtin_constant_p when applied to the given lvalue.
5976///
5977/// An lvalue is only "constant" if it is a pointer or reference to the first
5978/// character of a string literal.
5979template<typename LValue>
5980static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00005981 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00005982 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
5983}
5984
5985/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
5986/// GCC as we can manage.
5987static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
5988 QualType ArgType = Arg->getType();
5989
5990 // __builtin_constant_p always has one operand. The rules which gcc follows
5991 // are not precisely documented, but are as follows:
5992 //
5993 // - If the operand is of integral, floating, complex or enumeration type,
5994 // and can be folded to a known value of that type, it returns 1.
5995 // - If the operand and can be folded to a pointer to the first character
5996 // of a string literal (or such a pointer cast to an integral type), it
5997 // returns 1.
5998 //
5999 // Otherwise, it returns 0.
6000 //
6001 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6002 // its support for this does not currently work.
6003 if (ArgType->isIntegralOrEnumerationType()) {
6004 Expr::EvalResult Result;
6005 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6006 return false;
6007
6008 APValue &V = Result.Val;
6009 if (V.getKind() == APValue::Int)
6010 return true;
6011
6012 return EvaluateBuiltinConstantPForLValue(V);
6013 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6014 return Arg->isEvaluatable(Ctx);
6015 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6016 LValue LV;
6017 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006018 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006019 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6020 : EvaluatePointer(Arg, LV, Info)) &&
6021 !Status.HasSideEffects)
6022 return EvaluateBuiltinConstantPForLValue(LV);
6023 }
6024
6025 // Anything else isn't considered to be sufficiently constant.
6026 return false;
6027}
6028
John McCall95007602010-05-10 23:27:23 +00006029/// Retrieves the "underlying object type" of the given expression,
6030/// as used by __builtin_object_size.
Richard Smithce40ad62011-11-12 22:28:03 +00006031QualType IntExprEvaluator::GetObjectType(APValue::LValueBase B) {
6032 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6033 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006034 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006035 } else if (const Expr *E = B.get<const Expr*>()) {
6036 if (isa<CompoundLiteralExpr>(E))
6037 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006038 }
6039
6040 return QualType();
6041}
6042
Peter Collingbournee9200682011-05-13 03:29:01 +00006043bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E) {
John McCall95007602010-05-10 23:27:23 +00006044 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006045
6046 {
6047 // The operand of __builtin_object_size is never evaluated for side-effects.
6048 // If there are any, but we can determine the pointed-to object anyway, then
6049 // ignore the side-effects.
6050 SpeculativeEvaluationRAII SpeculativeEval(Info);
6051 if (!EvaluatePointer(E->getArg(0), Base, Info))
6052 return false;
6053 }
John McCall95007602010-05-10 23:27:23 +00006054
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006055 if (!Base.getLValueBase()) {
6056 // It is not possible to determine which objects ptr points to at compile time,
6057 // __builtin_object_size should return (size_t) -1 for type 0 or 1
6058 // and (size_t) 0 for type 2 or 3.
6059 llvm::APSInt TypeIntVaue;
6060 const Expr *ExprType = E->getArg(1);
6061 if (!ExprType->EvaluateAsInt(TypeIntVaue, Info.Ctx))
6062 return false;
6063 if (TypeIntVaue == 0 || TypeIntVaue == 1)
6064 return Success(-1, E);
6065 if (TypeIntVaue == 2 || TypeIntVaue == 3)
6066 return Success(0, E);
6067 return Error(E);
6068 }
John McCall95007602010-05-10 23:27:23 +00006069
Richard Smithce40ad62011-11-12 22:28:03 +00006070 QualType T = GetObjectType(Base.getLValueBase());
John McCall95007602010-05-10 23:27:23 +00006071 if (T.isNull() ||
6072 T->isIncompleteType() ||
Eli Friedmana170cd62010-08-05 02:49:48 +00006073 T->isFunctionType() ||
John McCall95007602010-05-10 23:27:23 +00006074 T->isVariablyModifiedType() ||
6075 T->isDependentType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006076 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006077
6078 CharUnits Size = Info.Ctx.getTypeSizeInChars(T);
6079 CharUnits Offset = Base.getLValueOffset();
6080
6081 if (!Offset.isNegative() && Offset <= Size)
6082 Size -= Offset;
6083 else
6084 Size = CharUnits::Zero();
Ken Dyckdbc01912011-03-11 02:13:43 +00006085 return Success(Size, E);
John McCall95007602010-05-10 23:27:23 +00006086}
6087
Peter Collingbournee9200682011-05-13 03:29:01 +00006088bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006089 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006090 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006091 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006092
6093 case Builtin::BI__builtin_object_size: {
John McCall95007602010-05-10 23:27:23 +00006094 if (TryEvaluateBuiltinObjectSize(E))
6095 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006096
Richard Smith0421ce72012-08-07 04:16:51 +00006097 // If evaluating the argument has side-effects, we can't determine the size
6098 // of the object, and so we lower it to unknown now. CodeGen relies on us to
6099 // handle all cases where the expression has side-effects.
Fariborz Jahanian4127b8e2009-11-05 18:03:03 +00006100 if (E->getArg(0)->HasSideEffects(Info.Ctx)) {
Richard Smithcaf33902011-10-10 18:28:20 +00006101 if (E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue() <= 1)
Chris Lattner4f105592009-11-03 19:48:51 +00006102 return Success(-1ULL, E);
Mike Stump722cedf2009-10-26 18:35:08 +00006103 return Success(0, E);
6104 }
Mike Stump876387b2009-10-27 22:09:17 +00006105
Richard Smith01ade172012-05-23 04:13:20 +00006106 // Expression had no side effects, but we couldn't statically determine the
6107 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006108 switch (Info.EvalMode) {
6109 case EvalInfo::EM_ConstantExpression:
6110 case EvalInfo::EM_PotentialConstantExpression:
6111 case EvalInfo::EM_ConstantFold:
6112 case EvalInfo::EM_EvaluateForOverflow:
6113 case EvalInfo::EM_IgnoreSideEffects:
6114 return Error(E);
6115 case EvalInfo::EM_ConstantExpressionUnevaluated:
6116 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
6117 return Success(-1ULL, E);
6118 }
Mike Stump722cedf2009-10-26 18:35:08 +00006119 }
6120
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006121 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006122 case Builtin::BI__builtin_bswap32:
6123 case Builtin::BI__builtin_bswap64: {
6124 APSInt Val;
6125 if (!EvaluateInteger(E->getArg(0), Val, Info))
6126 return false;
6127
6128 return Success(Val.byteSwap(), E);
6129 }
6130
Richard Smith8889a3d2013-06-13 06:26:32 +00006131 case Builtin::BI__builtin_classify_type:
6132 return Success(EvaluateBuiltinClassifyType(E), E);
6133
6134 // FIXME: BI__builtin_clrsb
6135 // FIXME: BI__builtin_clrsbl
6136 // FIXME: BI__builtin_clrsbll
6137
Richard Smith80b3c8e2013-06-13 05:04:16 +00006138 case Builtin::BI__builtin_clz:
6139 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006140 case Builtin::BI__builtin_clzll:
6141 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006142 APSInt Val;
6143 if (!EvaluateInteger(E->getArg(0), Val, Info))
6144 return false;
6145 if (!Val)
6146 return Error(E);
6147
6148 return Success(Val.countLeadingZeros(), E);
6149 }
6150
Richard Smith8889a3d2013-06-13 06:26:32 +00006151 case Builtin::BI__builtin_constant_p:
6152 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6153
Richard Smith80b3c8e2013-06-13 05:04:16 +00006154 case Builtin::BI__builtin_ctz:
6155 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006156 case Builtin::BI__builtin_ctzll:
6157 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006158 APSInt Val;
6159 if (!EvaluateInteger(E->getArg(0), Val, Info))
6160 return false;
6161 if (!Val)
6162 return Error(E);
6163
6164 return Success(Val.countTrailingZeros(), E);
6165 }
6166
Richard Smith8889a3d2013-06-13 06:26:32 +00006167 case Builtin::BI__builtin_eh_return_data_regno: {
6168 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6169 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6170 return Success(Operand, E);
6171 }
6172
6173 case Builtin::BI__builtin_expect:
6174 return Visit(E->getArg(0));
6175
6176 case Builtin::BI__builtin_ffs:
6177 case Builtin::BI__builtin_ffsl:
6178 case Builtin::BI__builtin_ffsll: {
6179 APSInt Val;
6180 if (!EvaluateInteger(E->getArg(0), Val, Info))
6181 return false;
6182
6183 unsigned N = Val.countTrailingZeros();
6184 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6185 }
6186
6187 case Builtin::BI__builtin_fpclassify: {
6188 APFloat Val(0.0);
6189 if (!EvaluateFloat(E->getArg(5), Val, Info))
6190 return false;
6191 unsigned Arg;
6192 switch (Val.getCategory()) {
6193 case APFloat::fcNaN: Arg = 0; break;
6194 case APFloat::fcInfinity: Arg = 1; break;
6195 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6196 case APFloat::fcZero: Arg = 4; break;
6197 }
6198 return Visit(E->getArg(Arg));
6199 }
6200
6201 case Builtin::BI__builtin_isinf_sign: {
6202 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006203 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006204 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6205 }
6206
Richard Smithea3019d2013-10-15 19:07:14 +00006207 case Builtin::BI__builtin_isinf: {
6208 APFloat Val(0.0);
6209 return EvaluateFloat(E->getArg(0), Val, Info) &&
6210 Success(Val.isInfinity() ? 1 : 0, E);
6211 }
6212
6213 case Builtin::BI__builtin_isfinite: {
6214 APFloat Val(0.0);
6215 return EvaluateFloat(E->getArg(0), Val, Info) &&
6216 Success(Val.isFinite() ? 1 : 0, E);
6217 }
6218
6219 case Builtin::BI__builtin_isnan: {
6220 APFloat Val(0.0);
6221 return EvaluateFloat(E->getArg(0), Val, Info) &&
6222 Success(Val.isNaN() ? 1 : 0, E);
6223 }
6224
6225 case Builtin::BI__builtin_isnormal: {
6226 APFloat Val(0.0);
6227 return EvaluateFloat(E->getArg(0), Val, Info) &&
6228 Success(Val.isNormal() ? 1 : 0, E);
6229 }
6230
Richard Smith8889a3d2013-06-13 06:26:32 +00006231 case Builtin::BI__builtin_parity:
6232 case Builtin::BI__builtin_parityl:
6233 case Builtin::BI__builtin_parityll: {
6234 APSInt Val;
6235 if (!EvaluateInteger(E->getArg(0), Val, Info))
6236 return false;
6237
6238 return Success(Val.countPopulation() % 2, E);
6239 }
6240
Richard Smith80b3c8e2013-06-13 05:04:16 +00006241 case Builtin::BI__builtin_popcount:
6242 case Builtin::BI__builtin_popcountl:
6243 case Builtin::BI__builtin_popcountll: {
6244 APSInt Val;
6245 if (!EvaluateInteger(E->getArg(0), Val, Info))
6246 return false;
6247
6248 return Success(Val.countPopulation(), E);
6249 }
6250
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006251 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006252 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006253 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006254 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006255 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6256 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006257 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006258 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006259 case Builtin::BI__builtin_strlen: {
6260 // As an extension, we support __builtin_strlen() as a constant expression,
6261 // and support folding strlen() to a constant.
6262 LValue String;
6263 if (!EvaluatePointer(E->getArg(0), String, Info))
6264 return false;
6265
6266 // Fast path: if it's a string literal, search the string value.
6267 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6268 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006269 // The string literal may have embedded null characters. Find the first
6270 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006271 StringRef Str = S->getBytes();
6272 int64_t Off = String.Offset.getQuantity();
6273 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6274 S->getCharByteWidth() == 1) {
6275 Str = Str.substr(Off);
6276
6277 StringRef::size_type Pos = Str.find(0);
6278 if (Pos != StringRef::npos)
6279 Str = Str.substr(0, Pos);
6280
6281 return Success(Str.size(), E);
6282 }
6283
6284 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006285 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006286
6287 // Slow path: scan the bytes of the string looking for the terminating 0.
6288 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6289 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6290 APValue Char;
6291 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6292 !Char.isInt())
6293 return false;
6294 if (!Char.getInt())
6295 return Success(Strlen, E);
6296 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6297 return false;
6298 }
6299 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006300
Richard Smith01ba47d2012-04-13 00:45:38 +00006301 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006302 case Builtin::BI__atomic_is_lock_free:
6303 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006304 APSInt SizeVal;
6305 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6306 return false;
6307
6308 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6309 // of two less than the maximum inline atomic width, we know it is
6310 // lock-free. If the size isn't a power of two, or greater than the
6311 // maximum alignment where we promote atomics, we know it is not lock-free
6312 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6313 // the answer can only be determined at runtime; for example, 16-byte
6314 // atomics have lock-free implementations on some, but not all,
6315 // x86-64 processors.
6316
6317 // Check power-of-two.
6318 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006319 if (Size.isPowerOfTwo()) {
6320 // Check against inlining width.
6321 unsigned InlineWidthBits =
6322 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6323 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6324 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6325 Size == CharUnits::One() ||
6326 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6327 Expr::NPC_NeverValueDependent))
6328 // OK, we will inline appropriately-aligned operations of this size,
6329 // and _Atomic(T) is appropriately-aligned.
6330 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006331
Richard Smith01ba47d2012-04-13 00:45:38 +00006332 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6333 castAs<PointerType>()->getPointeeType();
6334 if (!PointeeType->isIncompleteType() &&
6335 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6336 // OK, we will inline operations on this object.
6337 return Success(1, E);
6338 }
6339 }
6340 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006341
Richard Smith01ba47d2012-04-13 00:45:38 +00006342 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6343 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006344 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006345 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006346}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006347
Richard Smith8b3497e2011-10-31 01:37:14 +00006348static bool HasSameBase(const LValue &A, const LValue &B) {
6349 if (!A.getLValueBase())
6350 return !B.getLValueBase();
6351 if (!B.getLValueBase())
6352 return false;
6353
Richard Smithce40ad62011-11-12 22:28:03 +00006354 if (A.getLValueBase().getOpaqueValue() !=
6355 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006356 const Decl *ADecl = GetLValueBaseDecl(A);
6357 if (!ADecl)
6358 return false;
6359 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006360 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006361 return false;
6362 }
6363
6364 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006365 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006366}
6367
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006368namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006369
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006370/// \brief Data recursive integer evaluator of certain binary operators.
6371///
6372/// We use a data recursive algorithm for binary operators so that we are able
6373/// to handle extreme cases of chained binary operators without causing stack
6374/// overflow.
6375class DataRecursiveIntBinOpEvaluator {
6376 struct EvalResult {
6377 APValue Val;
6378 bool Failed;
6379
6380 EvalResult() : Failed(false) { }
6381
6382 void swap(EvalResult &RHS) {
6383 Val.swap(RHS.Val);
6384 Failed = RHS.Failed;
6385 RHS.Failed = false;
6386 }
6387 };
6388
6389 struct Job {
6390 const Expr *E;
6391 EvalResult LHSResult; // meaningful only for binary operator expression.
6392 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00006393
6394 Job() : StoredInfo(nullptr) {}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006395 void startSpeculativeEval(EvalInfo &Info) {
6396 OldEvalStatus = Info.EvalStatus;
Craig Topper36250ad2014-05-12 05:36:57 +00006397 Info.EvalStatus.Diag = nullptr;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006398 StoredInfo = &Info;
6399 }
6400 ~Job() {
6401 if (StoredInfo) {
6402 StoredInfo->EvalStatus = OldEvalStatus;
6403 }
6404 }
6405 private:
6406 EvalInfo *StoredInfo; // non-null if status changed.
6407 Expr::EvalStatus OldEvalStatus;
6408 };
6409
6410 SmallVector<Job, 16> Queue;
6411
6412 IntExprEvaluator &IntEval;
6413 EvalInfo &Info;
6414 APValue &FinalResult;
6415
6416public:
6417 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6418 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6419
6420 /// \brief True if \param E is a binary operator that we are going to handle
6421 /// data recursively.
6422 /// We handle binary operators that are comma, logical, or that have operands
6423 /// with integral or enumeration type.
6424 static bool shouldEnqueue(const BinaryOperator *E) {
6425 return E->getOpcode() == BO_Comma ||
6426 E->isLogicalOp() ||
6427 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6428 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006429 }
6430
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006431 bool Traverse(const BinaryOperator *E) {
6432 enqueue(E);
6433 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006434 while (!Queue.empty())
6435 process(PrevResult);
6436
6437 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006438
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006439 FinalResult.swap(PrevResult.Val);
6440 return true;
6441 }
6442
6443private:
6444 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6445 return IntEval.Success(Value, E, Result);
6446 }
6447 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6448 return IntEval.Success(Value, E, Result);
6449 }
6450 bool Error(const Expr *E) {
6451 return IntEval.Error(E);
6452 }
6453 bool Error(const Expr *E, diag::kind D) {
6454 return IntEval.Error(E, D);
6455 }
6456
6457 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6458 return Info.CCEDiag(E, D);
6459 }
6460
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006461 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6462 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006463 bool &SuppressRHSDiags);
6464
6465 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6466 const BinaryOperator *E, APValue &Result);
6467
6468 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6469 Result.Failed = !Evaluate(Result.Val, Info, E);
6470 if (Result.Failed)
6471 Result.Val = APValue();
6472 }
6473
Richard Trieuba4d0872012-03-21 23:30:30 +00006474 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006475
6476 void enqueue(const Expr *E) {
6477 E = E->IgnoreParens();
6478 Queue.resize(Queue.size()+1);
6479 Queue.back().E = E;
6480 Queue.back().Kind = Job::AnyExprKind;
6481 }
6482};
6483
6484}
6485
6486bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006487 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006488 bool &SuppressRHSDiags) {
6489 if (E->getOpcode() == BO_Comma) {
6490 // Ignore LHS but note if we could not evaluate it.
6491 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006492 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006493 return true;
6494 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006495
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006496 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006497 bool LHSAsBool;
6498 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006499 // We were able to evaluate the LHS, see if we can get away with not
6500 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006501 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6502 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006503 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006504 }
6505 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006506 LHSResult.Failed = true;
6507
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006508 // Since we weren't able to evaluate the left hand side, it
6509 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006510 if (!Info.noteSideEffect())
6511 return false;
6512
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006513 // We can't evaluate the LHS; however, sometimes the result
6514 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6515 // Don't ignore RHS and suppress diagnostics from this arm.
6516 SuppressRHSDiags = true;
6517 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006518
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006519 return true;
6520 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006521
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006522 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6523 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006524
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006525 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006526 return false; // Ignore RHS;
6527
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006528 return true;
6529}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006530
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006531bool DataRecursiveIntBinOpEvaluator::
6532 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6533 const BinaryOperator *E, APValue &Result) {
6534 if (E->getOpcode() == BO_Comma) {
6535 if (RHSResult.Failed)
6536 return false;
6537 Result = RHSResult.Val;
6538 return true;
6539 }
6540
6541 if (E->isLogicalOp()) {
6542 bool lhsResult, rhsResult;
6543 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6544 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6545
6546 if (LHSIsOK) {
6547 if (RHSIsOK) {
6548 if (E->getOpcode() == BO_LOr)
6549 return Success(lhsResult || rhsResult, E, Result);
6550 else
6551 return Success(lhsResult && rhsResult, E, Result);
6552 }
6553 } else {
6554 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006555 // We can't evaluate the LHS; however, sometimes the result
6556 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6557 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006558 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006559 }
6560 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006561
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006562 return false;
6563 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006564
6565 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6566 E->getRHS()->getType()->isIntegralOrEnumerationType());
6567
6568 if (LHSResult.Failed || RHSResult.Failed)
6569 return false;
6570
6571 const APValue &LHSVal = LHSResult.Val;
6572 const APValue &RHSVal = RHSResult.Val;
6573
6574 // Handle cases like (unsigned long)&a + 4.
6575 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6576 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006577 CharUnits AdditionalOffset =
6578 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006579 if (E->getOpcode() == BO_Add)
6580 Result.getLValueOffset() += AdditionalOffset;
6581 else
6582 Result.getLValueOffset() -= AdditionalOffset;
6583 return true;
6584 }
6585
6586 // Handle cases like 4 + (unsigned long)&a
6587 if (E->getOpcode() == BO_Add &&
6588 RHSVal.isLValue() && LHSVal.isInt()) {
6589 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006590 Result.getLValueOffset() +=
6591 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006592 return true;
6593 }
6594
6595 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6596 // Handle (intptr_t)&&A - (intptr_t)&&B.
6597 if (!LHSVal.getLValueOffset().isZero() ||
6598 !RHSVal.getLValueOffset().isZero())
6599 return false;
6600 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6601 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6602 if (!LHSExpr || !RHSExpr)
6603 return false;
6604 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6605 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6606 if (!LHSAddrExpr || !RHSAddrExpr)
6607 return false;
6608 // Make sure both labels come from the same function.
6609 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6610 RHSAddrExpr->getLabel()->getDeclContext())
6611 return false;
6612 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6613 return true;
6614 }
Richard Smith43e77732013-05-07 04:50:00 +00006615
6616 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006617 if (!LHSVal.isInt() || !RHSVal.isInt())
6618 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006619
6620 // Set up the width and signedness manually, in case it can't be deduced
6621 // from the operation we're performing.
6622 // FIXME: Don't do this in the cases where we can deduce it.
6623 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6624 E->getType()->isUnsignedIntegerOrEnumerationType());
6625 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6626 RHSVal.getInt(), Value))
6627 return false;
6628 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006629}
6630
Richard Trieuba4d0872012-03-21 23:30:30 +00006631void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006632 Job &job = Queue.back();
6633
6634 switch (job.Kind) {
6635 case Job::AnyExprKind: {
6636 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6637 if (shouldEnqueue(Bop)) {
6638 job.Kind = Job::BinOpKind;
6639 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006640 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006641 }
6642 }
6643
6644 EvaluateExpr(job.E, Result);
6645 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006646 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006647 }
6648
6649 case Job::BinOpKind: {
6650 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006651 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006652 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006653 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006654 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006655 }
6656 if (SuppressRHSDiags)
6657 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006658 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006659 job.Kind = Job::BinOpVisitedLHSKind;
6660 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006661 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006662 }
6663
6664 case Job::BinOpVisitedLHSKind: {
6665 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6666 EvalResult RHS;
6667 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006668 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006669 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006670 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006671 }
6672 }
6673
6674 llvm_unreachable("Invalid Job::Kind!");
6675}
6676
6677bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
6678 if (E->isAssignmentOp())
6679 return Error(E);
6680
6681 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6682 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006683
Anders Carlssonacc79812008-11-16 07:17:21 +00006684 QualType LHSTy = E->getLHS()->getType();
6685 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006686
6687 if (LHSTy->isAnyComplexType()) {
6688 assert(RHSTy->isAnyComplexType() && "Invalid comparison");
John McCall93d91dc2010-05-07 17:22:02 +00006689 ComplexValue LHS, RHS;
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006690
Richard Smith253c2a32012-01-27 01:14:48 +00006691 bool LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
6692 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006693 return false;
6694
Richard Smith253c2a32012-01-27 01:14:48 +00006695 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006696 return false;
6697
6698 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00006699 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006700 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00006701 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006702 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
6703
John McCalle3027922010-08-25 11:45:40 +00006704 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006705 return Success((CR_r == APFloat::cmpEqual &&
6706 CR_i == APFloat::cmpEqual), E);
6707 else {
John McCalle3027922010-08-25 11:45:40 +00006708 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006709 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00006710 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006711 CR_r == APFloat::cmpLessThan ||
6712 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00006713 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00006714 CR_i == APFloat::cmpLessThan ||
6715 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006716 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006717 } else {
John McCalle3027922010-08-25 11:45:40 +00006718 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006719 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
6720 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
6721 else {
John McCalle3027922010-08-25 11:45:40 +00006722 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006723 "Invalid compex comparison.");
6724 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
6725 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
6726 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00006727 }
6728 }
Mike Stump11289f42009-09-09 15:08:12 +00006729
Anders Carlssonacc79812008-11-16 07:17:21 +00006730 if (LHSTy->isRealFloatingType() &&
6731 RHSTy->isRealFloatingType()) {
6732 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00006733
Richard Smith253c2a32012-01-27 01:14:48 +00006734 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
6735 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00006736 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006737
Richard Smith253c2a32012-01-27 01:14:48 +00006738 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00006739 return false;
Mike Stump11289f42009-09-09 15:08:12 +00006740
Anders Carlssonacc79812008-11-16 07:17:21 +00006741 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00006742
Anders Carlssonacc79812008-11-16 07:17:21 +00006743 switch (E->getOpcode()) {
6744 default:
David Blaikie83d382b2011-09-23 05:06:16 +00006745 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00006746 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006747 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00006748 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006749 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00006750 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006751 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006752 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00006753 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006754 E);
John McCalle3027922010-08-25 11:45:40 +00006755 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006756 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00006757 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00006758 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00006759 || CR == APFloat::cmpLessThan
6760 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00006761 }
Anders Carlssonacc79812008-11-16 07:17:21 +00006762 }
Mike Stump11289f42009-09-09 15:08:12 +00006763
Eli Friedmana38da572009-04-28 19:17:36 +00006764 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006765 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00006766 LValue LHSValue, RHSValue;
6767
6768 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
6769 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006770 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006771
Richard Smith253c2a32012-01-27 01:14:48 +00006772 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006773 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006774
Richard Smith8b3497e2011-10-31 01:37:14 +00006775 // Reject differing bases from the normal codepath; we special-case
6776 // comparisons to null.
6777 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006778 if (E->getOpcode() == BO_Sub) {
6779 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006780 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
6781 return false;
6782 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00006783 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006784 if (!LHSExpr || !RHSExpr)
6785 return false;
6786 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6787 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6788 if (!LHSAddrExpr || !RHSAddrExpr)
6789 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006790 // Make sure both labels come from the same function.
6791 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6792 RHSAddrExpr->getLabel()->getDeclContext())
6793 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006794 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00006795 return true;
6796 }
Richard Smith83c68212011-10-31 05:11:32 +00006797 // Inequalities and subtractions between unrelated pointers have
6798 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00006799 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006800 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006801 // A constant address may compare equal to the address of a symbol.
6802 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00006803 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00006804 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
6805 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006806 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006807 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00006808 // distinct addresses. In clang, the result of such a comparison is
6809 // unspecified, so it is not a constant expression. However, we do know
6810 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00006811 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
6812 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006813 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006814 // We can't tell whether weak symbols will end up pointing to the same
6815 // object.
6816 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006817 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00006818 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00006819 // (Note that clang defaults to -fmerge-all-constants, which can
6820 // lead to inconsistent results for comparisons involving the address
6821 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00006822 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00006823 }
Eli Friedman64004332009-03-23 04:38:34 +00006824
Richard Smith1b470412012-02-01 08:10:20 +00006825 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
6826 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
6827
Richard Smith84f6dcf2012-02-02 01:16:57 +00006828 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
6829 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
6830
John McCalle3027922010-08-25 11:45:40 +00006831 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00006832 // C++11 [expr.add]p6:
6833 // Unless both pointers point to elements of the same array object, or
6834 // one past the last element of the array object, the behavior is
6835 // undefined.
6836 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6837 !AreElementsOfSameArray(getType(LHSValue.Base),
6838 LHSDesignator, RHSDesignator))
6839 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
6840
Chris Lattner882bdf22010-04-20 17:13:14 +00006841 QualType Type = E->getLHS()->getType();
6842 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006843
Richard Smithd62306a2011-11-10 06:34:14 +00006844 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00006845 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00006846 return false;
Eli Friedman64004332009-03-23 04:38:34 +00006847
Richard Smith84c6b3d2013-09-10 21:34:14 +00006848 // As an extension, a type may have zero size (empty struct or union in
6849 // C, array of zero length). Pointer subtraction in such cases has
6850 // undefined behavior, so is not constant.
6851 if (ElementSize.isZero()) {
6852 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
6853 << ElementType;
6854 return false;
6855 }
6856
Richard Smith1b470412012-02-01 08:10:20 +00006857 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
6858 // and produce incorrect results when it overflows. Such behavior
6859 // appears to be non-conforming, but is common, so perhaps we should
6860 // assume the standard intended for such cases to be undefined behavior
6861 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00006862
Richard Smith1b470412012-02-01 08:10:20 +00006863 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
6864 // overflow in the final conversion to ptrdiff_t.
6865 APSInt LHS(
6866 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
6867 APSInt RHS(
6868 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
6869 APSInt ElemSize(
6870 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
6871 APSInt TrueResult = (LHS - RHS) / ElemSize;
6872 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
6873
6874 if (Result.extend(65) != TrueResult)
6875 HandleOverflow(Info, E, TrueResult, E->getType());
6876 return Success(Result, E);
6877 }
Richard Smithde21b242012-01-31 06:41:30 +00006878
6879 // C++11 [expr.rel]p3:
6880 // Pointers to void (after pointer conversions) can be compared, with a
6881 // result defined as follows: If both pointers represent the same
6882 // address or are both the null pointer value, the result is true if the
6883 // operator is <= or >= and false otherwise; otherwise the result is
6884 // unspecified.
6885 // We interpret this as applying to pointers to *cv* void.
6886 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00006887 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00006888 CCEDiag(E, diag::note_constexpr_void_comparison);
6889
Richard Smith84f6dcf2012-02-02 01:16:57 +00006890 // C++11 [expr.rel]p2:
6891 // - If two pointers point to non-static data members of the same object,
6892 // or to subobjects or array elements fo such members, recursively, the
6893 // pointer to the later declared member compares greater provided the
6894 // two members have the same access control and provided their class is
6895 // not a union.
6896 // [...]
6897 // - Otherwise pointer comparisons are unspecified.
6898 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
6899 E->isRelationalOp()) {
6900 bool WasArrayIndex;
6901 unsigned Mismatch =
6902 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
6903 RHSDesignator, WasArrayIndex);
6904 // At the point where the designators diverge, the comparison has a
6905 // specified value if:
6906 // - we are comparing array indices
6907 // - we are comparing fields of a union, or fields with the same access
6908 // Otherwise, the result is unspecified and thus the comparison is not a
6909 // constant expression.
6910 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
6911 Mismatch < RHSDesignator.Entries.size()) {
6912 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
6913 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
6914 if (!LF && !RF)
6915 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
6916 else if (!LF)
6917 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6918 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
6919 << RF->getParent() << RF;
6920 else if (!RF)
6921 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
6922 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
6923 << LF->getParent() << LF;
6924 else if (!LF->getParent()->isUnion() &&
6925 LF->getAccess() != RF->getAccess())
6926 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
6927 << LF << LF->getAccess() << RF << RF->getAccess()
6928 << LF->getParent();
6929 }
6930 }
6931
Eli Friedman6c31cb42012-04-16 04:30:08 +00006932 // The comparison here must be unsigned, and performed with the same
6933 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00006934 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
6935 uint64_t CompareLHS = LHSOffset.getQuantity();
6936 uint64_t CompareRHS = RHSOffset.getQuantity();
6937 assert(PtrSize <= 64 && "Unexpected pointer width");
6938 uint64_t Mask = ~0ULL >> (64 - PtrSize);
6939 CompareLHS &= Mask;
6940 CompareRHS &= Mask;
6941
Eli Friedman2f5b7c52012-04-16 19:23:57 +00006942 // If there is a base and this is a relational operator, we can only
6943 // compare pointers within the object in question; otherwise, the result
6944 // depends on where the object is located in memory.
6945 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
6946 QualType BaseTy = getType(LHSValue.Base);
6947 if (BaseTy->isIncompleteType())
6948 return Error(E);
6949 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
6950 uint64_t OffsetLimit = Size.getQuantity();
6951 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
6952 return Error(E);
6953 }
6954
Richard Smith8b3497e2011-10-31 01:37:14 +00006955 switch (E->getOpcode()) {
6956 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00006957 case BO_LT: return Success(CompareLHS < CompareRHS, E);
6958 case BO_GT: return Success(CompareLHS > CompareRHS, E);
6959 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
6960 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
6961 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
6962 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00006963 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006964 }
6965 }
Richard Smith7bb00672012-02-01 01:42:44 +00006966
6967 if (LHSTy->isMemberPointerType()) {
6968 assert(E->isEqualityOp() && "unexpected member pointer operation");
6969 assert(RHSTy->isMemberPointerType() && "invalid comparison");
6970
6971 MemberPtr LHSValue, RHSValue;
6972
6973 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
6974 if (!LHSOK && Info.keepEvaluatingAfterFailure())
6975 return false;
6976
6977 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
6978 return false;
6979
6980 // C++11 [expr.eq]p2:
6981 // If both operands are null, they compare equal. Otherwise if only one is
6982 // null, they compare unequal.
6983 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
6984 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
6985 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
6986 }
6987
6988 // Otherwise if either is a pointer to a virtual member function, the
6989 // result is unspecified.
6990 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
6991 if (MD->isVirtual())
6992 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6993 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
6994 if (MD->isVirtual())
6995 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
6996
6997 // Otherwise they compare equal if and only if they would refer to the
6998 // same member of the same most derived object or the same subobject if
6999 // they were dereferenced with a hypothetical object of the associated
7000 // class type.
7001 bool Equal = LHSValue == RHSValue;
7002 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7003 }
7004
Richard Smithab44d9b2012-02-14 22:35:28 +00007005 if (LHSTy->isNullPtrType()) {
7006 assert(E->isComparisonOp() && "unexpected nullptr operation");
7007 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7008 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7009 // are compared, the result is true of the operator is <=, >= or ==, and
7010 // false otherwise.
7011 BinaryOperator::Opcode Opcode = E->getOpcode();
7012 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7013 }
7014
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007015 assert((!LHSTy->isIntegralOrEnumerationType() ||
7016 !RHSTy->isIntegralOrEnumerationType()) &&
7017 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7018 // We can't continue from here for non-integral types.
7019 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00007020}
7021
Ken Dyck160146e2010-01-27 17:10:57 +00007022CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
Richard Smithf6d70302014-06-10 23:34:28 +00007023 // C++ [expr.alignof]p3:
7024 // When alignof is applied to a reference type, the result is the
7025 // alignment of the referenced type.
Sebastian Redl22e2e5c2009-11-23 17:18:46 +00007026 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
7027 T = Ref->getPointeeType();
Chad Rosier99ee7822011-07-26 07:03:04 +00007028
7029 // __alignof is defined to return the preferred alignment.
7030 return Info.Ctx.toCharUnitsFromBits(
7031 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
Chris Lattner24aeeab2009-01-24 21:09:06 +00007032}
7033
Ken Dyck160146e2010-01-27 17:10:57 +00007034CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
Chris Lattner68061312009-01-24 21:53:27 +00007035 E = E->IgnoreParens();
7036
John McCall768439e2013-05-06 07:40:34 +00007037 // The kinds of expressions that we have special-case logic here for
7038 // should be kept up to date with the special checks for those
7039 // expressions in Sema.
7040
Chris Lattner68061312009-01-24 21:53:27 +00007041 // alignof decl is always accepted, even if it doesn't make sense: we default
Mike Stump11289f42009-09-09 15:08:12 +00007042 // to 1 in those cases.
Chris Lattner68061312009-01-24 21:53:27 +00007043 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
Richard Smithf6d70302014-06-10 23:34:28 +00007044 return Info.Ctx.getDeclAlign(DRE->getDecl(),
Ken Dyck160146e2010-01-27 17:10:57 +00007045 /*RefAsPointee*/true);
Eli Friedman64004332009-03-23 04:38:34 +00007046
Chris Lattner68061312009-01-24 21:53:27 +00007047 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
Ken Dyck160146e2010-01-27 17:10:57 +00007048 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
7049 /*RefAsPointee*/true);
Chris Lattner68061312009-01-24 21:53:27 +00007050
Chris Lattner24aeeab2009-01-24 21:09:06 +00007051 return GetAlignOfType(E->getType());
7052}
7053
7054
Peter Collingbournee190dee2011-03-11 19:24:49 +00007055/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7056/// a result as the expression's type.
7057bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7058 const UnaryExprOrTypeTraitExpr *E) {
7059 switch(E->getKind()) {
7060 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00007061 if (E->isArgumentType())
Ken Dyckdbc01912011-03-11 02:13:43 +00007062 return Success(GetAlignOfType(E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007063 else
Ken Dyckdbc01912011-03-11 02:13:43 +00007064 return Success(GetAlignOfExpr(E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007065 }
Eli Friedman64004332009-03-23 04:38:34 +00007066
Peter Collingbournee190dee2011-03-11 19:24:49 +00007067 case UETT_VecStep: {
7068 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00007069
Peter Collingbournee190dee2011-03-11 19:24:49 +00007070 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00007071 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00007072
Peter Collingbournee190dee2011-03-11 19:24:49 +00007073 // The vec_step built-in functions that take a 3-component
7074 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7075 if (n == 3)
7076 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00007077
Peter Collingbournee190dee2011-03-11 19:24:49 +00007078 return Success(n, E);
7079 } else
7080 return Success(1, E);
7081 }
7082
7083 case UETT_SizeOf: {
7084 QualType SrcTy = E->getTypeOfArgument();
7085 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7086 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007087 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7088 SrcTy = Ref->getPointeeType();
7089
Richard Smithd62306a2011-11-10 06:34:14 +00007090 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007091 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007092 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007093 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007094 }
7095 }
7096
7097 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007098}
7099
Peter Collingbournee9200682011-05-13 03:29:01 +00007100bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007101 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007102 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007103 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007104 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007105 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007106 for (unsigned i = 0; i != n; ++i) {
7107 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7108 switch (ON.getKind()) {
7109 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007110 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007111 APSInt IdxResult;
7112 if (!EvaluateInteger(Idx, IdxResult, Info))
7113 return false;
7114 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7115 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007116 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007117 CurrentType = AT->getElementType();
7118 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7119 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007120 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007121 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007122
Douglas Gregor882211c2010-04-28 22:16:22 +00007123 case OffsetOfExpr::OffsetOfNode::Field: {
7124 FieldDecl *MemberDecl = ON.getField();
7125 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007126 if (!RT)
7127 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007128 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007129 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007130 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007131 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007132 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007133 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007134 CurrentType = MemberDecl->getType().getNonReferenceType();
7135 break;
7136 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007137
Douglas Gregor882211c2010-04-28 22:16:22 +00007138 case OffsetOfExpr::OffsetOfNode::Identifier:
7139 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007140
Douglas Gregord1702062010-04-29 00:18:15 +00007141 case OffsetOfExpr::OffsetOfNode::Base: {
7142 CXXBaseSpecifier *BaseSpec = ON.getBase();
7143 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007144 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007145
7146 // Find the layout of the class whose base we are looking into.
7147 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007148 if (!RT)
7149 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007150 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007151 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007152 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7153
7154 // Find the base class itself.
7155 CurrentType = BaseSpec->getType();
7156 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7157 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007158 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007159
7160 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007161 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007162 break;
7163 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007164 }
7165 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007166 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007167}
7168
Chris Lattnere13042c2008-07-11 19:10:17 +00007169bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007170 switch (E->getOpcode()) {
7171 default:
7172 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7173 // See C99 6.6p3.
7174 return Error(E);
7175 case UO_Extension:
7176 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7177 // If so, we could clear the diagnostic ID.
7178 return Visit(E->getSubExpr());
7179 case UO_Plus:
7180 // The result is just the value.
7181 return Visit(E->getSubExpr());
7182 case UO_Minus: {
7183 if (!Visit(E->getSubExpr()))
7184 return false;
7185 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007186 const APSInt &Value = Result.getInt();
7187 if (Value.isSigned() && Value.isMinSignedValue())
7188 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7189 E->getType());
7190 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007191 }
7192 case UO_Not: {
7193 if (!Visit(E->getSubExpr()))
7194 return false;
7195 if (!Result.isInt()) return Error(E);
7196 return Success(~Result.getInt(), E);
7197 }
7198 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007199 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007200 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007201 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007202 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007203 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007204 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007205}
Mike Stump11289f42009-09-09 15:08:12 +00007206
Chris Lattner477c4be2008-07-12 01:15:53 +00007207/// HandleCast - This is used to evaluate implicit or explicit casts where the
7208/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007209bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7210 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007211 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007212 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007213
Eli Friedmanc757de22011-03-25 00:43:55 +00007214 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007215 case CK_BaseToDerived:
7216 case CK_DerivedToBase:
7217 case CK_UncheckedDerivedToBase:
7218 case CK_Dynamic:
7219 case CK_ToUnion:
7220 case CK_ArrayToPointerDecay:
7221 case CK_FunctionToPointerDecay:
7222 case CK_NullToPointer:
7223 case CK_NullToMemberPointer:
7224 case CK_BaseToDerivedMemberPointer:
7225 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007226 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007227 case CK_ConstructorConversion:
7228 case CK_IntegralToPointer:
7229 case CK_ToVoid:
7230 case CK_VectorSplat:
7231 case CK_IntegralToFloating:
7232 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007233 case CK_CPointerToObjCPointerCast:
7234 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007235 case CK_AnyPointerToBlockPointerCast:
7236 case CK_ObjCObjectLValueCast:
7237 case CK_FloatingRealToComplex:
7238 case CK_FloatingComplexToReal:
7239 case CK_FloatingComplexCast:
7240 case CK_FloatingComplexToIntegralComplex:
7241 case CK_IntegralRealToComplex:
7242 case CK_IntegralComplexCast:
7243 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007244 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007245 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007246 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007247 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007248 llvm_unreachable("invalid cast kind for integral value");
7249
Eli Friedman9faf2f92011-03-25 19:07:11 +00007250 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007251 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007252 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007253 case CK_ARCProduceObject:
7254 case CK_ARCConsumeObject:
7255 case CK_ARCReclaimReturnedObject:
7256 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007257 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007258 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007259
Richard Smith4ef685b2012-01-17 21:17:26 +00007260 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007261 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007262 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007263 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007264 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007265
7266 case CK_MemberPointerToBoolean:
7267 case CK_PointerToBoolean:
7268 case CK_IntegralToBoolean:
7269 case CK_FloatingToBoolean:
7270 case CK_FloatingComplexToBoolean:
7271 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007272 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007273 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007274 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007275 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007276 }
7277
Eli Friedmanc757de22011-03-25 00:43:55 +00007278 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007279 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007280 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007281
Eli Friedman742421e2009-02-20 01:15:07 +00007282 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007283 // Allow casts of address-of-label differences if they are no-ops
7284 // or narrowing. (The narrowing case isn't actually guaranteed to
7285 // be constant-evaluatable except in some narrow cases which are hard
7286 // to detect here. We let it through on the assumption the user knows
7287 // what they are doing.)
7288 if (Result.isAddrLabelDiff())
7289 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007290 // Only allow casts of lvalues if they are lossless.
7291 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7292 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007293
Richard Smith911e1422012-01-30 22:27:01 +00007294 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7295 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007296 }
Mike Stump11289f42009-09-09 15:08:12 +00007297
Eli Friedmanc757de22011-03-25 00:43:55 +00007298 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007299 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7300
John McCall45d55e42010-05-07 21:00:08 +00007301 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007302 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007303 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007304
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007305 if (LV.getLValueBase()) {
7306 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007307 // FIXME: Allow a larger integer size than the pointer size, and allow
7308 // narrowing back down to pointer width in subsequent integral casts.
7309 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007310 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007311 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007312
Richard Smithcf74da72011-11-16 07:18:12 +00007313 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007314 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007315 return true;
7316 }
7317
Ken Dyck02990832010-01-15 12:37:54 +00007318 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7319 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007320 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007321 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007322
Eli Friedmanc757de22011-03-25 00:43:55 +00007323 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007324 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007325 if (!EvaluateComplex(SubExpr, C, Info))
7326 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007327 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007328 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007329
Eli Friedmanc757de22011-03-25 00:43:55 +00007330 case CK_FloatingToIntegral: {
7331 APFloat F(0.0);
7332 if (!EvaluateFloat(SubExpr, F, Info))
7333 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007334
Richard Smith357362d2011-12-13 06:39:58 +00007335 APSInt Value;
7336 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7337 return false;
7338 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007339 }
7340 }
Mike Stump11289f42009-09-09 15:08:12 +00007341
Eli Friedmanc757de22011-03-25 00:43:55 +00007342 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007343}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007344
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007345bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7346 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007347 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007348 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7349 return false;
7350 if (!LV.isComplexInt())
7351 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007352 return Success(LV.getComplexIntReal(), E);
7353 }
7354
7355 return Visit(E->getSubExpr());
7356}
7357
Eli Friedman4e7a2412009-02-27 04:45:43 +00007358bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007359 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007360 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007361 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7362 return false;
7363 if (!LV.isComplexInt())
7364 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007365 return Success(LV.getComplexIntImag(), E);
7366 }
7367
Richard Smith4a678122011-10-24 18:44:57 +00007368 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007369 return Success(0, E);
7370}
7371
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007372bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7373 return Success(E->getPackLength(), E);
7374}
7375
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007376bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7377 return Success(E->getValue(), E);
7378}
7379
Chris Lattner05706e882008-07-11 18:11:29 +00007380//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007381// Float Evaluation
7382//===----------------------------------------------------------------------===//
7383
7384namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007385class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007386 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00007387 APFloat &Result;
7388public:
7389 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007390 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007391
Richard Smith2e312c82012-03-03 22:46:17 +00007392 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007393 Result = V.getFloat();
7394 return true;
7395 }
Eli Friedman24c01542008-08-22 00:06:13 +00007396
Richard Smithfddd3842011-12-30 21:15:51 +00007397 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007398 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7399 return true;
7400 }
7401
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007402 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007403
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007404 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007405 bool VisitBinaryOperator(const BinaryOperator *E);
7406 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007407 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007408
John McCallb1fb0d32010-05-07 22:08:54 +00007409 bool VisitUnaryReal(const UnaryOperator *E);
7410 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007411
Richard Smithfddd3842011-12-30 21:15:51 +00007412 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007413};
7414} // end anonymous namespace
7415
7416static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007417 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007418 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007419}
7420
Jay Foad39c79802011-01-12 09:06:06 +00007421static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007422 QualType ResultTy,
7423 const Expr *Arg,
7424 bool SNaN,
7425 llvm::APFloat &Result) {
7426 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7427 if (!S) return false;
7428
7429 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7430
7431 llvm::APInt fill;
7432
7433 // Treat empty strings as if they were zero.
7434 if (S->getString().empty())
7435 fill = llvm::APInt(32, 0);
7436 else if (S->getString().getAsInteger(0, fill))
7437 return false;
7438
7439 if (SNaN)
7440 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7441 else
7442 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7443 return true;
7444}
7445
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007446bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00007447 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007448 default:
7449 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7450
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007451 case Builtin::BI__builtin_huge_val:
7452 case Builtin::BI__builtin_huge_valf:
7453 case Builtin::BI__builtin_huge_vall:
7454 case Builtin::BI__builtin_inf:
7455 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007456 case Builtin::BI__builtin_infl: {
7457 const llvm::fltSemantics &Sem =
7458 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007459 Result = llvm::APFloat::getInf(Sem);
7460 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007461 }
Mike Stump11289f42009-09-09 15:08:12 +00007462
John McCall16291492010-02-28 13:00:19 +00007463 case Builtin::BI__builtin_nans:
7464 case Builtin::BI__builtin_nansf:
7465 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007466 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7467 true, Result))
7468 return Error(E);
7469 return true;
John McCall16291492010-02-28 13:00:19 +00007470
Chris Lattner0b7282e2008-10-06 06:31:58 +00007471 case Builtin::BI__builtin_nan:
7472 case Builtin::BI__builtin_nanf:
7473 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007474 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007475 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007476 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7477 false, Result))
7478 return Error(E);
7479 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007480
7481 case Builtin::BI__builtin_fabs:
7482 case Builtin::BI__builtin_fabsf:
7483 case Builtin::BI__builtin_fabsl:
7484 if (!EvaluateFloat(E->getArg(0), Result, Info))
7485 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007486
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007487 if (Result.isNegative())
7488 Result.changeSign();
7489 return true;
7490
Richard Smith8889a3d2013-06-13 06:26:32 +00007491 // FIXME: Builtin::BI__builtin_powi
7492 // FIXME: Builtin::BI__builtin_powif
7493 // FIXME: Builtin::BI__builtin_powil
7494
Mike Stump11289f42009-09-09 15:08:12 +00007495 case Builtin::BI__builtin_copysign:
7496 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007497 case Builtin::BI__builtin_copysignl: {
7498 APFloat RHS(0.);
7499 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7500 !EvaluateFloat(E->getArg(1), RHS, Info))
7501 return false;
7502 Result.copySign(RHS);
7503 return true;
7504 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007505 }
7506}
7507
John McCallb1fb0d32010-05-07 22:08:54 +00007508bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007509 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7510 ComplexValue CV;
7511 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7512 return false;
7513 Result = CV.FloatReal;
7514 return true;
7515 }
7516
7517 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007518}
7519
7520bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007521 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7522 ComplexValue CV;
7523 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7524 return false;
7525 Result = CV.FloatImag;
7526 return true;
7527 }
7528
Richard Smith4a678122011-10-24 18:44:57 +00007529 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007530 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7531 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007532 return true;
7533}
7534
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007535bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007536 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007537 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007538 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007539 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007540 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007541 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7542 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007543 Result.changeSign();
7544 return true;
7545 }
7546}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007547
Eli Friedman24c01542008-08-22 00:06:13 +00007548bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007549 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7550 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007551
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007552 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007553 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7554 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007555 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007556 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7557 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007558}
7559
7560bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7561 Result = E->getValue();
7562 return true;
7563}
7564
Peter Collingbournee9200682011-05-13 03:29:01 +00007565bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7566 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007567
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007568 switch (E->getCastKind()) {
7569 default:
Richard Smith11562c52011-10-28 17:51:58 +00007570 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007571
7572 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007573 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007574 return EvaluateInteger(SubExpr, IntResult, Info) &&
7575 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7576 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007577 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007578
7579 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007580 if (!Visit(SubExpr))
7581 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007582 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7583 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007584 }
John McCalld7646252010-11-14 08:17:51 +00007585
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007586 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007587 ComplexValue V;
7588 if (!EvaluateComplex(SubExpr, V, Info))
7589 return false;
7590 Result = V.getComplexFloatReal();
7591 return true;
7592 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007593 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007594}
7595
Eli Friedman24c01542008-08-22 00:06:13 +00007596//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007597// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007598//===----------------------------------------------------------------------===//
7599
7600namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007601class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007602 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00007603 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007604
Anders Carlsson537969c2008-11-16 20:27:53 +00007605public:
John McCall93d91dc2010-05-07 17:22:02 +00007606 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007607 : ExprEvaluatorBaseTy(info), Result(Result) {}
7608
Richard Smith2e312c82012-03-03 22:46:17 +00007609 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007610 Result.setFrom(V);
7611 return true;
7612 }
Mike Stump11289f42009-09-09 15:08:12 +00007613
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007614 bool ZeroInitialization(const Expr *E);
7615
Anders Carlsson537969c2008-11-16 20:27:53 +00007616 //===--------------------------------------------------------------------===//
7617 // Visitor Methods
7618 //===--------------------------------------------------------------------===//
7619
Peter Collingbournee9200682011-05-13 03:29:01 +00007620 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007621 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007622 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007623 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007624 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007625};
7626} // end anonymous namespace
7627
John McCall93d91dc2010-05-07 17:22:02 +00007628static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7629 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007630 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007631 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007632}
7633
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007634bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007635 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007636 if (ElemTy->isRealFloatingType()) {
7637 Result.makeComplexFloat();
7638 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7639 Result.FloatReal = Zero;
7640 Result.FloatImag = Zero;
7641 } else {
7642 Result.makeComplexInt();
7643 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7644 Result.IntReal = Zero;
7645 Result.IntImag = Zero;
7646 }
7647 return true;
7648}
7649
Peter Collingbournee9200682011-05-13 03:29:01 +00007650bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7651 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007652
7653 if (SubExpr->getType()->isRealFloatingType()) {
7654 Result.makeComplexFloat();
7655 APFloat &Imag = Result.FloatImag;
7656 if (!EvaluateFloat(SubExpr, Imag, Info))
7657 return false;
7658
7659 Result.FloatReal = APFloat(Imag.getSemantics());
7660 return true;
7661 } else {
7662 assert(SubExpr->getType()->isIntegerType() &&
7663 "Unexpected imaginary literal.");
7664
7665 Result.makeComplexInt();
7666 APSInt &Imag = Result.IntImag;
7667 if (!EvaluateInteger(SubExpr, Imag, Info))
7668 return false;
7669
7670 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
7671 return true;
7672 }
7673}
7674
Peter Collingbournee9200682011-05-13 03:29:01 +00007675bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007676
John McCallfcef3cf2010-12-14 17:51:41 +00007677 switch (E->getCastKind()) {
7678 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007679 case CK_BaseToDerived:
7680 case CK_DerivedToBase:
7681 case CK_UncheckedDerivedToBase:
7682 case CK_Dynamic:
7683 case CK_ToUnion:
7684 case CK_ArrayToPointerDecay:
7685 case CK_FunctionToPointerDecay:
7686 case CK_NullToPointer:
7687 case CK_NullToMemberPointer:
7688 case CK_BaseToDerivedMemberPointer:
7689 case CK_DerivedToBaseMemberPointer:
7690 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00007691 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00007692 case CK_ConstructorConversion:
7693 case CK_IntegralToPointer:
7694 case CK_PointerToIntegral:
7695 case CK_PointerToBoolean:
7696 case CK_ToVoid:
7697 case CK_VectorSplat:
7698 case CK_IntegralCast:
7699 case CK_IntegralToBoolean:
7700 case CK_IntegralToFloating:
7701 case CK_FloatingToIntegral:
7702 case CK_FloatingToBoolean:
7703 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007704 case CK_CPointerToObjCPointerCast:
7705 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007706 case CK_AnyPointerToBlockPointerCast:
7707 case CK_ObjCObjectLValueCast:
7708 case CK_FloatingComplexToReal:
7709 case CK_FloatingComplexToBoolean:
7710 case CK_IntegralComplexToReal:
7711 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00007712 case CK_ARCProduceObject:
7713 case CK_ARCConsumeObject:
7714 case CK_ARCReclaimReturnedObject:
7715 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007716 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00007717 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007718 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007719 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007720 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00007721 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00007722
John McCallfcef3cf2010-12-14 17:51:41 +00007723 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007724 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00007725 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007726 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007727
7728 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007729 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00007730 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007731 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00007732
7733 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007734 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00007735 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007736 return false;
7737
John McCallfcef3cf2010-12-14 17:51:41 +00007738 Result.makeComplexFloat();
7739 Result.FloatImag = APFloat(Real.getSemantics());
7740 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007741 }
7742
John McCallfcef3cf2010-12-14 17:51:41 +00007743 case CK_FloatingComplexCast: {
7744 if (!Visit(E->getSubExpr()))
7745 return false;
7746
7747 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7748 QualType From
7749 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7750
Richard Smith357362d2011-12-13 06:39:58 +00007751 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
7752 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007753 }
7754
7755 case CK_FloatingComplexToIntegralComplex: {
7756 if (!Visit(E->getSubExpr()))
7757 return false;
7758
7759 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7760 QualType From
7761 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7762 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00007763 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
7764 To, Result.IntReal) &&
7765 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
7766 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007767 }
7768
7769 case CK_IntegralRealToComplex: {
7770 APSInt &Real = Result.IntReal;
7771 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
7772 return false;
7773
7774 Result.makeComplexInt();
7775 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
7776 return true;
7777 }
7778
7779 case CK_IntegralComplexCast: {
7780 if (!Visit(E->getSubExpr()))
7781 return false;
7782
7783 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
7784 QualType From
7785 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
7786
Richard Smith911e1422012-01-30 22:27:01 +00007787 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
7788 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007789 return true;
7790 }
7791
7792 case CK_IntegralComplexToFloatingComplex: {
7793 if (!Visit(E->getSubExpr()))
7794 return false;
7795
Ted Kremenek28831752012-08-23 20:46:57 +00007796 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007797 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00007798 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00007799 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00007800 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
7801 To, Result.FloatReal) &&
7802 HandleIntToFloatCast(Info, E, From, Result.IntImag,
7803 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00007804 }
7805 }
7806
7807 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007808}
7809
John McCall93d91dc2010-05-07 17:22:02 +00007810bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007811 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00007812 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
7813
Richard Smith253c2a32012-01-27 01:14:48 +00007814 bool LHSOK = Visit(E->getLHS());
7815 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00007816 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007817
John McCall93d91dc2010-05-07 17:22:02 +00007818 ComplexValue RHS;
Richard Smith253c2a32012-01-27 01:14:48 +00007819 if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00007820 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007821
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007822 assert(Result.isComplexFloat() == RHS.isComplexFloat() &&
7823 "Invalid operands to binary operator.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007824 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007825 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007826 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007827 if (Result.isComplexFloat()) {
7828 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
7829 APFloat::rmNearestTiesToEven);
7830 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
7831 APFloat::rmNearestTiesToEven);
7832 } else {
7833 Result.getComplexIntReal() += RHS.getComplexIntReal();
7834 Result.getComplexIntImag() += RHS.getComplexIntImag();
7835 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007836 break;
John McCalle3027922010-08-25 11:45:40 +00007837 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007838 if (Result.isComplexFloat()) {
7839 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
7840 APFloat::rmNearestTiesToEven);
7841 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
7842 APFloat::rmNearestTiesToEven);
7843 } else {
7844 Result.getComplexIntReal() -= RHS.getComplexIntReal();
7845 Result.getComplexIntImag() -= RHS.getComplexIntImag();
7846 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007847 break;
John McCalle3027922010-08-25 11:45:40 +00007848 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007849 if (Result.isComplexFloat()) {
John McCall93d91dc2010-05-07 17:22:02 +00007850 ComplexValue LHS = Result;
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007851 APFloat &LHS_r = LHS.getComplexFloatReal();
7852 APFloat &LHS_i = LHS.getComplexFloatImag();
7853 APFloat &RHS_r = RHS.getComplexFloatReal();
7854 APFloat &RHS_i = RHS.getComplexFloatImag();
Mike Stump11289f42009-09-09 15:08:12 +00007855
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007856 APFloat Tmp = LHS_r;
7857 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7858 Result.getComplexFloatReal() = Tmp;
7859 Tmp = LHS_i;
7860 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7861 Result.getComplexFloatReal().subtract(Tmp, APFloat::rmNearestTiesToEven);
7862
7863 Tmp = LHS_r;
7864 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7865 Result.getComplexFloatImag() = Tmp;
7866 Tmp = LHS_i;
7867 Tmp.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7868 Result.getComplexFloatImag().add(Tmp, APFloat::rmNearestTiesToEven);
7869 } else {
John McCall93d91dc2010-05-07 17:22:02 +00007870 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00007871 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007872 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
7873 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00007874 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00007875 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
7876 LHS.getComplexIntImag() * RHS.getComplexIntReal());
7877 }
7878 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007879 case BO_Div:
7880 if (Result.isComplexFloat()) {
7881 ComplexValue LHS = Result;
7882 APFloat &LHS_r = LHS.getComplexFloatReal();
7883 APFloat &LHS_i = LHS.getComplexFloatImag();
7884 APFloat &RHS_r = RHS.getComplexFloatReal();
7885 APFloat &RHS_i = RHS.getComplexFloatImag();
7886 APFloat &Res_r = Result.getComplexFloatReal();
7887 APFloat &Res_i = Result.getComplexFloatImag();
7888
7889 APFloat Den = RHS_r;
7890 Den.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7891 APFloat Tmp = RHS_i;
7892 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7893 Den.add(Tmp, APFloat::rmNearestTiesToEven);
7894
7895 Res_r = LHS_r;
7896 Res_r.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7897 Tmp = LHS_i;
7898 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7899 Res_r.add(Tmp, APFloat::rmNearestTiesToEven);
7900 Res_r.divide(Den, APFloat::rmNearestTiesToEven);
7901
7902 Res_i = LHS_i;
7903 Res_i.multiply(RHS_r, APFloat::rmNearestTiesToEven);
7904 Tmp = LHS_r;
7905 Tmp.multiply(RHS_i, APFloat::rmNearestTiesToEven);
7906 Res_i.subtract(Tmp, APFloat::rmNearestTiesToEven);
7907 Res_i.divide(Den, APFloat::rmNearestTiesToEven);
7908 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007909 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
7910 return Error(E, diag::note_expr_divide_by_zero);
7911
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007912 ComplexValue LHS = Result;
7913 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
7914 RHS.getComplexIntImag() * RHS.getComplexIntImag();
7915 Result.getComplexIntReal() =
7916 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
7917 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
7918 Result.getComplexIntImag() =
7919 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
7920 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
7921 }
7922 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007923 }
7924
John McCall93d91dc2010-05-07 17:22:02 +00007925 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00007926}
7927
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007928bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
7929 // Get the operand value into 'Result'.
7930 if (!Visit(E->getSubExpr()))
7931 return false;
7932
7933 switch (E->getOpcode()) {
7934 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007935 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007936 case UO_Extension:
7937 return true;
7938 case UO_Plus:
7939 // The result is always just the subexpr.
7940 return true;
7941 case UO_Minus:
7942 if (Result.isComplexFloat()) {
7943 Result.getComplexFloatReal().changeSign();
7944 Result.getComplexFloatImag().changeSign();
7945 }
7946 else {
7947 Result.getComplexIntReal() = -Result.getComplexIntReal();
7948 Result.getComplexIntImag() = -Result.getComplexIntImag();
7949 }
7950 return true;
7951 case UO_Not:
7952 if (Result.isComplexFloat())
7953 Result.getComplexFloatImag().changeSign();
7954 else
7955 Result.getComplexIntImag() = -Result.getComplexIntImag();
7956 return true;
7957 }
7958}
7959
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007960bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
7961 if (E->getNumInits() == 2) {
7962 if (E->getType()->isComplexType()) {
7963 Result.makeComplexFloat();
7964 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
7965 return false;
7966 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
7967 return false;
7968 } else {
7969 Result.makeComplexInt();
7970 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
7971 return false;
7972 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
7973 return false;
7974 }
7975 return true;
7976 }
7977 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
7978}
7979
Anders Carlsson537969c2008-11-16 20:27:53 +00007980//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00007981// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
7982// implicit conversion.
7983//===----------------------------------------------------------------------===//
7984
7985namespace {
7986class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00007987 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00007988 APValue &Result;
7989public:
7990 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
7991 : ExprEvaluatorBaseTy(Info), Result(Result) {}
7992
7993 bool Success(const APValue &V, const Expr *E) {
7994 Result = V;
7995 return true;
7996 }
7997
7998 bool ZeroInitialization(const Expr *E) {
7999 ImplicitValueInitExpr VIE(
8000 E->getType()->castAs<AtomicType>()->getValueType());
8001 return Evaluate(Result, Info, &VIE);
8002 }
8003
8004 bool VisitCastExpr(const CastExpr *E) {
8005 switch (E->getCastKind()) {
8006 default:
8007 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8008 case CK_NonAtomicToAtomic:
8009 return Evaluate(Result, Info, E->getSubExpr());
8010 }
8011 }
8012};
8013} // end anonymous namespace
8014
8015static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8016 assert(E->isRValue() && E->getType()->isAtomicType());
8017 return AtomicExprEvaluator(Info, Result).Visit(E);
8018}
8019
8020//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00008021// Void expression evaluation, primarily for a cast to void on the LHS of a
8022// comma operator
8023//===----------------------------------------------------------------------===//
8024
8025namespace {
8026class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008027 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00008028public:
8029 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8030
Richard Smith2e312c82012-03-03 22:46:17 +00008031 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00008032
8033 bool VisitCastExpr(const CastExpr *E) {
8034 switch (E->getCastKind()) {
8035 default:
8036 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8037 case CK_ToVoid:
8038 VisitIgnoredValue(E->getSubExpr());
8039 return true;
8040 }
8041 }
Hal Finkela8443c32014-07-17 14:49:58 +00008042
8043 bool VisitCallExpr(const CallExpr *E) {
8044 switch (E->getBuiltinCallee()) {
8045 default:
8046 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8047 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00008048 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00008049 // The argument is not evaluated!
8050 return true;
8051 }
8052 }
Richard Smith42d3af92011-12-07 00:43:50 +00008053};
8054} // end anonymous namespace
8055
8056static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8057 assert(E->isRValue() && E->getType()->isVoidType());
8058 return VoidExprEvaluator(Info).Visit(E);
8059}
8060
8061//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00008062// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00008063//===----------------------------------------------------------------------===//
8064
Richard Smith2e312c82012-03-03 22:46:17 +00008065static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00008066 // In C, function designators are not lvalues, but we evaluate them as if they
8067 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00008068 QualType T = E->getType();
8069 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00008070 LValue LV;
8071 if (!EvaluateLValue(E, LV, Info))
8072 return false;
8073 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008074 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008075 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008076 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008077 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008078 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008079 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008080 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00008081 LValue LV;
8082 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008083 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008084 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008085 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00008086 llvm::APFloat F(0.0);
8087 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008088 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00008089 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00008090 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00008091 ComplexValue C;
8092 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008093 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008094 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008095 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00008096 MemberPtr P;
8097 if (!EvaluateMemberPointer(E, P, Info))
8098 return false;
8099 P.moveInto(Result);
8100 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00008101 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008102 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008103 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008104 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8105 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008106 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008107 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008108 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008109 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008110 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008111 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8112 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008113 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008114 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008115 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008116 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008117 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008118 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008119 if (!EvaluateVoid(E, Info))
8120 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008121 } else if (T->isAtomicType()) {
8122 if (!EvaluateAtomic(E, Result, Info))
8123 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008124 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008125 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008126 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008127 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008128 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008129 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008130 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008131
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008132 return true;
8133}
8134
Richard Smithb228a862012-02-15 02:18:13 +00008135/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8136/// cases, the in-place evaluation is essential, since later initializers for
8137/// an object can indirectly refer to subobjects which were initialized earlier.
8138static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008139 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008140 assert(!E->isValueDependent());
8141
Richard Smith7525ff62013-05-09 07:14:00 +00008142 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008143 return false;
8144
8145 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008146 // Evaluate arrays and record types in-place, so that later initializers can
8147 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008148 if (E->getType()->isArrayType())
8149 return EvaluateArray(E, This, Result, Info);
8150 else if (E->getType()->isRecordType())
8151 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008152 }
8153
8154 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008155 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008156}
8157
Richard Smithf57d8cb2011-12-09 22:58:01 +00008158/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8159/// lvalue-to-rvalue cast if it is an lvalue.
8160static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00008161 if (E->getType().isNull())
8162 return false;
8163
Richard Smithfddd3842011-12-30 21:15:51 +00008164 if (!CheckLiteralType(Info, E))
8165 return false;
8166
Richard Smith2e312c82012-03-03 22:46:17 +00008167 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008168 return false;
8169
8170 if (E->isGLValue()) {
8171 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008172 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008173 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008174 return false;
8175 }
8176
Richard Smith2e312c82012-03-03 22:46:17 +00008177 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008178 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008179}
Richard Smith11562c52011-10-28 17:51:58 +00008180
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008181static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8182 const ASTContext &Ctx, bool &IsConst) {
8183 // Fast-path evaluations of integer literals, since we sometimes see files
8184 // containing vast quantities of these.
8185 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8186 Result.Val = APValue(APSInt(L->getValue(),
8187 L->getType()->isUnsignedIntegerType()));
8188 IsConst = true;
8189 return true;
8190 }
James Dennett0492ef02014-03-14 17:44:10 +00008191
8192 // This case should be rare, but we need to check it before we check on
8193 // the type below.
8194 if (Exp->getType().isNull()) {
8195 IsConst = false;
8196 return true;
8197 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008198
8199 // FIXME: Evaluating values of large array and record types can cause
8200 // performance problems. Only do so in C++11 for now.
8201 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8202 Exp->getType()->isRecordType()) &&
8203 !Ctx.getLangOpts().CPlusPlus11) {
8204 IsConst = false;
8205 return true;
8206 }
8207 return false;
8208}
8209
8210
Richard Smith7b553f12011-10-29 00:50:52 +00008211/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008212/// any crazy technique (that has nothing to do with language standards) that
8213/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008214/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8215/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008216bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008217 bool IsConst;
8218 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8219 return IsConst;
8220
Richard Smith6d4c6582013-11-05 22:18:15 +00008221 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008222 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008223}
8224
Jay Foad39c79802011-01-12 09:06:06 +00008225bool Expr::EvaluateAsBooleanCondition(bool &Result,
8226 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008227 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008228 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008229 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008230}
8231
Richard Smith5fab0c92011-12-28 19:48:30 +00008232bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8233 SideEffectsKind AllowSideEffects) const {
8234 if (!getType()->isIntegralOrEnumerationType())
8235 return false;
8236
Richard Smith11562c52011-10-28 17:51:58 +00008237 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008238 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8239 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008240 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008241
Richard Smith11562c52011-10-28 17:51:58 +00008242 Result = ExprResult.Val.getInt();
8243 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008244}
8245
Jay Foad39c79802011-01-12 09:06:06 +00008246bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008247 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008248
John McCall45d55e42010-05-07 21:00:08 +00008249 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008250 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8251 !CheckLValueConstantExpression(Info, getExprLoc(),
8252 Ctx.getLValueReferenceType(getType()), LV))
8253 return false;
8254
Richard Smith2e312c82012-03-03 22:46:17 +00008255 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008256 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008257}
8258
Richard Smithd0b4dd62011-12-19 06:19:21 +00008259bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8260 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008261 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008262 // FIXME: Evaluating initializers for large array and record types can cause
8263 // performance problems. Only do so in C++11 for now.
8264 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008265 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008266 return false;
8267
Richard Smithd0b4dd62011-12-19 06:19:21 +00008268 Expr::EvalStatus EStatus;
8269 EStatus.Diag = &Notes;
8270
Richard Smith6d4c6582013-11-05 22:18:15 +00008271 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008272 InitInfo.setEvaluatingDecl(VD, Value);
8273
8274 LValue LVal;
8275 LVal.set(VD);
8276
Richard Smithfddd3842011-12-30 21:15:51 +00008277 // C++11 [basic.start.init]p2:
8278 // Variables with static storage duration or thread storage duration shall be
8279 // zero-initialized before any other initialization takes place.
8280 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008281 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008282 !VD->getType()->isReferenceType()) {
8283 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008284 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008285 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008286 return false;
8287 }
8288
Richard Smith7525ff62013-05-09 07:14:00 +00008289 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8290 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008291 EStatus.HasSideEffects)
8292 return false;
8293
8294 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8295 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008296}
8297
Richard Smith7b553f12011-10-29 00:50:52 +00008298/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8299/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008300bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008301 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008302 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008303}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008304
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008305APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008306 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008307 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008308 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008309 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008310 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008311 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008312 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008313
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008314 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008315}
John McCall864e3962010-05-07 05:32:02 +00008316
Richard Smithe9ff7702013-11-05 22:23:30 +00008317void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008318 bool IsConst;
8319 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008320 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008321 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008322 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8323 }
8324}
8325
Richard Smithe6c01442013-06-05 00:46:14 +00008326bool Expr::EvalResult::isGlobalLValue() const {
8327 assert(Val.isLValue());
8328 return IsGlobalLValue(Val.getLValueBase());
8329}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008330
8331
John McCall864e3962010-05-07 05:32:02 +00008332/// isIntegerConstantExpr - this recursive routine will test if an expression is
8333/// an integer constant expression.
8334
8335/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8336/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008337
8338// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008339// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8340// and a (possibly null) SourceLocation indicating the location of the problem.
8341//
John McCall864e3962010-05-07 05:32:02 +00008342// Note that to reduce code duplication, this helper does no evaluation
8343// itself; the caller checks whether the expression is evaluatable, and
8344// in the rare cases where CheckICE actually cares about the evaluated
8345// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008346
Dan Gohman28ade552010-07-26 21:25:24 +00008347namespace {
8348
Richard Smith9e575da2012-12-28 13:25:52 +00008349enum ICEKind {
8350 /// This expression is an ICE.
8351 IK_ICE,
8352 /// This expression is not an ICE, but if it isn't evaluated, it's
8353 /// a legal subexpression for an ICE. This return value is used to handle
8354 /// the comma operator in C99 mode, and non-constant subexpressions.
8355 IK_ICEIfUnevaluated,
8356 /// This expression is not an ICE, and is not a legal subexpression for one.
8357 IK_NotICE
8358};
8359
John McCall864e3962010-05-07 05:32:02 +00008360struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008361 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008362 SourceLocation Loc;
8363
Richard Smith9e575da2012-12-28 13:25:52 +00008364 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008365};
8366
Dan Gohman28ade552010-07-26 21:25:24 +00008367}
8368
Richard Smith9e575da2012-12-28 13:25:52 +00008369static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8370
8371static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008372
Craig Toppera31a8822013-08-22 07:09:37 +00008373static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008374 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008375 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008376 !EVResult.Val.isInt())
8377 return ICEDiag(IK_NotICE, E->getLocStart());
8378
John McCall864e3962010-05-07 05:32:02 +00008379 return NoDiag();
8380}
8381
Craig Toppera31a8822013-08-22 07:09:37 +00008382static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008383 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008384 if (!E->getType()->isIntegralOrEnumerationType())
8385 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008386
8387 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008388#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008389#define STMT(Node, Base) case Expr::Node##Class:
8390#define EXPR(Node, Base)
8391#include "clang/AST/StmtNodes.inc"
8392 case Expr::PredefinedExprClass:
8393 case Expr::FloatingLiteralClass:
8394 case Expr::ImaginaryLiteralClass:
8395 case Expr::StringLiteralClass:
8396 case Expr::ArraySubscriptExprClass:
8397 case Expr::MemberExprClass:
8398 case Expr::CompoundAssignOperatorClass:
8399 case Expr::CompoundLiteralExprClass:
8400 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008401 case Expr::DesignatedInitExprClass:
8402 case Expr::ImplicitValueInitExprClass:
8403 case Expr::ParenListExprClass:
8404 case Expr::VAArgExprClass:
8405 case Expr::AddrLabelExprClass:
8406 case Expr::StmtExprClass:
8407 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008408 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008409 case Expr::CXXDynamicCastExprClass:
8410 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008411 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008412 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008413 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008414 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008415 case Expr::CXXThisExprClass:
8416 case Expr::CXXThrowExprClass:
8417 case Expr::CXXNewExprClass:
8418 case Expr::CXXDeleteExprClass:
8419 case Expr::CXXPseudoDestructorExprClass:
8420 case Expr::UnresolvedLookupExprClass:
8421 case Expr::DependentScopeDeclRefExprClass:
8422 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008423 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008424 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008425 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008426 case Expr::CXXTemporaryObjectExprClass:
8427 case Expr::CXXUnresolvedConstructExprClass:
8428 case Expr::CXXDependentScopeMemberExprClass:
8429 case Expr::UnresolvedMemberExprClass:
8430 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008431 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008432 case Expr::ObjCArrayLiteralClass:
8433 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008434 case Expr::ObjCEncodeExprClass:
8435 case Expr::ObjCMessageExprClass:
8436 case Expr::ObjCSelectorExprClass:
8437 case Expr::ObjCProtocolExprClass:
8438 case Expr::ObjCIvarRefExprClass:
8439 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008440 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008441 case Expr::ObjCIsaExprClass:
8442 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00008443 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00008444 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008445 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008446 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008447 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008448 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008449 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008450 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008451 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008452 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008453 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008454 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008455 case Expr::LambdaExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008456 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008457
Richard Smithf137f932014-01-25 20:50:08 +00008458 case Expr::InitListExprClass: {
8459 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8460 // form "T x = { a };" is equivalent to "T x = a;".
8461 // Unless we're initializing a reference, T is a scalar as it is known to be
8462 // of integral or enumeration type.
8463 if (E->isRValue())
8464 if (cast<InitListExpr>(E)->getNumInits() == 1)
8465 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8466 return ICEDiag(IK_NotICE, E->getLocStart());
8467 }
8468
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008469 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008470 case Expr::GNUNullExprClass:
8471 // GCC considers the GNU __null value to be an integral constant expression.
8472 return NoDiag();
8473
John McCall7c454bb2011-07-15 05:09:51 +00008474 case Expr::SubstNonTypeTemplateParmExprClass:
8475 return
8476 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8477
John McCall864e3962010-05-07 05:32:02 +00008478 case Expr::ParenExprClass:
8479 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008480 case Expr::GenericSelectionExprClass:
8481 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008482 case Expr::IntegerLiteralClass:
8483 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008484 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008485 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008486 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008487 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008488 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008489 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008490 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008491 return NoDiag();
8492 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008493 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008494 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8495 // constant expressions, but they can never be ICEs because an ICE cannot
8496 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008497 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00008498 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00008499 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008500 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008501 }
Richard Smith6365c912012-02-24 22:12:32 +00008502 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008503 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8504 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008505 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008506 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008507 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008508 // Parameter variables are never constants. Without this check,
8509 // getAnyInitializer() can find a default argument, which leads
8510 // to chaos.
8511 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008512 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008513
8514 // C++ 7.1.5.1p2
8515 // A variable of non-volatile const-qualified integral or enumeration
8516 // type initialized by an ICE can be used in ICEs.
8517 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008518 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008519 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008520
Richard Smithd0b4dd62011-12-19 06:19:21 +00008521 const VarDecl *VD;
8522 // Look for a declaration of this variable that has an initializer, and
8523 // check whether it is an ICE.
8524 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8525 return NoDiag();
8526 else
Richard Smith9e575da2012-12-28 13:25:52 +00008527 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008528 }
8529 }
Richard Smith9e575da2012-12-28 13:25:52 +00008530 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008531 }
John McCall864e3962010-05-07 05:32:02 +00008532 case Expr::UnaryOperatorClass: {
8533 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8534 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008535 case UO_PostInc:
8536 case UO_PostDec:
8537 case UO_PreInc:
8538 case UO_PreDec:
8539 case UO_AddrOf:
8540 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008541 // C99 6.6/3 allows increment and decrement within unevaluated
8542 // subexpressions of constant expressions, but they can never be ICEs
8543 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008544 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008545 case UO_Extension:
8546 case UO_LNot:
8547 case UO_Plus:
8548 case UO_Minus:
8549 case UO_Not:
8550 case UO_Real:
8551 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008552 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008553 }
Richard Smith9e575da2012-12-28 13:25:52 +00008554
John McCall864e3962010-05-07 05:32:02 +00008555 // OffsetOf falls through here.
8556 }
8557 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008558 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8559 // EvaluateAsRValue matches the proposed gcc behavior for cases like
8560 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
8561 // compliance: we should warn earlier for offsetof expressions with
8562 // array subscripts that aren't ICEs, and if the array subscripts
8563 // are ICEs, the value of the offsetof must be an integer constant.
8564 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008565 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00008566 case Expr::UnaryExprOrTypeTraitExprClass: {
8567 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
8568 if ((Exp->getKind() == UETT_SizeOf) &&
8569 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00008570 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008571 return NoDiag();
8572 }
8573 case Expr::BinaryOperatorClass: {
8574 const BinaryOperator *Exp = cast<BinaryOperator>(E);
8575 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008576 case BO_PtrMemD:
8577 case BO_PtrMemI:
8578 case BO_Assign:
8579 case BO_MulAssign:
8580 case BO_DivAssign:
8581 case BO_RemAssign:
8582 case BO_AddAssign:
8583 case BO_SubAssign:
8584 case BO_ShlAssign:
8585 case BO_ShrAssign:
8586 case BO_AndAssign:
8587 case BO_XorAssign:
8588 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00008589 // C99 6.6/3 allows assignments within unevaluated subexpressions of
8590 // constant expressions, but they can never be ICEs because an ICE cannot
8591 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008592 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008593
John McCalle3027922010-08-25 11:45:40 +00008594 case BO_Mul:
8595 case BO_Div:
8596 case BO_Rem:
8597 case BO_Add:
8598 case BO_Sub:
8599 case BO_Shl:
8600 case BO_Shr:
8601 case BO_LT:
8602 case BO_GT:
8603 case BO_LE:
8604 case BO_GE:
8605 case BO_EQ:
8606 case BO_NE:
8607 case BO_And:
8608 case BO_Xor:
8609 case BO_Or:
8610 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00008611 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8612 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00008613 if (Exp->getOpcode() == BO_Div ||
8614 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00008615 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00008616 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00008617 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00008618 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008619 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00008620 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008621 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00008622 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00008623 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00008624 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008625 }
8626 }
8627 }
John McCalle3027922010-08-25 11:45:40 +00008628 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00008629 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00008630 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
8631 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00008632 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
8633 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008634 } else {
8635 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00008636 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008637 }
8638 }
Richard Smith9e575da2012-12-28 13:25:52 +00008639 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008640 }
John McCalle3027922010-08-25 11:45:40 +00008641 case BO_LAnd:
8642 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00008643 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
8644 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008645 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00008646 // Rare case where the RHS has a comma "side-effect"; we need
8647 // to actually check the condition to see whether the side
8648 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00008649 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00008650 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00008651 return RHSResult;
8652 return NoDiag();
8653 }
8654
Richard Smith9e575da2012-12-28 13:25:52 +00008655 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00008656 }
8657 }
8658 }
8659 case Expr::ImplicitCastExprClass:
8660 case Expr::CStyleCastExprClass:
8661 case Expr::CXXFunctionalCastExprClass:
8662 case Expr::CXXStaticCastExprClass:
8663 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00008664 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00008665 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008666 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00008667 if (isa<ExplicitCastExpr>(E)) {
8668 if (const FloatingLiteral *FL
8669 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
8670 unsigned DestWidth = Ctx.getIntWidth(E->getType());
8671 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
8672 APSInt IgnoredVal(DestWidth, !DestSigned);
8673 bool Ignored;
8674 // If the value does not fit in the destination type, the behavior is
8675 // undefined, so we are not required to treat it as a constant
8676 // expression.
8677 if (FL->getValue().convertToInteger(IgnoredVal,
8678 llvm::APFloat::rmTowardZero,
8679 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00008680 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00008681 return NoDiag();
8682 }
8683 }
Eli Friedman76d4e432011-09-29 21:49:34 +00008684 switch (cast<CastExpr>(E)->getCastKind()) {
8685 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008686 case CK_AtomicToNonAtomic:
8687 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00008688 case CK_NoOp:
8689 case CK_IntegralToBoolean:
8690 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00008691 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00008692 default:
Richard Smith9e575da2012-12-28 13:25:52 +00008693 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00008694 }
John McCall864e3962010-05-07 05:32:02 +00008695 }
John McCallc07a0c72011-02-17 10:25:35 +00008696 case Expr::BinaryConditionalOperatorClass: {
8697 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
8698 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008699 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00008700 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008701 if (FalseResult.Kind == IK_NotICE) return FalseResult;
8702 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
8703 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00008704 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00008705 return FalseResult;
8706 }
John McCall864e3962010-05-07 05:32:02 +00008707 case Expr::ConditionalOperatorClass: {
8708 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
8709 // If the condition (ignoring parens) is a __builtin_constant_p call,
8710 // then only the true side is actually considered in an integer constant
8711 // expression, and it is fully evaluated. This is an important GNU
8712 // extension. See GCC PR38377 for discussion.
8713 if (const CallExpr *CallCE
8714 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00008715 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00008716 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00008717 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008718 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008719 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008720
Richard Smithf57d8cb2011-12-09 22:58:01 +00008721 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
8722 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00008723
Richard Smith9e575da2012-12-28 13:25:52 +00008724 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008725 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008726 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00008727 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008728 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00008729 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00008730 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00008731 return NoDiag();
8732 // Rare case where the diagnostics depend on which side is evaluated
8733 // Note that if we get here, CondResult is 0, and at least one of
8734 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00008735 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00008736 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00008737 return TrueResult;
8738 }
8739 case Expr::CXXDefaultArgExprClass:
8740 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00008741 case Expr::CXXDefaultInitExprClass:
8742 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008743 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00008744 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008745 }
8746 }
8747
David Blaikiee4d798f2012-01-20 21:50:17 +00008748 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00008749}
8750
Richard Smithf57d8cb2011-12-09 22:58:01 +00008751/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00008752static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008753 const Expr *E,
8754 llvm::APSInt *Value,
8755 SourceLocation *Loc) {
8756 if (!E->getType()->isIntegralOrEnumerationType()) {
8757 if (Loc) *Loc = E->getExprLoc();
8758 return false;
8759 }
8760
Richard Smith66e05fe2012-01-18 05:21:49 +00008761 APValue Result;
8762 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00008763 return false;
8764
Richard Smith66e05fe2012-01-18 05:21:49 +00008765 assert(Result.isInt() && "pointer cast to int is not an ICE");
8766 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00008767 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008768}
8769
Craig Toppera31a8822013-08-22 07:09:37 +00008770bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
8771 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008772 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00008773 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008774
Richard Smith9e575da2012-12-28 13:25:52 +00008775 ICEDiag D = CheckICE(this, Ctx);
8776 if (D.Kind != IK_ICE) {
8777 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00008778 return false;
8779 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008780 return true;
8781}
8782
Craig Toppera31a8822013-08-22 07:09:37 +00008783bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00008784 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008785 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008786 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
8787
8788 if (!isIntegerConstantExpr(Ctx, Loc))
8789 return false;
8790 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00008791 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00008792 return true;
8793}
Richard Smith66e05fe2012-01-18 05:21:49 +00008794
Craig Toppera31a8822013-08-22 07:09:37 +00008795bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00008796 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00008797}
8798
Craig Toppera31a8822013-08-22 07:09:37 +00008799bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00008800 SourceLocation *Loc) const {
8801 // We support this checking in C++98 mode in order to diagnose compatibility
8802 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008803 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00008804
Richard Smith98a0a492012-02-14 21:38:30 +00008805 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00008806 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008807 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00008808 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00008809 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00008810
8811 APValue Scratch;
8812 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
8813
8814 if (!Diags.empty()) {
8815 IsConstExpr = false;
8816 if (Loc) *Loc = Diags[0].first;
8817 } else if (!IsConstExpr) {
8818 // FIXME: This shouldn't happen.
8819 if (Loc) *Loc = getExprLoc();
8820 }
8821
8822 return IsConstExpr;
8823}
Richard Smith253c2a32012-01-27 01:14:48 +00008824
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008825bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
8826 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00008827 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008828 Expr::EvalStatus Status;
8829 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
8830
8831 ArgVector ArgValues(Args.size());
8832 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
8833 I != E; ++I) {
8834 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I))
8835 // If evaluation fails, throw away the argument entirely.
8836 ArgValues[I - Args.begin()] = APValue();
8837 if (Info.EvalStatus.HasSideEffects)
8838 return false;
8839 }
8840
8841 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00008842 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008843 ArgValues.data());
8844 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
8845}
8846
Richard Smith253c2a32012-01-27 01:14:48 +00008847bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008848 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00008849 PartialDiagnosticAt> &Diags) {
8850 // FIXME: It would be useful to check constexpr function templates, but at the
8851 // moment the constant expression evaluator cannot cope with the non-rigorous
8852 // ASTs which we build for dependent expressions.
8853 if (FD->isDependentContext())
8854 return true;
8855
8856 Expr::EvalStatus Status;
8857 Status.Diag = &Diags;
8858
Richard Smith6d4c6582013-11-05 22:18:15 +00008859 EvalInfo Info(FD->getASTContext(), Status,
8860 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00008861
8862 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00008863 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00008864
Richard Smith7525ff62013-05-09 07:14:00 +00008865 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00008866 // is a temporary being used as the 'this' pointer.
8867 LValue This;
8868 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00008869 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00008870
Richard Smith253c2a32012-01-27 01:14:48 +00008871 ArrayRef<const Expr*> Args;
8872
8873 SourceLocation Loc = FD->getLocation();
8874
Richard Smith2e312c82012-03-03 22:46:17 +00008875 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00008876 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
8877 // Evaluate the call as a constant initializer, to allow the construction
8878 // of objects of non-literal types.
8879 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00008880 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00008881 } else
Craig Topper36250ad2014-05-12 05:36:57 +00008882 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith253c2a32012-01-27 01:14:48 +00008883 Args, FD->getBody(), Info, Scratch);
8884
8885 return Diags.empty();
8886}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008887
8888bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
8889 const FunctionDecl *FD,
8890 SmallVectorImpl<
8891 PartialDiagnosticAt> &Diags) {
8892 Expr::EvalStatus Status;
8893 Status.Diag = &Diags;
8894
8895 EvalInfo Info(FD->getASTContext(), Status,
8896 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
8897
8898 // Fabricate a call stack frame to give the arguments a plausible cover story.
8899 ArrayRef<const Expr*> Args;
8900 ArgVector ArgValues(0);
8901 bool Success = EvaluateArgs(Args, ArgValues, Info);
8902 (void)Success;
8903 assert(Success &&
8904 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00008905 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00008906
8907 APValue ResultScratch;
8908 Evaluate(ResultScratch, Info, E);
8909 return Diags.empty();
8910}