blob: dea85d84a2d7a72a33c1bb6a2f91b41e1a932d42 [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.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000495 EM_PotentialConstantExpressionUnevaluated,
496
497 /// Evaluate as a constant expression. Continue evaluating if we find a
498 /// MemberExpr with a base that can't be evaluated.
499 EM_DesignatorFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000500 } EvalMode;
501
502 /// Are we checking whether the expression is a potential constant
503 /// expression?
504 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000505 return EvalMode == EM_PotentialConstantExpression ||
506 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000507 }
508
509 /// Are we checking an expression for overflow?
510 // FIXME: We should check for any kind of undefined or suspicious behavior
511 // in such constructs, not just overflow.
512 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
513
514 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000515 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000516 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000517 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000518 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
519 EvaluatingDecl((const ValueDecl *)nullptr),
520 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
521 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000522
Richard Smith7525ff62013-05-09 07:14:00 +0000523 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
524 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000525 EvaluatingDeclValue = &Value;
526 }
527
David Blaikiebbafb8a2012-03-11 07:00:24 +0000528 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000529
Richard Smith357362d2011-12-13 06:39:58 +0000530 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000531 // Don't perform any constexpr calls (other than the call we're checking)
532 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000533 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000534 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000535 if (NextCallIndex == 0) {
536 // NextCallIndex has wrapped around.
537 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
538 return false;
539 }
Richard Smith357362d2011-12-13 06:39:58 +0000540 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
541 return true;
542 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
543 << getLangOpts().ConstexprCallDepth;
544 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000545 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000546
Richard Smithb228a862012-02-15 02:18:13 +0000547 CallStackFrame *getCallFrame(unsigned CallIndex) {
548 assert(CallIndex && "no call index in getCallFrame");
549 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
550 // be null in this loop.
551 CallStackFrame *Frame = CurrentCall;
552 while (Frame->Index > CallIndex)
553 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000554 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000555 }
556
Richard Smitha3d3bd22013-05-08 02:12:03 +0000557 bool nextStep(const Stmt *S) {
558 if (!StepsLeft) {
559 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
560 return false;
561 }
562 --StepsLeft;
563 return true;
564 }
565
Richard Smith357362d2011-12-13 06:39:58 +0000566 private:
567 /// Add a diagnostic to the diagnostics list.
568 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
569 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
570 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
571 return EvalStatus.Diag->back().second;
572 }
573
Richard Smithf6f003a2011-12-16 19:06:07 +0000574 /// Add notes containing a call stack to the current point of evaluation.
575 void addCallStack(unsigned Limit);
576
Richard Smith357362d2011-12-13 06:39:58 +0000577 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000578 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000579 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
580 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000581 unsigned ExtraNotes = 0) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000582 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000583 // If we have a prior diagnostic, it will be noting that the expression
584 // isn't a constant expression. This diagnostic is more important,
585 // unless we require this evaluation to produce a constant expression.
586 //
587 // FIXME: We might want to show both diagnostics to the user in
588 // EM_ConstantFold mode.
589 if (!EvalStatus.Diag->empty()) {
590 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000591 case EM_ConstantFold:
592 case EM_IgnoreSideEffects:
593 case EM_EvaluateForOverflow:
594 if (!EvalStatus.HasSideEffects)
595 break;
596 // We've had side-effects; we want the diagnostic from them, not
597 // some later problem.
Richard Smith6d4c6582013-11-05 22:18:15 +0000598 case EM_ConstantExpression:
599 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000600 case EM_ConstantExpressionUnevaluated:
601 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000602 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000603 HasActiveDiagnostic = false;
604 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000605 }
606 }
607
Richard Smithf6f003a2011-12-16 19:06:07 +0000608 unsigned CallStackNotes = CallStackDepth - 1;
609 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
610 if (Limit)
611 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000612 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000613 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000614
Richard Smith357362d2011-12-13 06:39:58 +0000615 HasActiveDiagnostic = true;
Richard Smith92b1ce02011-12-12 09:28:41 +0000616 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000617 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
618 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000619 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000620 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000621 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000622 }
Richard Smith357362d2011-12-13 06:39:58 +0000623 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000624 return OptionalDiagnostic();
625 }
626
Richard Smithce1ec5e2012-03-15 04:53:45 +0000627 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
628 = diag::note_invalid_subexpr_in_const_expr,
629 unsigned ExtraNotes = 0) {
630 if (EvalStatus.Diag)
631 return Diag(E->getExprLoc(), DiagId, ExtraNotes);
632 HasActiveDiagnostic = false;
633 return OptionalDiagnostic();
634 }
635
Richard Smith92b1ce02011-12-12 09:28:41 +0000636 /// Diagnose that the evaluation does not produce a C++11 core constant
637 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000638 ///
639 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
640 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000641 template<typename LocArg>
642 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000643 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000644 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000645 // Don't override a previous diagnostic. Don't bother collecting
646 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000647 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000648 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000649 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000650 }
Richard Smith357362d2011-12-13 06:39:58 +0000651 return Diag(Loc, DiagId, ExtraNotes);
652 }
653
654 /// Add a note to a prior diagnostic.
655 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
656 if (!HasActiveDiagnostic)
657 return OptionalDiagnostic();
658 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000659 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000660
661 /// Add a stack of notes to a prior diagnostic.
662 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
663 if (HasActiveDiagnostic) {
664 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
665 Diags.begin(), Diags.end());
666 }
667 }
Richard Smith253c2a32012-01-27 01:14:48 +0000668
Richard Smith6d4c6582013-11-05 22:18:15 +0000669 /// Should we continue evaluation after encountering a side-effect that we
670 /// couldn't model?
671 bool keepEvaluatingAfterSideEffect() {
672 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000673 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000674 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000675 case EM_EvaluateForOverflow:
676 case EM_IgnoreSideEffects:
677 return true;
678
Richard Smith6d4c6582013-11-05 22:18:15 +0000679 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000680 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000681 case EM_ConstantFold:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000682 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000683 return false;
684 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000685 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000686 }
687
688 /// Note that we have had a side-effect, and determine whether we should
689 /// keep evaluating.
690 bool noteSideEffect() {
691 EvalStatus.HasSideEffects = true;
692 return keepEvaluatingAfterSideEffect();
693 }
694
Richard Smith253c2a32012-01-27 01:14:48 +0000695 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000696 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000697 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000698 if (!StepsLeft)
699 return false;
700
701 switch (EvalMode) {
702 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000703 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000704 case EM_EvaluateForOverflow:
705 return true;
706
707 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000708 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000709 case EM_ConstantFold:
710 case EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000711 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000712 return false;
713 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000714 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000715 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000716
717 bool allowInvalidBaseExpr() const {
718 return EvalMode == EM_DesignatorFold;
719 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000720 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000721
722 /// Object used to treat all foldable expressions as constant expressions.
723 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000724 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000725 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000726 bool HadNoPriorDiags;
727 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000728
Richard Smith6d4c6582013-11-05 22:18:15 +0000729 explicit FoldConstant(EvalInfo &Info, bool Enabled)
730 : Info(Info),
731 Enabled(Enabled),
732 HadNoPriorDiags(Info.EvalStatus.Diag &&
733 Info.EvalStatus.Diag->empty() &&
734 !Info.EvalStatus.HasSideEffects),
735 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000736 if (Enabled &&
737 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
738 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000739 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000740 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000741 void keepDiagnostics() { Enabled = false; }
742 ~FoldConstant() {
743 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000744 !Info.EvalStatus.HasSideEffects)
745 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000746 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000747 }
748 };
Richard Smith17100ba2012-02-16 02:46:34 +0000749
George Burgess IV3a03fab2015-09-04 21:28:13 +0000750 /// RAII object used to treat the current evaluation as the correct pointer
751 /// offset fold for the current EvalMode
752 struct FoldOffsetRAII {
753 EvalInfo &Info;
754 EvalInfo::EvaluationMode OldMode;
755 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
756 : Info(Info), OldMode(Info.EvalMode) {
757 if (!Info.checkingPotentialConstantExpression())
758 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
759 : EvalInfo::EM_ConstantFold;
760 }
761
762 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
763 };
764
Richard Smith17100ba2012-02-16 02:46:34 +0000765 /// RAII object used to suppress diagnostics and side-effects from a
766 /// speculative evaluation.
767 class SpeculativeEvaluationRAII {
768 EvalInfo &Info;
769 Expr::EvalStatus Old;
770
771 public:
772 SpeculativeEvaluationRAII(EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +0000773 SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Richard Smith17100ba2012-02-16 02:46:34 +0000774 : Info(Info), Old(Info.EvalStatus) {
775 Info.EvalStatus.Diag = NewDiag;
Richard Smith6d4c6582013-11-05 22:18:15 +0000776 // If we're speculatively evaluating, we may have skipped over some
777 // evaluations and missed out a side effect.
778 Info.EvalStatus.HasSideEffects = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000779 }
780 ~SpeculativeEvaluationRAII() {
781 Info.EvalStatus = Old;
782 }
783 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000784
785 /// RAII object wrapping a full-expression or block scope, and handling
786 /// the ending of the lifetime of temporaries created within it.
787 template<bool IsFullExpression>
788 class ScopeRAII {
789 EvalInfo &Info;
790 unsigned OldStackSize;
791 public:
792 ScopeRAII(EvalInfo &Info)
793 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
794 ~ScopeRAII() {
795 // Body moved to a static method to encourage the compiler to inline away
796 // instances of this class.
797 cleanup(Info, OldStackSize);
798 }
799 private:
800 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
801 unsigned NewEnd = OldStackSize;
802 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
803 I != N; ++I) {
804 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
805 // Full-expression cleanup of a lifetime-extended temporary: nothing
806 // to do, just move this cleanup to the right place in the stack.
807 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
808 ++NewEnd;
809 } else {
810 // End the lifetime of the object.
811 Info.CleanupStack[I].endLifetime();
812 }
813 }
814 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
815 Info.CleanupStack.end());
816 }
817 };
818 typedef ScopeRAII<false> BlockScopeRAII;
819 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000820}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000821
Richard Smitha8105bc2012-01-06 16:39:00 +0000822bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
823 CheckSubobjectKind CSK) {
824 if (Invalid)
825 return false;
826 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000827 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000828 << CSK;
829 setInvalid();
830 return false;
831 }
832 return true;
833}
834
835void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
836 const Expr *E, uint64_t N) {
837 if (MostDerivedPathLength == Entries.size() && MostDerivedArraySize)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000838 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000839 << static_cast<int>(N) << /*array*/ 0
840 << static_cast<unsigned>(MostDerivedArraySize);
841 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000842 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000843 << static_cast<int>(N) << /*non-array*/ 1;
844 setInvalid();
845}
846
Richard Smithf6f003a2011-12-16 19:06:07 +0000847CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
848 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000849 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000850 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000851 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000852 Info.CurrentCall = this;
853 ++Info.CallStackDepth;
854}
855
856CallStackFrame::~CallStackFrame() {
857 assert(Info.CurrentCall == this && "calls retired out of order");
858 --Info.CallStackDepth;
859 Info.CurrentCall = Caller;
860}
861
Richard Smith08d6a2c2013-07-24 07:11:57 +0000862APValue &CallStackFrame::createTemporary(const void *Key,
863 bool IsLifetimeExtended) {
864 APValue &Result = Temporaries[Key];
865 assert(Result.isUninit() && "temporary created multiple times");
866 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
867 return Result;
868}
869
Richard Smith84401042013-06-03 05:03:02 +0000870static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000871
872void EvalInfo::addCallStack(unsigned Limit) {
873 // Determine which calls to skip, if any.
874 unsigned ActiveCalls = CallStackDepth - 1;
875 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
876 if (Limit && Limit < ActiveCalls) {
877 SkipStart = Limit / 2 + Limit % 2;
878 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000879 }
880
Richard Smithf6f003a2011-12-16 19:06:07 +0000881 // Walk the call stack and add the diagnostics.
882 unsigned CallIdx = 0;
883 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
884 Frame = Frame->Caller, ++CallIdx) {
885 // Skip this call?
886 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
887 if (CallIdx == SkipStart) {
888 // Note that we're skipping calls.
889 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
890 << unsigned(ActiveCalls - Limit);
891 }
892 continue;
893 }
894
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000895 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +0000896 llvm::raw_svector_ostream Out(Buffer);
897 describeCall(Frame, Out);
898 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
899 }
900}
901
902namespace {
John McCall93d91dc2010-05-07 17:22:02 +0000903 struct ComplexValue {
904 private:
905 bool IsInt;
906
907 public:
908 APSInt IntReal, IntImag;
909 APFloat FloatReal, FloatImag;
910
911 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
912
913 void makeComplexFloat() { IsInt = false; }
914 bool isComplexFloat() const { return !IsInt; }
915 APFloat &getComplexFloatReal() { return FloatReal; }
916 APFloat &getComplexFloatImag() { return FloatImag; }
917
918 void makeComplexInt() { IsInt = true; }
919 bool isComplexInt() const { return IsInt; }
920 APSInt &getComplexIntReal() { return IntReal; }
921 APSInt &getComplexIntImag() { return IntImag; }
922
Richard Smith2e312c82012-03-03 22:46:17 +0000923 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +0000924 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +0000925 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +0000926 else
Richard Smith2e312c82012-03-03 22:46:17 +0000927 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +0000928 }
Richard Smith2e312c82012-03-03 22:46:17 +0000929 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +0000930 assert(v.isComplexFloat() || v.isComplexInt());
931 if (v.isComplexFloat()) {
932 makeComplexFloat();
933 FloatReal = v.getComplexFloatReal();
934 FloatImag = v.getComplexFloatImag();
935 } else {
936 makeComplexInt();
937 IntReal = v.getComplexIntReal();
938 IntImag = v.getComplexIntImag();
939 }
940 }
John McCall93d91dc2010-05-07 17:22:02 +0000941 };
John McCall45d55e42010-05-07 21:00:08 +0000942
943 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +0000944 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +0000945 CharUnits Offset;
George Burgess IV3a03fab2015-09-04 21:28:13 +0000946 bool InvalidBase : 1;
947 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +0000948 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +0000949
Richard Smithce40ad62011-11-12 22:28:03 +0000950 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +0000951 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +0000952 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +0000953 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +0000954 SubobjectDesignator &getLValueDesignator() { return Designator; }
955 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +0000956
Richard Smith2e312c82012-03-03 22:46:17 +0000957 void moveInto(APValue &V) const {
958 if (Designator.Invalid)
959 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
960 else
961 V = APValue(Base, Offset, Designator.Entries,
962 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +0000963 }
Richard Smith2e312c82012-03-03 22:46:17 +0000964 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +0000965 assert(V.isLValue());
966 Base = V.getLValueBase();
967 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +0000968 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +0000969 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +0000970 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +0000971 }
972
George Burgess IV3a03fab2015-09-04 21:28:13 +0000973 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
Richard Smithce40ad62011-11-12 22:28:03 +0000974 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +0000975 Offset = CharUnits::Zero();
George Burgess IV3a03fab2015-09-04 21:28:13 +0000976 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +0000977 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +0000978 Designator = SubobjectDesignator(getType(B));
979 }
980
George Burgess IV3a03fab2015-09-04 21:28:13 +0000981 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
982 set(B, I, true);
983 }
984
Richard Smitha8105bc2012-01-06 16:39:00 +0000985 // Check that this LValue is not based on a null pointer. If it is, produce
986 // a diagnostic and mark the designator as invalid.
987 bool checkNullPointer(EvalInfo &Info, const Expr *E,
988 CheckSubobjectKind CSK) {
989 if (Designator.Invalid)
990 return false;
991 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000992 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000993 << CSK;
994 Designator.setInvalid();
995 return false;
996 }
997 return true;
998 }
999
1000 // Check this LValue refers to an object. If not, set the designator to be
1001 // invalid and emit a diagnostic.
1002 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001003 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001004 Designator.checkSubobject(Info, E, CSK);
1005 }
1006
1007 void addDecl(EvalInfo &Info, const Expr *E,
1008 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001009 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1010 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001011 }
1012 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001013 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1014 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001015 }
Richard Smith66c96992012-02-18 22:04:06 +00001016 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001017 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1018 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001019 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001020 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001021 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +00001022 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +00001023 }
John McCall45d55e42010-05-07 21:00:08 +00001024 };
Richard Smith027bf112011-11-17 22:56:20 +00001025
1026 struct MemberPtr {
1027 MemberPtr() {}
1028 explicit MemberPtr(const ValueDecl *Decl) :
1029 DeclAndIsDerivedMember(Decl, false), Path() {}
1030
1031 /// The member or (direct or indirect) field referred to by this member
1032 /// pointer, or 0 if this is a null member pointer.
1033 const ValueDecl *getDecl() const {
1034 return DeclAndIsDerivedMember.getPointer();
1035 }
1036 /// Is this actually a member of some type derived from the relevant class?
1037 bool isDerivedMember() const {
1038 return DeclAndIsDerivedMember.getInt();
1039 }
1040 /// Get the class which the declaration actually lives in.
1041 const CXXRecordDecl *getContainingRecord() const {
1042 return cast<CXXRecordDecl>(
1043 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1044 }
1045
Richard Smith2e312c82012-03-03 22:46:17 +00001046 void moveInto(APValue &V) const {
1047 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001048 }
Richard Smith2e312c82012-03-03 22:46:17 +00001049 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001050 assert(V.isMemberPointer());
1051 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1052 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1053 Path.clear();
1054 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1055 Path.insert(Path.end(), P.begin(), P.end());
1056 }
1057
1058 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1059 /// whether the member is a member of some class derived from the class type
1060 /// of the member pointer.
1061 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1062 /// Path - The path of base/derived classes from the member declaration's
1063 /// class (exclusive) to the class type of the member pointer (inclusive).
1064 SmallVector<const CXXRecordDecl*, 4> Path;
1065
1066 /// Perform a cast towards the class of the Decl (either up or down the
1067 /// hierarchy).
1068 bool castBack(const CXXRecordDecl *Class) {
1069 assert(!Path.empty());
1070 const CXXRecordDecl *Expected;
1071 if (Path.size() >= 2)
1072 Expected = Path[Path.size() - 2];
1073 else
1074 Expected = getContainingRecord();
1075 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1076 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1077 // if B does not contain the original member and is not a base or
1078 // derived class of the class containing the original member, the result
1079 // of the cast is undefined.
1080 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1081 // (D::*). We consider that to be a language defect.
1082 return false;
1083 }
1084 Path.pop_back();
1085 return true;
1086 }
1087 /// Perform a base-to-derived member pointer cast.
1088 bool castToDerived(const CXXRecordDecl *Derived) {
1089 if (!getDecl())
1090 return true;
1091 if (!isDerivedMember()) {
1092 Path.push_back(Derived);
1093 return true;
1094 }
1095 if (!castBack(Derived))
1096 return false;
1097 if (Path.empty())
1098 DeclAndIsDerivedMember.setInt(false);
1099 return true;
1100 }
1101 /// Perform a derived-to-base member pointer cast.
1102 bool castToBase(const CXXRecordDecl *Base) {
1103 if (!getDecl())
1104 return true;
1105 if (Path.empty())
1106 DeclAndIsDerivedMember.setInt(true);
1107 if (isDerivedMember()) {
1108 Path.push_back(Base);
1109 return true;
1110 }
1111 return castBack(Base);
1112 }
1113 };
Richard Smith357362d2011-12-13 06:39:58 +00001114
Richard Smith7bb00672012-02-01 01:42:44 +00001115 /// Compare two member pointers, which are assumed to be of the same type.
1116 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1117 if (!LHS.getDecl() || !RHS.getDecl())
1118 return !LHS.getDecl() && !RHS.getDecl();
1119 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1120 return false;
1121 return LHS.Path == RHS.Path;
1122 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001123}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001124
Richard Smith2e312c82012-03-03 22:46:17 +00001125static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001126static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1127 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001128 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001129static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1130static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001131static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1132 EvalInfo &Info);
1133static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
Chris Lattnercdf34e72008-07-11 22:52:41 +00001134static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001135static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001136 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001137static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001138static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001139static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
Chris Lattner05706e882008-07-11 18:11:29 +00001140
1141//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001142// Misc utilities
1143//===----------------------------------------------------------------------===//
1144
Richard Smith84401042013-06-03 05:03:02 +00001145/// Produce a string describing the given constexpr call.
1146static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1147 unsigned ArgIndex = 0;
1148 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1149 !isa<CXXConstructorDecl>(Frame->Callee) &&
1150 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1151
1152 if (!IsMemberCall)
1153 Out << *Frame->Callee << '(';
1154
1155 if (Frame->This && IsMemberCall) {
1156 APValue Val;
1157 Frame->This->moveInto(Val);
1158 Val.printPretty(Out, Frame->Info.Ctx,
1159 Frame->This->Designator.MostDerivedType);
1160 // FIXME: Add parens around Val if needed.
1161 Out << "->" << *Frame->Callee << '(';
1162 IsMemberCall = false;
1163 }
1164
1165 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1166 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1167 if (ArgIndex > (unsigned)IsMemberCall)
1168 Out << ", ";
1169
1170 const ParmVarDecl *Param = *I;
1171 const APValue &Arg = Frame->Arguments[ArgIndex];
1172 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1173
1174 if (ArgIndex == 0 && IsMemberCall)
1175 Out << "->" << *Frame->Callee << '(';
1176 }
1177
1178 Out << ')';
1179}
1180
Richard Smithd9f663b2013-04-22 15:31:51 +00001181/// Evaluate an expression to see if it had side-effects, and discard its
1182/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001183/// \return \c true if the caller should keep evaluating.
1184static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001185 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001186 if (!Evaluate(Scratch, Info, E))
1187 // We don't need the value, but we might have skipped a side effect here.
1188 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001189 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001190}
1191
Richard Smith861b5b52013-05-07 23:34:45 +00001192/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1193/// return its existing value.
1194static int64_t getExtValue(const APSInt &Value) {
1195 return Value.isSigned() ? Value.getSExtValue()
1196 : static_cast<int64_t>(Value.getZExtValue());
1197}
1198
Richard Smithd62306a2011-11-10 06:34:14 +00001199/// Should this call expression be treated as a string literal?
1200static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001201 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001202 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1203 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1204}
1205
Richard Smithce40ad62011-11-12 22:28:03 +00001206static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001207 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1208 // constant expression of pointer type that evaluates to...
1209
1210 // ... a null pointer value, or a prvalue core constant expression of type
1211 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001212 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001213
Richard Smithce40ad62011-11-12 22:28:03 +00001214 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1215 // ... the address of an object with static storage duration,
1216 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1217 return VD->hasGlobalStorage();
1218 // ... the address of a function,
1219 return isa<FunctionDecl>(D);
1220 }
1221
1222 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001223 switch (E->getStmtClass()) {
1224 default:
1225 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001226 case Expr::CompoundLiteralExprClass: {
1227 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1228 return CLE->isFileScope() && CLE->isLValue();
1229 }
Richard Smithe6c01442013-06-05 00:46:14 +00001230 case Expr::MaterializeTemporaryExprClass:
1231 // A materialized temporary might have been lifetime-extended to static
1232 // storage duration.
1233 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001234 // A string literal has static storage duration.
1235 case Expr::StringLiteralClass:
1236 case Expr::PredefinedExprClass:
1237 case Expr::ObjCStringLiteralClass:
1238 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001239 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001240 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001241 return true;
1242 case Expr::CallExprClass:
1243 return IsStringLiteralCall(cast<CallExpr>(E));
1244 // For GCC compatibility, &&label has static storage duration.
1245 case Expr::AddrLabelExprClass:
1246 return true;
1247 // A Block literal expression may be used as the initialization value for
1248 // Block variables at global or local static scope.
1249 case Expr::BlockExprClass:
1250 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001251 case Expr::ImplicitValueInitExprClass:
1252 // FIXME:
1253 // We can never form an lvalue with an implicit value initialization as its
1254 // base through expression evaluation, so these only appear in one case: the
1255 // implicit variable declaration we invent when checking whether a constexpr
1256 // constructor can produce a constant expression. We must assume that such
1257 // an expression might be a global lvalue.
1258 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001259 }
John McCall95007602010-05-10 23:27:23 +00001260}
1261
Richard Smithb228a862012-02-15 02:18:13 +00001262static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1263 assert(Base && "no location for a null lvalue");
1264 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1265 if (VD)
1266 Info.Note(VD->getLocation(), diag::note_declared_at);
1267 else
Ted Kremenek28831752012-08-23 20:46:57 +00001268 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001269 diag::note_constexpr_temporary_here);
1270}
1271
Richard Smith80815602011-11-07 05:07:52 +00001272/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001273/// value for an address or reference constant expression. Return true if we
1274/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001275static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1276 QualType Type, const LValue &LVal) {
1277 bool IsReferenceType = Type->isReferenceType();
1278
Richard Smith357362d2011-12-13 06:39:58 +00001279 APValue::LValueBase Base = LVal.getLValueBase();
1280 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1281
Richard Smith0dea49e2012-02-18 04:58:18 +00001282 // Check that the object is a global. Note that the fake 'this' object we
1283 // manufacture when checking potential constant expressions is conservatively
1284 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001285 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001286 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001287 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001288 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1289 << IsReferenceType << !Designator.Entries.empty()
1290 << !!VD << VD;
1291 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001292 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001293 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001294 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001295 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001296 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001297 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001298 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001299 LVal.getLValueCallIndex() == 0) &&
1300 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001301
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001302 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1303 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001304 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001305 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001306 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001307
Hans Wennborg82dd8772014-06-25 22:19:48 +00001308 // A dllimport variable never acts like a constant.
1309 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001310 return false;
1311 }
1312 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1313 // __declspec(dllimport) must be handled very carefully:
1314 // We must never initialize an expression with the thunk in C++.
1315 // Doing otherwise would allow the same id-expression to yield
1316 // different addresses for the same function in different translation
1317 // units. However, this means that we must dynamically initialize the
1318 // expression with the contents of the import address table at runtime.
1319 //
1320 // The C language has no notion of ODR; furthermore, it has no notion of
1321 // dynamic initialization. This means that we are permitted to
1322 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001323 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001324 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001325 }
1326 }
1327
Richard Smitha8105bc2012-01-06 16:39:00 +00001328 // Allow address constant expressions to be past-the-end pointers. This is
1329 // an extension: the standard requires them to point to an object.
1330 if (!IsReferenceType)
1331 return true;
1332
1333 // A reference constant expression must refer to an object.
1334 if (!Base) {
1335 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001336 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001337 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001338 }
1339
Richard Smith357362d2011-12-13 06:39:58 +00001340 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001341 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001342 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001343 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001344 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001345 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001346 }
1347
Richard Smith80815602011-11-07 05:07:52 +00001348 return true;
1349}
1350
Richard Smithfddd3842011-12-30 21:15:51 +00001351/// Check that this core constant expression is of literal type, and if not,
1352/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001353static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001354 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001355 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001356 return true;
1357
Richard Smith7525ff62013-05-09 07:14:00 +00001358 // C++1y: A constant initializer for an object o [...] may also invoke
1359 // constexpr constructors for o and its subobjects even if those objects
1360 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001361 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001362 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001363 return true;
1364
Richard Smithfddd3842011-12-30 21:15:51 +00001365 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001366 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001367 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001368 << E->getType();
1369 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001370 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001371 return false;
1372}
1373
Richard Smith0b0a0b62011-10-29 20:57:55 +00001374/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001375/// constant expression. If not, report an appropriate diagnostic. Does not
1376/// check that the expression is of literal type.
1377static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1378 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001379 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001380 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1381 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001382 return false;
1383 }
1384
Richard Smith77be48a2014-07-31 06:31:19 +00001385 // We allow _Atomic(T) to be initialized from anything that T can be
1386 // initialized from.
1387 if (const AtomicType *AT = Type->getAs<AtomicType>())
1388 Type = AT->getValueType();
1389
Richard Smithb228a862012-02-15 02:18:13 +00001390 // Core issue 1454: For a literal constant expression of array or class type,
1391 // each subobject of its value shall have been initialized by a constant
1392 // expression.
1393 if (Value.isArray()) {
1394 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1395 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1396 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1397 Value.getArrayInitializedElt(I)))
1398 return false;
1399 }
1400 if (!Value.hasArrayFiller())
1401 return true;
1402 return CheckConstantExpression(Info, DiagLoc, EltTy,
1403 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001404 }
Richard Smithb228a862012-02-15 02:18:13 +00001405 if (Value.isUnion() && Value.getUnionField()) {
1406 return CheckConstantExpression(Info, DiagLoc,
1407 Value.getUnionField()->getType(),
1408 Value.getUnionValue());
1409 }
1410 if (Value.isStruct()) {
1411 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1412 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1413 unsigned BaseIndex = 0;
1414 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1415 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1416 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1417 Value.getStructBase(BaseIndex)))
1418 return false;
1419 }
1420 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001421 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001422 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1423 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001424 return false;
1425 }
1426 }
1427
1428 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001429 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001430 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001431 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1432 }
1433
1434 // Everything else is fine.
1435 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001436}
1437
Benjamin Kramer8407df72015-03-09 16:47:52 +00001438static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001439 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001440}
1441
1442static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001443 if (Value.CallIndex)
1444 return false;
1445 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1446 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001447}
1448
Richard Smithcecf1842011-11-01 21:06:14 +00001449static bool IsWeakLValue(const LValue &Value) {
1450 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001451 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001452}
1453
David Majnemerb5116032014-12-09 23:32:34 +00001454static bool isZeroSized(const LValue &Value) {
1455 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001456 if (Decl && isa<VarDecl>(Decl)) {
1457 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001458 if (Ty->isArrayType())
1459 return Ty->isIncompleteType() ||
1460 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001461 }
1462 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001463}
1464
Richard Smith2e312c82012-03-03 22:46:17 +00001465static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001466 // A null base expression indicates a null pointer. These are always
1467 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001468 if (!Value.getLValueBase()) {
1469 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001470 return true;
1471 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001472
Richard Smith027bf112011-11-17 22:56:20 +00001473 // We have a non-null base. These are generally known to be true, but if it's
1474 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001475 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001476 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001477 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001478}
1479
Richard Smith2e312c82012-03-03 22:46:17 +00001480static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001481 switch (Val.getKind()) {
1482 case APValue::Uninitialized:
1483 return false;
1484 case APValue::Int:
1485 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001486 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001487 case APValue::Float:
1488 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001489 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001490 case APValue::ComplexInt:
1491 Result = Val.getComplexIntReal().getBoolValue() ||
1492 Val.getComplexIntImag().getBoolValue();
1493 return true;
1494 case APValue::ComplexFloat:
1495 Result = !Val.getComplexFloatReal().isZero() ||
1496 !Val.getComplexFloatImag().isZero();
1497 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001498 case APValue::LValue:
1499 return EvalPointerValueAsBool(Val, Result);
1500 case APValue::MemberPointer:
1501 Result = Val.getMemberPointerDecl();
1502 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001503 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001504 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001505 case APValue::Struct:
1506 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001507 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001508 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001509 }
1510
Richard Smith11562c52011-10-28 17:51:58 +00001511 llvm_unreachable("unknown APValue kind");
1512}
1513
1514static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1515 EvalInfo &Info) {
1516 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001517 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001518 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001519 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001520 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001521}
1522
Richard Smith357362d2011-12-13 06:39:58 +00001523template<typename T>
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001524static void HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001525 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001526 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001527 << SrcValue << DestType;
Richard Smith357362d2011-12-13 06:39:58 +00001528}
1529
1530static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1531 QualType SrcType, const APFloat &Value,
1532 QualType DestType, APSInt &Result) {
1533 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001534 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001535 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001536
Richard Smith357362d2011-12-13 06:39:58 +00001537 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001538 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001539 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1540 & APFloat::opInvalidOp)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001541 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001542 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001543}
1544
Richard Smith357362d2011-12-13 06:39:58 +00001545static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1546 QualType SrcType, QualType DestType,
1547 APFloat &Result) {
1548 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001549 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001550 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1551 APFloat::rmNearestTiesToEven, &ignored)
1552 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001553 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001554 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001555}
1556
Richard Smith911e1422012-01-30 22:27:01 +00001557static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1558 QualType DestType, QualType SrcType,
1559 APSInt &Value) {
1560 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001561 APSInt Result = Value;
1562 // Figure out if this is a truncate, extend or noop cast.
1563 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001564 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001565 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001566 return Result;
1567}
1568
Richard Smith357362d2011-12-13 06:39:58 +00001569static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1570 QualType SrcType, const APSInt &Value,
1571 QualType DestType, APFloat &Result) {
1572 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1573 if (Result.convertFromAPInt(Value, Value.isSigned(),
1574 APFloat::rmNearestTiesToEven)
1575 & APFloat::opOverflow)
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001576 HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001577 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001578}
1579
Richard Smith49ca8aa2013-08-06 07:09:20 +00001580static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1581 APValue &Value, const FieldDecl *FD) {
1582 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1583
1584 if (!Value.isInt()) {
1585 // Trying to store a pointer-cast-to-integer into a bitfield.
1586 // FIXME: In this case, we should provide the diagnostic for casting
1587 // a pointer to an integer.
1588 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1589 Info.Diag(E);
1590 return false;
1591 }
1592
1593 APSInt &Int = Value.getInt();
1594 unsigned OldBitWidth = Int.getBitWidth();
1595 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1596 if (NewBitWidth < OldBitWidth)
1597 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1598 return true;
1599}
1600
Eli Friedman803acb32011-12-22 03:51:45 +00001601static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1602 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001603 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001604 if (!Evaluate(SVal, Info, E))
1605 return false;
1606 if (SVal.isInt()) {
1607 Res = SVal.getInt();
1608 return true;
1609 }
1610 if (SVal.isFloat()) {
1611 Res = SVal.getFloat().bitcastToAPInt();
1612 return true;
1613 }
1614 if (SVal.isVector()) {
1615 QualType VecTy = E->getType();
1616 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1617 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1618 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1619 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1620 Res = llvm::APInt::getNullValue(VecSize);
1621 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1622 APValue &Elt = SVal.getVectorElt(i);
1623 llvm::APInt EltAsInt;
1624 if (Elt.isInt()) {
1625 EltAsInt = Elt.getInt();
1626 } else if (Elt.isFloat()) {
1627 EltAsInt = Elt.getFloat().bitcastToAPInt();
1628 } else {
1629 // Don't try to handle vectors of anything other than int or float
1630 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001631 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001632 return false;
1633 }
1634 unsigned BaseEltSize = EltAsInt.getBitWidth();
1635 if (BigEndian)
1636 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1637 else
1638 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1639 }
1640 return true;
1641 }
1642 // Give up if the input isn't an int, float, or vector. For example, we
1643 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001644 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001645 return false;
1646}
1647
Richard Smith43e77732013-05-07 04:50:00 +00001648/// Perform the given integer operation, which is known to need at most BitWidth
1649/// bits, and check for overflow in the original type (if that type was not an
1650/// unsigned type).
1651template<typename Operation>
1652static APSInt CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1653 const APSInt &LHS, const APSInt &RHS,
1654 unsigned BitWidth, Operation Op) {
1655 if (LHS.isUnsigned())
1656 return Op(LHS, RHS);
1657
1658 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
1659 APSInt Result = Value.trunc(LHS.getBitWidth());
1660 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001661 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001662 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
1663 diag::warn_integer_constant_overflow)
1664 << Result.toString(10) << E->getType();
1665 else
1666 HandleOverflow(Info, E, Value, E->getType());
1667 }
1668 return Result;
1669}
1670
1671/// Perform the given binary integer operation.
1672static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1673 BinaryOperatorKind Opcode, APSInt RHS,
1674 APSInt &Result) {
1675 switch (Opcode) {
1676 default:
1677 Info.Diag(E);
1678 return false;
1679 case BO_Mul:
1680 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1681 std::multiplies<APSInt>());
1682 return true;
1683 case BO_Add:
1684 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1685 std::plus<APSInt>());
1686 return true;
1687 case BO_Sub:
1688 Result = CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1689 std::minus<APSInt>());
1690 return true;
1691 case BO_And: Result = LHS & RHS; return true;
1692 case BO_Xor: Result = LHS ^ RHS; return true;
1693 case BO_Or: Result = LHS | RHS; return true;
1694 case BO_Div:
1695 case BO_Rem:
1696 if (RHS == 0) {
1697 Info.Diag(E, diag::note_expr_divide_by_zero);
1698 return false;
1699 }
1700 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1.
1701 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1702 LHS.isSigned() && LHS.isMinSignedValue())
1703 HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1), E->getType());
1704 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1705 return true;
1706 case BO_Shl: {
1707 if (Info.getLangOpts().OpenCL)
1708 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1709 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1710 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1711 RHS.isUnsigned());
1712 else if (RHS.isSigned() && RHS.isNegative()) {
1713 // During constant-folding, a negative shift is an opposite shift. Such
1714 // a shift is not a constant expression.
1715 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1716 RHS = -RHS;
1717 goto shift_right;
1718 }
1719 shift_left:
1720 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1721 // the shifted type.
1722 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1723 if (SA != RHS) {
1724 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1725 << RHS << E->getType() << LHS.getBitWidth();
1726 } else if (LHS.isSigned()) {
1727 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1728 // operand, and must not overflow the corresponding unsigned type.
1729 if (LHS.isNegative())
1730 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1731 else if (LHS.countLeadingZeros() < SA)
1732 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1733 }
1734 Result = LHS << SA;
1735 return true;
1736 }
1737 case BO_Shr: {
1738 if (Info.getLangOpts().OpenCL)
1739 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1740 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1741 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1742 RHS.isUnsigned());
1743 else if (RHS.isSigned() && RHS.isNegative()) {
1744 // During constant-folding, a negative shift is an opposite shift. Such a
1745 // shift is not a constant expression.
1746 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1747 RHS = -RHS;
1748 goto shift_left;
1749 }
1750 shift_right:
1751 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1752 // shifted type.
1753 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1754 if (SA != RHS)
1755 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1756 << RHS << E->getType() << LHS.getBitWidth();
1757 Result = LHS >> SA;
1758 return true;
1759 }
1760
1761 case BO_LT: Result = LHS < RHS; return true;
1762 case BO_GT: Result = LHS > RHS; return true;
1763 case BO_LE: Result = LHS <= RHS; return true;
1764 case BO_GE: Result = LHS >= RHS; return true;
1765 case BO_EQ: Result = LHS == RHS; return true;
1766 case BO_NE: Result = LHS != RHS; return true;
1767 }
1768}
1769
Richard Smith861b5b52013-05-07 23:34:45 +00001770/// Perform the given binary floating-point operation, in-place, on LHS.
1771static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1772 APFloat &LHS, BinaryOperatorKind Opcode,
1773 const APFloat &RHS) {
1774 switch (Opcode) {
1775 default:
1776 Info.Diag(E);
1777 return false;
1778 case BO_Mul:
1779 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1780 break;
1781 case BO_Add:
1782 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1783 break;
1784 case BO_Sub:
1785 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1786 break;
1787 case BO_Div:
1788 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1789 break;
1790 }
1791
1792 if (LHS.isInfinity() || LHS.isNaN())
1793 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
1794 return true;
1795}
1796
Richard Smitha8105bc2012-01-06 16:39:00 +00001797/// Cast an lvalue referring to a base subobject to a derived class, by
1798/// truncating the lvalue's path to the given length.
1799static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1800 const RecordDecl *TruncatedType,
1801 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001802 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001803
1804 // Check we actually point to a derived class object.
1805 if (TruncatedElements == D.Entries.size())
1806 return true;
1807 assert(TruncatedElements >= D.MostDerivedPathLength &&
1808 "not casting to a derived class");
1809 if (!Result.checkSubobject(Info, E, CSK_Derived))
1810 return false;
1811
1812 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001813 const RecordDecl *RD = TruncatedType;
1814 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001815 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001816 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1817 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001818 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001819 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001820 else
Richard Smithd62306a2011-11-10 06:34:14 +00001821 Result.Offset -= Layout.getBaseClassOffset(Base);
1822 RD = Base;
1823 }
Richard Smith027bf112011-11-17 22:56:20 +00001824 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001825 return true;
1826}
1827
John McCalld7bca762012-05-01 00:38:49 +00001828static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001829 const CXXRecordDecl *Derived,
1830 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001831 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001832 if (!RL) {
1833 if (Derived->isInvalidDecl()) return false;
1834 RL = &Info.Ctx.getASTRecordLayout(Derived);
1835 }
1836
Richard Smithd62306a2011-11-10 06:34:14 +00001837 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001838 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001839 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001840}
1841
Richard Smitha8105bc2012-01-06 16:39:00 +00001842static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001843 const CXXRecordDecl *DerivedDecl,
1844 const CXXBaseSpecifier *Base) {
1845 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1846
John McCalld7bca762012-05-01 00:38:49 +00001847 if (!Base->isVirtual())
1848 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001849
Richard Smitha8105bc2012-01-06 16:39:00 +00001850 SubobjectDesignator &D = Obj.Designator;
1851 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001852 return false;
1853
Richard Smitha8105bc2012-01-06 16:39:00 +00001854 // Extract most-derived object and corresponding type.
1855 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1856 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1857 return false;
1858
1859 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001860 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001861 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1862 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001863 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001864 return true;
1865}
1866
Richard Smith84401042013-06-03 05:03:02 +00001867static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1868 QualType Type, LValue &Result) {
1869 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1870 PathE = E->path_end();
1871 PathI != PathE; ++PathI) {
1872 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1873 *PathI))
1874 return false;
1875 Type = (*PathI)->getType();
1876 }
1877 return true;
1878}
1879
Richard Smithd62306a2011-11-10 06:34:14 +00001880/// Update LVal to refer to the given field, which must be a member of the type
1881/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00001882static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00001883 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00001884 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001885 if (!RL) {
1886 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001887 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00001888 }
Richard Smithd62306a2011-11-10 06:34:14 +00001889
1890 unsigned I = FD->getFieldIndex();
1891 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00001892 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00001893 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001894}
1895
Richard Smith1b78b3d2012-01-25 22:15:11 +00001896/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00001897static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00001898 LValue &LVal,
1899 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00001900 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00001901 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00001902 return false;
1903 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00001904}
1905
Richard Smithd62306a2011-11-10 06:34:14 +00001906/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00001907static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
1908 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00001909 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
1910 // extension.
1911 if (Type->isVoidType() || Type->isFunctionType()) {
1912 Size = CharUnits::One();
1913 return true;
1914 }
1915
1916 if (!Type->isConstantSizeType()) {
1917 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00001918 // FIXME: Better diagnostic.
1919 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00001920 return false;
1921 }
1922
1923 Size = Info.Ctx.getTypeSizeInChars(Type);
1924 return true;
1925}
1926
1927/// Update a pointer value to model pointer arithmetic.
1928/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00001929/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00001930/// \param LVal - The pointer value to be updated.
1931/// \param EltTy - The pointee type represented by LVal.
1932/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00001933static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
1934 LValue &LVal, QualType EltTy,
1935 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00001936 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00001937 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00001938 return false;
1939
1940 // Compute the new offset in the appropriate width.
1941 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00001942 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00001943 return true;
1944}
1945
Richard Smith66c96992012-02-18 22:04:06 +00001946/// Update an lvalue to refer to a component of a complex number.
1947/// \param Info - Information about the ongoing evaluation.
1948/// \param LVal - The lvalue to be updated.
1949/// \param EltTy - The complex number's component type.
1950/// \param Imag - False for the real component, true for the imaginary.
1951static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
1952 LValue &LVal, QualType EltTy,
1953 bool Imag) {
1954 if (Imag) {
1955 CharUnits SizeOfComponent;
1956 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
1957 return false;
1958 LVal.Offset += SizeOfComponent;
1959 }
1960 LVal.addComplex(Info, E, EltTy, Imag);
1961 return true;
1962}
1963
Richard Smith27908702011-10-24 17:54:18 +00001964/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00001965///
1966/// \param Info Information about the ongoing evaluation.
1967/// \param E An expression to be used when printing diagnostics.
1968/// \param VD The variable whose initializer should be obtained.
1969/// \param Frame The frame in which the variable was created. Must be null
1970/// if this variable is not local to the evaluation.
1971/// \param Result Filled in with a pointer to the value of the variable.
1972static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
1973 const VarDecl *VD, CallStackFrame *Frame,
1974 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00001975 // If this is a parameter to an active constexpr function call, perform
1976 // argument substitution.
1977 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00001978 // Assume arguments of a potential constant expression are unknown
1979 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00001980 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00001981 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001982 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001983 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00001984 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001985 }
Richard Smith3229b742013-05-05 21:17:10 +00001986 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00001987 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00001988 }
Richard Smith27908702011-10-24 17:54:18 +00001989
Richard Smithd9f663b2013-04-22 15:31:51 +00001990 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00001991 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00001992 Result = Frame->getTemporary(VD);
1993 assert(Result && "missing value for local variable");
1994 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001995 }
1996
Richard Smithd0b4dd62011-12-19 06:19:21 +00001997 // Dig out the initializer, and use the declaration which it's attached to.
1998 const Expr *Init = VD->getAnyInitializer(VD);
1999 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002000 // If we're checking a potential constant expression, the variable could be
2001 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002002 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00002003 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002004 return false;
2005 }
2006
Richard Smithd62306a2011-11-10 06:34:14 +00002007 // If we're currently evaluating the initializer of this declaration, use that
2008 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002009 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002010 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002011 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002012 }
2013
Richard Smithcecf1842011-11-01 21:06:14 +00002014 // Never evaluate the initializer of a weak variable. We can't be sure that
2015 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002016 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002017 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002018 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002019 }
Richard Smithcecf1842011-11-01 21:06:14 +00002020
Richard Smithd0b4dd62011-12-19 06:19:21 +00002021 // Check that we can fold the initializer. In C++, we will have already done
2022 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002023 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002024 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002025 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002026 Notes.size() + 1) << VD;
2027 Info.Note(VD->getLocation(), diag::note_declared_at);
2028 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002029 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002030 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002031 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002032 Notes.size() + 1) << VD;
2033 Info.Note(VD->getLocation(), diag::note_declared_at);
2034 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002035 }
Richard Smith27908702011-10-24 17:54:18 +00002036
Richard Smith3229b742013-05-05 21:17:10 +00002037 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002038 return true;
Richard Smith27908702011-10-24 17:54:18 +00002039}
2040
Richard Smith11562c52011-10-28 17:51:58 +00002041static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002042 Qualifiers Quals = T.getQualifiers();
2043 return Quals.hasConst() && !Quals.hasVolatile();
2044}
2045
Richard Smithe97cbd72011-11-11 04:05:33 +00002046/// Get the base index of the given base class within an APValue representing
2047/// the given derived class.
2048static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2049 const CXXRecordDecl *Base) {
2050 Base = Base->getCanonicalDecl();
2051 unsigned Index = 0;
2052 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2053 E = Derived->bases_end(); I != E; ++I, ++Index) {
2054 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2055 return Index;
2056 }
2057
2058 llvm_unreachable("base class missing from derived class's bases list");
2059}
2060
Richard Smith3da88fa2013-04-26 14:36:30 +00002061/// Extract the value of a character from a string literal.
2062static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2063 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002064 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2065 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2066 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002067 const StringLiteral *S = cast<StringLiteral>(Lit);
2068 const ConstantArrayType *CAT =
2069 Info.Ctx.getAsConstantArrayType(S->getType());
2070 assert(CAT && "string literal isn't an array");
2071 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002072 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002073
2074 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002075 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002076 if (Index < S->getLength())
2077 Value = S->getCodeUnit(Index);
2078 return Value;
2079}
2080
Richard Smith3da88fa2013-04-26 14:36:30 +00002081// Expand a string literal into an array of characters.
2082static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2083 APValue &Result) {
2084 const StringLiteral *S = cast<StringLiteral>(Lit);
2085 const ConstantArrayType *CAT =
2086 Info.Ctx.getAsConstantArrayType(S->getType());
2087 assert(CAT && "string literal isn't an array");
2088 QualType CharType = CAT->getElementType();
2089 assert(CharType->isIntegerType() && "unexpected character type");
2090
2091 unsigned Elts = CAT->getSize().getZExtValue();
2092 Result = APValue(APValue::UninitArray(),
2093 std::min(S->getLength(), Elts), Elts);
2094 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2095 CharType->isUnsignedIntegerType());
2096 if (Result.hasArrayFiller())
2097 Result.getArrayFiller() = APValue(Value);
2098 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2099 Value = S->getCodeUnit(I);
2100 Result.getArrayInitializedElt(I) = APValue(Value);
2101 }
2102}
2103
2104// Expand an array so that it has more than Index filled elements.
2105static void expandArray(APValue &Array, unsigned Index) {
2106 unsigned Size = Array.getArraySize();
2107 assert(Index < Size);
2108
2109 // Always at least double the number of elements for which we store a value.
2110 unsigned OldElts = Array.getArrayInitializedElts();
2111 unsigned NewElts = std::max(Index+1, OldElts * 2);
2112 NewElts = std::min(Size, std::max(NewElts, 8u));
2113
2114 // Copy the data across.
2115 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2116 for (unsigned I = 0; I != OldElts; ++I)
2117 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2118 for (unsigned I = OldElts; I != NewElts; ++I)
2119 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2120 if (NewValue.hasArrayFiller())
2121 NewValue.getArrayFiller() = Array.getArrayFiller();
2122 Array.swap(NewValue);
2123}
2124
Richard Smithb01fe402014-09-16 01:24:02 +00002125/// Determine whether a type would actually be read by an lvalue-to-rvalue
2126/// conversion. If it's of class type, we may assume that the copy operation
2127/// is trivial. Note that this is never true for a union type with fields
2128/// (because the copy always "reads" the active member) and always true for
2129/// a non-class type.
2130static bool isReadByLvalueToRvalueConversion(QualType T) {
2131 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2132 if (!RD || (RD->isUnion() && !RD->field_empty()))
2133 return true;
2134 if (RD->isEmpty())
2135 return false;
2136
2137 for (auto *Field : RD->fields())
2138 if (isReadByLvalueToRvalueConversion(Field->getType()))
2139 return true;
2140
2141 for (auto &BaseSpec : RD->bases())
2142 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2143 return true;
2144
2145 return false;
2146}
2147
2148/// Diagnose an attempt to read from any unreadable field within the specified
2149/// type, which might be a class type.
2150static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2151 QualType T) {
2152 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2153 if (!RD)
2154 return false;
2155
2156 if (!RD->hasMutableFields())
2157 return false;
2158
2159 for (auto *Field : RD->fields()) {
2160 // If we're actually going to read this field in some way, then it can't
2161 // be mutable. If we're in a union, then assigning to a mutable field
2162 // (even an empty one) can change the active member, so that's not OK.
2163 // FIXME: Add core issue number for the union case.
2164 if (Field->isMutable() &&
2165 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2166 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2167 Info.Note(Field->getLocation(), diag::note_declared_at);
2168 return true;
2169 }
2170
2171 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2172 return true;
2173 }
2174
2175 for (auto &BaseSpec : RD->bases())
2176 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2177 return true;
2178
2179 // All mutable fields were empty, and thus not actually read.
2180 return false;
2181}
2182
Richard Smith861b5b52013-05-07 23:34:45 +00002183/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002184enum AccessKinds {
2185 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002186 AK_Assign,
2187 AK_Increment,
2188 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002189};
2190
Richard Smith3229b742013-05-05 21:17:10 +00002191/// A handle to a complete object (an object that is not a subobject of
2192/// another object).
2193struct CompleteObject {
2194 /// The value of the complete object.
2195 APValue *Value;
2196 /// The type of the complete object.
2197 QualType Type;
2198
Craig Topper36250ad2014-05-12 05:36:57 +00002199 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002200 CompleteObject(APValue *Value, QualType Type)
2201 : Value(Value), Type(Type) {
2202 assert(Value && "missing value for complete object");
2203 }
2204
Aaron Ballman67347662015-02-15 22:00:28 +00002205 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002206};
2207
Richard Smith3da88fa2013-04-26 14:36:30 +00002208/// Find the designated sub-object of an rvalue.
2209template<typename SubobjectHandler>
2210typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002211findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002212 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002213 if (Sub.Invalid)
2214 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002215 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002216 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002217 if (Info.getLangOpts().CPlusPlus11)
2218 Info.Diag(E, diag::note_constexpr_access_past_end)
2219 << handler.AccessKind;
2220 else
2221 Info.Diag(E);
2222 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002223 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002224
Richard Smith3229b742013-05-05 21:17:10 +00002225 APValue *O = Obj.Value;
2226 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002227 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002228
Richard Smithd62306a2011-11-10 06:34:14 +00002229 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002230 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2231 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002232 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002233 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2234 return handler.failed();
2235 }
2236
Richard Smith49ca8aa2013-08-06 07:09:20 +00002237 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002238 // If we are reading an object of class type, there may still be more
2239 // things we need to check: if there are any mutable subobjects, we
2240 // cannot perform this read. (This only happens when performing a trivial
2241 // copy or assignment.)
2242 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2243 diagnoseUnreadableFields(Info, E, ObjType))
2244 return handler.failed();
2245
Richard Smith49ca8aa2013-08-06 07:09:20 +00002246 if (!handler.found(*O, ObjType))
2247 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002248
Richard Smith49ca8aa2013-08-06 07:09:20 +00002249 // If we modified a bit-field, truncate it to the right width.
2250 if (handler.AccessKind != AK_Read &&
2251 LastField && LastField->isBitField() &&
2252 !truncateBitfieldValue(Info, E, *O, LastField))
2253 return false;
2254
2255 return true;
2256 }
2257
Craig Topper36250ad2014-05-12 05:36:57 +00002258 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002259 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002260 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002261 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002262 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002263 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002264 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002265 // Note, it should not be possible to form a pointer with a valid
2266 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002267 if (Info.getLangOpts().CPlusPlus11)
2268 Info.Diag(E, diag::note_constexpr_access_past_end)
2269 << handler.AccessKind;
2270 else
2271 Info.Diag(E);
2272 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002273 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002274
2275 ObjType = CAT->getElementType();
2276
Richard Smith14a94132012-02-17 03:35:37 +00002277 // An array object is represented as either an Array APValue or as an
2278 // LValue which refers to a string literal.
2279 if (O->isLValue()) {
2280 assert(I == N - 1 && "extracting subobject of character?");
2281 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002282 if (handler.AccessKind != AK_Read)
2283 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2284 *O);
2285 else
2286 return handler.foundString(*O, ObjType, Index);
2287 }
2288
2289 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002290 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002291 else if (handler.AccessKind != AK_Read) {
2292 expandArray(*O, Index);
2293 O = &O->getArrayInitializedElt(Index);
2294 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002295 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002296 } else if (ObjType->isAnyComplexType()) {
2297 // Next subobject is a complex number.
2298 uint64_t Index = Sub.Entries[I].ArrayIndex;
2299 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002300 if (Info.getLangOpts().CPlusPlus11)
2301 Info.Diag(E, diag::note_constexpr_access_past_end)
2302 << handler.AccessKind;
2303 else
2304 Info.Diag(E);
2305 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002306 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002307
2308 bool WasConstQualified = ObjType.isConstQualified();
2309 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2310 if (WasConstQualified)
2311 ObjType.addConst();
2312
Richard Smith66c96992012-02-18 22:04:06 +00002313 assert(I == N - 1 && "extracting subobject of scalar?");
2314 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002315 return handler.found(Index ? O->getComplexIntImag()
2316 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002317 } else {
2318 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002319 return handler.found(Index ? O->getComplexFloatImag()
2320 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002321 }
Richard Smithd62306a2011-11-10 06:34:14 +00002322 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002323 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002324 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002325 << Field;
2326 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002327 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002328 }
2329
Richard Smithd62306a2011-11-10 06:34:14 +00002330 // Next subobject is a class, struct or union field.
2331 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2332 if (RD->isUnion()) {
2333 const FieldDecl *UnionField = O->getUnionField();
2334 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002335 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002336 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2337 << handler.AccessKind << Field << !UnionField << UnionField;
2338 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002339 }
Richard Smithd62306a2011-11-10 06:34:14 +00002340 O = &O->getUnionValue();
2341 } else
2342 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002343
2344 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002345 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002346 if (WasConstQualified && !Field->isMutable())
2347 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002348
2349 if (ObjType.isVolatileQualified()) {
2350 if (Info.getLangOpts().CPlusPlus) {
2351 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002352 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2353 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002354 Info.Note(Field->getLocation(), diag::note_declared_at);
2355 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002356 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002357 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002358 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002359 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002360
2361 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002362 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002363 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002364 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2365 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2366 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002367
2368 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002369 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002370 if (WasConstQualified)
2371 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002372 }
2373 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002374}
2375
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002376namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002377struct ExtractSubobjectHandler {
2378 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002379 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002380
2381 static const AccessKinds AccessKind = AK_Read;
2382
2383 typedef bool result_type;
2384 bool failed() { return false; }
2385 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002386 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002387 return true;
2388 }
2389 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002390 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002391 return true;
2392 }
2393 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002394 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002395 return true;
2396 }
2397 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002398 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002399 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2400 return true;
2401 }
2402};
Richard Smith3229b742013-05-05 21:17:10 +00002403} // end anonymous namespace
2404
Richard Smith3da88fa2013-04-26 14:36:30 +00002405const AccessKinds ExtractSubobjectHandler::AccessKind;
2406
2407/// Extract the designated sub-object of an rvalue.
2408static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002409 const CompleteObject &Obj,
2410 const SubobjectDesignator &Sub,
2411 APValue &Result) {
2412 ExtractSubobjectHandler Handler = { Info, Result };
2413 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002414}
2415
Richard Smith3229b742013-05-05 21:17:10 +00002416namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002417struct ModifySubobjectHandler {
2418 EvalInfo &Info;
2419 APValue &NewVal;
2420 const Expr *E;
2421
2422 typedef bool result_type;
2423 static const AccessKinds AccessKind = AK_Assign;
2424
2425 bool checkConst(QualType QT) {
2426 // Assigning to a const object has undefined behavior.
2427 if (QT.isConstQualified()) {
2428 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2429 return false;
2430 }
2431 return true;
2432 }
2433
2434 bool failed() { return false; }
2435 bool found(APValue &Subobj, QualType SubobjType) {
2436 if (!checkConst(SubobjType))
2437 return false;
2438 // We've been given ownership of NewVal, so just swap it in.
2439 Subobj.swap(NewVal);
2440 return true;
2441 }
2442 bool found(APSInt &Value, QualType SubobjType) {
2443 if (!checkConst(SubobjType))
2444 return false;
2445 if (!NewVal.isInt()) {
2446 // Maybe trying to write a cast pointer value into a complex?
2447 Info.Diag(E);
2448 return false;
2449 }
2450 Value = NewVal.getInt();
2451 return true;
2452 }
2453 bool found(APFloat &Value, QualType SubobjType) {
2454 if (!checkConst(SubobjType))
2455 return false;
2456 Value = NewVal.getFloat();
2457 return true;
2458 }
2459 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2460 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2461 }
2462};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002463} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002464
Richard Smith3229b742013-05-05 21:17:10 +00002465const AccessKinds ModifySubobjectHandler::AccessKind;
2466
Richard Smith3da88fa2013-04-26 14:36:30 +00002467/// Update the designated sub-object of an rvalue to the given value.
2468static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002469 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002470 const SubobjectDesignator &Sub,
2471 APValue &NewVal) {
2472 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002473 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002474}
2475
Richard Smith84f6dcf2012-02-02 01:16:57 +00002476/// Find the position where two subobject designators diverge, or equivalently
2477/// the length of the common initial subsequence.
2478static unsigned FindDesignatorMismatch(QualType ObjType,
2479 const SubobjectDesignator &A,
2480 const SubobjectDesignator &B,
2481 bool &WasArrayIndex) {
2482 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2483 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002484 if (!ObjType.isNull() &&
2485 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002486 // Next subobject is an array element.
2487 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2488 WasArrayIndex = true;
2489 return I;
2490 }
Richard Smith66c96992012-02-18 22:04:06 +00002491 if (ObjType->isAnyComplexType())
2492 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2493 else
2494 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002495 } else {
2496 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2497 WasArrayIndex = false;
2498 return I;
2499 }
2500 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2501 // Next subobject is a field.
2502 ObjType = FD->getType();
2503 else
2504 // Next subobject is a base class.
2505 ObjType = QualType();
2506 }
2507 }
2508 WasArrayIndex = false;
2509 return I;
2510}
2511
2512/// Determine whether the given subobject designators refer to elements of the
2513/// same array object.
2514static bool AreElementsOfSameArray(QualType ObjType,
2515 const SubobjectDesignator &A,
2516 const SubobjectDesignator &B) {
2517 if (A.Entries.size() != B.Entries.size())
2518 return false;
2519
2520 bool IsArray = A.MostDerivedArraySize != 0;
2521 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2522 // A is a subobject of the array element.
2523 return false;
2524
2525 // If A (and B) designates an array element, the last entry will be the array
2526 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2527 // of length 1' case, and the entire path must match.
2528 bool WasArrayIndex;
2529 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2530 return CommonLength >= A.Entries.size() - IsArray;
2531}
2532
Richard Smith3229b742013-05-05 21:17:10 +00002533/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002534static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2535 AccessKinds AK, const LValue &LVal,
2536 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002537 if (!LVal.Base) {
2538 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2539 return CompleteObject();
2540 }
2541
Craig Topper36250ad2014-05-12 05:36:57 +00002542 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002543 if (LVal.CallIndex) {
2544 Frame = Info.getCallFrame(LVal.CallIndex);
2545 if (!Frame) {
2546 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2547 << AK << LVal.Base.is<const ValueDecl*>();
2548 NoteLValueLocation(Info, LVal.Base);
2549 return CompleteObject();
2550 }
Richard Smith3229b742013-05-05 21:17:10 +00002551 }
2552
2553 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2554 // is not a constant expression (even if the object is non-volatile). We also
2555 // apply this rule to C++98, in order to conform to the expected 'volatile'
2556 // semantics.
2557 if (LValType.isVolatileQualified()) {
2558 if (Info.getLangOpts().CPlusPlus)
2559 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2560 << AK << LValType;
2561 else
2562 Info.Diag(E);
2563 return CompleteObject();
2564 }
2565
2566 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002567 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002568 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002569
2570 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2571 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2572 // In C++11, constexpr, non-volatile variables initialized with constant
2573 // expressions are constant expressions too. Inside constexpr functions,
2574 // parameters are constant expressions even if they're non-const.
2575 // In C++1y, objects local to a constant expression (those with a Frame) are
2576 // both readable and writable inside constant expressions.
2577 // In C, such things can also be folded, although they are not ICEs.
2578 const VarDecl *VD = dyn_cast<VarDecl>(D);
2579 if (VD) {
2580 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2581 VD = VDef;
2582 }
2583 if (!VD || VD->isInvalidDecl()) {
2584 Info.Diag(E);
2585 return CompleteObject();
2586 }
2587
2588 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002589 if (BaseType.isVolatileQualified()) {
2590 if (Info.getLangOpts().CPlusPlus) {
2591 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2592 << AK << 1 << VD;
2593 Info.Note(VD->getLocation(), diag::note_declared_at);
2594 } else {
2595 Info.Diag(E);
2596 }
2597 return CompleteObject();
2598 }
2599
2600 // Unless we're looking at a local variable or argument in a constexpr call,
2601 // the variable we're reading must be const.
2602 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002603 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002604 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2605 // OK, we can read and modify an object if we're in the process of
2606 // evaluating its initializer, because its lifetime began in this
2607 // evaluation.
2608 } else if (AK != AK_Read) {
2609 // All the remaining cases only permit reading.
2610 Info.Diag(E, diag::note_constexpr_modify_global);
2611 return CompleteObject();
2612 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002613 // OK, we can read this variable.
2614 } else if (BaseType->isIntegralOrEnumerationType()) {
2615 if (!BaseType.isConstQualified()) {
2616 if (Info.getLangOpts().CPlusPlus) {
2617 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2618 Info.Note(VD->getLocation(), diag::note_declared_at);
2619 } else {
2620 Info.Diag(E);
2621 }
2622 return CompleteObject();
2623 }
2624 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2625 // We support folding of const floating-point types, in order to make
2626 // static const data members of such types (supported as an extension)
2627 // more useful.
2628 if (Info.getLangOpts().CPlusPlus11) {
2629 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2630 Info.Note(VD->getLocation(), diag::note_declared_at);
2631 } else {
2632 Info.CCEDiag(E);
2633 }
2634 } else {
2635 // FIXME: Allow folding of values of any literal type in all languages.
2636 if (Info.getLangOpts().CPlusPlus11) {
2637 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2638 Info.Note(VD->getLocation(), diag::note_declared_at);
2639 } else {
2640 Info.Diag(E);
2641 }
2642 return CompleteObject();
2643 }
2644 }
2645
2646 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2647 return CompleteObject();
2648 } else {
2649 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2650
2651 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002652 if (const MaterializeTemporaryExpr *MTE =
2653 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2654 assert(MTE->getStorageDuration() == SD_Static &&
2655 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002656
Richard Smithe6c01442013-06-05 00:46:14 +00002657 // Per C++1y [expr.const]p2:
2658 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2659 // - a [...] glvalue of integral or enumeration type that refers to
2660 // a non-volatile const object [...]
2661 // [...]
2662 // - a [...] glvalue of literal type that refers to a non-volatile
2663 // object whose lifetime began within the evaluation of e.
2664 //
2665 // C++11 misses the 'began within the evaluation of e' check and
2666 // instead allows all temporaries, including things like:
2667 // int &&r = 1;
2668 // int x = ++r;
2669 // constexpr int k = r;
2670 // Therefore we use the C++1y rules in C++11 too.
2671 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2672 const ValueDecl *ED = MTE->getExtendingDecl();
2673 if (!(BaseType.isConstQualified() &&
2674 BaseType->isIntegralOrEnumerationType()) &&
2675 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2676 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2677 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2678 return CompleteObject();
2679 }
2680
2681 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2682 assert(BaseVal && "got reference to unevaluated temporary");
2683 } else {
2684 Info.Diag(E);
2685 return CompleteObject();
2686 }
2687 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002688 BaseVal = Frame->getTemporary(Base);
2689 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002690 }
Richard Smith3229b742013-05-05 21:17:10 +00002691
2692 // Volatile temporary objects cannot be accessed in constant expressions.
2693 if (BaseType.isVolatileQualified()) {
2694 if (Info.getLangOpts().CPlusPlus) {
2695 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2696 << AK << 0;
2697 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2698 } else {
2699 Info.Diag(E);
2700 }
2701 return CompleteObject();
2702 }
2703 }
2704
Richard Smith7525ff62013-05-09 07:14:00 +00002705 // During the construction of an object, it is not yet 'const'.
2706 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2707 // and this doesn't do quite the right thing for const subobjects of the
2708 // object under construction.
2709 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2710 BaseType = Info.Ctx.getCanonicalType(BaseType);
2711 BaseType.removeLocalConst();
2712 }
2713
Richard Smith6d4c6582013-11-05 22:18:15 +00002714 // In C++1y, we can't safely access any mutable state when we might be
2715 // evaluating after an unmodeled side effect or an evaluation failure.
2716 //
2717 // FIXME: Not all local state is mutable. Allow local constant subobjects
2718 // to be read here (but take care with 'mutable' fields).
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002719 if (Frame && Info.getLangOpts().CPlusPlus14 &&
Richard Smith6d4c6582013-11-05 22:18:15 +00002720 (Info.EvalStatus.HasSideEffects || Info.keepEvaluatingAfterFailure()))
Richard Smith3229b742013-05-05 21:17:10 +00002721 return CompleteObject();
2722
2723 return CompleteObject(BaseVal, BaseType);
2724}
2725
Richard Smith243ef902013-05-05 23:31:59 +00002726/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2727/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2728/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002729///
2730/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002731/// \param Conv - The expression for which we are performing the conversion.
2732/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002733/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2734/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002735/// \param LVal - The glvalue on which we are attempting to perform this action.
2736/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002737static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002738 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002739 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002740 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002741 return false;
2742
Richard Smith3229b742013-05-05 21:17:10 +00002743 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002744 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002745 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002746 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2747 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2748 // initializer until now for such expressions. Such an expression can't be
2749 // an ICE in C, so this only matters for fold.
2750 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2751 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002752 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002753 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002754 }
Richard Smith3229b742013-05-05 21:17:10 +00002755 APValue Lit;
2756 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2757 return false;
2758 CompleteObject LitObj(&Lit, Base->getType());
2759 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002760 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002761 // We represent a string literal array as an lvalue pointing at the
2762 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002763 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002764 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2765 CompleteObject StrObj(&Str, Base->getType());
2766 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002767 }
Richard Smith11562c52011-10-28 17:51:58 +00002768 }
2769
Richard Smith3229b742013-05-05 21:17:10 +00002770 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2771 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002772}
2773
2774/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002775static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002776 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002777 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002778 return false;
2779
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002780 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith3229b742013-05-05 21:17:10 +00002781 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002782 return false;
2783 }
2784
Richard Smith3229b742013-05-05 21:17:10 +00002785 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2786 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002787}
2788
Richard Smith243ef902013-05-05 23:31:59 +00002789static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2790 return T->isSignedIntegerType() &&
2791 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2792}
2793
2794namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002795struct CompoundAssignSubobjectHandler {
2796 EvalInfo &Info;
2797 const Expr *E;
2798 QualType PromotedLHSType;
2799 BinaryOperatorKind Opcode;
2800 const APValue &RHS;
2801
2802 static const AccessKinds AccessKind = AK_Assign;
2803
2804 typedef bool result_type;
2805
2806 bool checkConst(QualType QT) {
2807 // Assigning to a const object has undefined behavior.
2808 if (QT.isConstQualified()) {
2809 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2810 return false;
2811 }
2812 return true;
2813 }
2814
2815 bool failed() { return false; }
2816 bool found(APValue &Subobj, QualType SubobjType) {
2817 switch (Subobj.getKind()) {
2818 case APValue::Int:
2819 return found(Subobj.getInt(), SubobjType);
2820 case APValue::Float:
2821 return found(Subobj.getFloat(), SubobjType);
2822 case APValue::ComplexInt:
2823 case APValue::ComplexFloat:
2824 // FIXME: Implement complex compound assignment.
2825 Info.Diag(E);
2826 return false;
2827 case APValue::LValue:
2828 return foundPointer(Subobj, SubobjType);
2829 default:
2830 // FIXME: can this happen?
2831 Info.Diag(E);
2832 return false;
2833 }
2834 }
2835 bool found(APSInt &Value, QualType SubobjType) {
2836 if (!checkConst(SubobjType))
2837 return false;
2838
2839 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2840 // We don't support compound assignment on integer-cast-to-pointer
2841 // values.
2842 Info.Diag(E);
2843 return false;
2844 }
2845
2846 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2847 SubobjType, Value);
2848 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
2849 return false;
2850 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
2851 return true;
2852 }
2853 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00002854 return checkConst(SubobjType) &&
2855 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
2856 Value) &&
2857 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
2858 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00002859 }
2860 bool foundPointer(APValue &Subobj, QualType SubobjType) {
2861 if (!checkConst(SubobjType))
2862 return false;
2863
2864 QualType PointeeType;
2865 if (const PointerType *PT = SubobjType->getAs<PointerType>())
2866 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00002867
2868 if (PointeeType.isNull() || !RHS.isInt() ||
2869 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00002870 Info.Diag(E);
2871 return false;
2872 }
2873
Richard Smith861b5b52013-05-07 23:34:45 +00002874 int64_t Offset = getExtValue(RHS.getInt());
2875 if (Opcode == BO_Sub)
2876 Offset = -Offset;
2877
2878 LValue LVal;
2879 LVal.setFrom(Info.Ctx, Subobj);
2880 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
2881 return false;
2882 LVal.moveInto(Subobj);
2883 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002884 }
2885 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2886 llvm_unreachable("shouldn't encounter string elements here");
2887 }
2888};
2889} // end anonymous namespace
2890
2891const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
2892
2893/// Perform a compound assignment of LVal <op>= RVal.
2894static bool handleCompoundAssignment(
2895 EvalInfo &Info, const Expr *E,
2896 const LValue &LVal, QualType LValType, QualType PromotedLValType,
2897 BinaryOperatorKind Opcode, const APValue &RVal) {
2898 if (LVal.Designator.Invalid)
2899 return false;
2900
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002901 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith43e77732013-05-07 04:50:00 +00002902 Info.Diag(E);
2903 return false;
2904 }
2905
2906 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2907 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
2908 RVal };
2909 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
2910}
2911
2912namespace {
Richard Smith243ef902013-05-05 23:31:59 +00002913struct IncDecSubobjectHandler {
2914 EvalInfo &Info;
2915 const Expr *E;
2916 AccessKinds AccessKind;
2917 APValue *Old;
2918
2919 typedef bool result_type;
2920
2921 bool checkConst(QualType QT) {
2922 // Assigning to a const object has undefined behavior.
2923 if (QT.isConstQualified()) {
2924 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2925 return false;
2926 }
2927 return true;
2928 }
2929
2930 bool failed() { return false; }
2931 bool found(APValue &Subobj, QualType SubobjType) {
2932 // Stash the old value. Also clear Old, so we don't clobber it later
2933 // if we're post-incrementing a complex.
2934 if (Old) {
2935 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00002936 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00002937 }
2938
2939 switch (Subobj.getKind()) {
2940 case APValue::Int:
2941 return found(Subobj.getInt(), SubobjType);
2942 case APValue::Float:
2943 return found(Subobj.getFloat(), SubobjType);
2944 case APValue::ComplexInt:
2945 return found(Subobj.getComplexIntReal(),
2946 SubobjType->castAs<ComplexType>()->getElementType()
2947 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2948 case APValue::ComplexFloat:
2949 return found(Subobj.getComplexFloatReal(),
2950 SubobjType->castAs<ComplexType>()->getElementType()
2951 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
2952 case APValue::LValue:
2953 return foundPointer(Subobj, SubobjType);
2954 default:
2955 // FIXME: can this happen?
2956 Info.Diag(E);
2957 return false;
2958 }
2959 }
2960 bool found(APSInt &Value, QualType SubobjType) {
2961 if (!checkConst(SubobjType))
2962 return false;
2963
2964 if (!SubobjType->isIntegerType()) {
2965 // We don't support increment / decrement on integer-cast-to-pointer
2966 // values.
2967 Info.Diag(E);
2968 return false;
2969 }
2970
2971 if (Old) *Old = APValue(Value);
2972
2973 // bool arithmetic promotes to int, and the conversion back to bool
2974 // doesn't reduce mod 2^n, so special-case it.
2975 if (SubobjType->isBooleanType()) {
2976 if (AccessKind == AK_Increment)
2977 Value = 1;
2978 else
2979 Value = !Value;
2980 return true;
2981 }
2982
2983 bool WasNegative = Value.isNegative();
2984 if (AccessKind == AK_Increment) {
2985 ++Value;
2986
2987 if (!WasNegative && Value.isNegative() &&
2988 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2989 APSInt ActualValue(Value, /*IsUnsigned*/true);
2990 HandleOverflow(Info, E, ActualValue, SubobjType);
2991 }
2992 } else {
2993 --Value;
2994
2995 if (WasNegative && !Value.isNegative() &&
2996 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
2997 unsigned BitWidth = Value.getBitWidth();
2998 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
2999 ActualValue.setBit(BitWidth);
3000 HandleOverflow(Info, E, ActualValue, SubobjType);
3001 }
3002 }
3003 return true;
3004 }
3005 bool found(APFloat &Value, QualType SubobjType) {
3006 if (!checkConst(SubobjType))
3007 return false;
3008
3009 if (Old) *Old = APValue(Value);
3010
3011 APFloat One(Value.getSemantics(), 1);
3012 if (AccessKind == AK_Increment)
3013 Value.add(One, APFloat::rmNearestTiesToEven);
3014 else
3015 Value.subtract(One, APFloat::rmNearestTiesToEven);
3016 return true;
3017 }
3018 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3019 if (!checkConst(SubobjType))
3020 return false;
3021
3022 QualType PointeeType;
3023 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3024 PointeeType = PT->getPointeeType();
3025 else {
3026 Info.Diag(E);
3027 return false;
3028 }
3029
3030 LValue LVal;
3031 LVal.setFrom(Info.Ctx, Subobj);
3032 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3033 AccessKind == AK_Increment ? 1 : -1))
3034 return false;
3035 LVal.moveInto(Subobj);
3036 return true;
3037 }
3038 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3039 llvm_unreachable("shouldn't encounter string elements here");
3040 }
3041};
3042} // end anonymous namespace
3043
3044/// Perform an increment or decrement on LVal.
3045static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3046 QualType LValType, bool IsIncrement, APValue *Old) {
3047 if (LVal.Designator.Invalid)
3048 return false;
3049
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003050 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith243ef902013-05-05 23:31:59 +00003051 Info.Diag(E);
3052 return false;
3053 }
3054
3055 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3056 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3057 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3058 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3059}
3060
Richard Smithe97cbd72011-11-11 04:05:33 +00003061/// Build an lvalue for the object argument of a member function call.
3062static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3063 LValue &This) {
3064 if (Object->getType()->isPointerType())
3065 return EvaluatePointer(Object, This, Info);
3066
3067 if (Object->isGLValue())
3068 return EvaluateLValue(Object, This, Info);
3069
Richard Smithd9f663b2013-04-22 15:31:51 +00003070 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003071 return EvaluateTemporary(Object, This, Info);
3072
Richard Smith3e79a572014-06-11 19:53:12 +00003073 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003074 return false;
3075}
3076
3077/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3078/// lvalue referring to the result.
3079///
3080/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003081/// \param LV - An lvalue referring to the base of the member pointer.
3082/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003083/// \param IncludeMember - Specifies whether the member itself is included in
3084/// the resulting LValue subobject designator. This is not possible when
3085/// creating a bound member function.
3086/// \return The field or method declaration to which the member pointer refers,
3087/// or 0 if evaluation fails.
3088static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003089 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003090 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003091 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003092 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003093 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003094 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003095 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003096
3097 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3098 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003099 if (!MemPtr.getDecl()) {
3100 // FIXME: Specific diagnostic.
3101 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003102 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003103 }
Richard Smith253c2a32012-01-27 01:14:48 +00003104
Richard Smith027bf112011-11-17 22:56:20 +00003105 if (MemPtr.isDerivedMember()) {
3106 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003107 // The end of the derived-to-base path for the base object must match the
3108 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003109 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003110 LV.Designator.Entries.size()) {
3111 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003112 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003113 }
Richard Smith027bf112011-11-17 22:56:20 +00003114 unsigned PathLengthToMember =
3115 LV.Designator.Entries.size() - MemPtr.Path.size();
3116 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3117 const CXXRecordDecl *LVDecl = getAsBaseClass(
3118 LV.Designator.Entries[PathLengthToMember + I]);
3119 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003120 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3121 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003122 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003123 }
Richard Smith027bf112011-11-17 22:56:20 +00003124 }
3125
3126 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003127 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003128 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003129 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003130 } else if (!MemPtr.Path.empty()) {
3131 // Extend the LValue path with the member pointer's path.
3132 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3133 MemPtr.Path.size() + IncludeMember);
3134
3135 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003136 if (const PointerType *PT = LVType->getAs<PointerType>())
3137 LVType = PT->getPointeeType();
3138 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3139 assert(RD && "member pointer access on non-class-type expression");
3140 // The first class in the path is that of the lvalue.
3141 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3142 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003143 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003144 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003145 RD = Base;
3146 }
3147 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003148 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3149 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003150 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003151 }
3152
3153 // Add the member. Note that we cannot build bound member functions here.
3154 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003155 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003156 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003157 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003158 } else if (const IndirectFieldDecl *IFD =
3159 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003160 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003161 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003162 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003163 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003164 }
Richard Smith027bf112011-11-17 22:56:20 +00003165 }
3166
3167 return MemPtr.getDecl();
3168}
3169
Richard Smith84401042013-06-03 05:03:02 +00003170static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3171 const BinaryOperator *BO,
3172 LValue &LV,
3173 bool IncludeMember = true) {
3174 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3175
3176 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
3177 if (Info.keepEvaluatingAfterFailure()) {
3178 MemberPtr MemPtr;
3179 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3180 }
Craig Topper36250ad2014-05-12 05:36:57 +00003181 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003182 }
3183
3184 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3185 BO->getRHS(), IncludeMember);
3186}
3187
Richard Smith027bf112011-11-17 22:56:20 +00003188/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3189/// the provided lvalue, which currently refers to the base object.
3190static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3191 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003192 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003193 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003194 return false;
3195
Richard Smitha8105bc2012-01-06 16:39:00 +00003196 QualType TargetQT = E->getType();
3197 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3198 TargetQT = PT->getPointeeType();
3199
3200 // Check this cast lands within the final derived-to-base subobject path.
3201 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003202 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003203 << D.MostDerivedType << TargetQT;
3204 return false;
3205 }
3206
Richard Smith027bf112011-11-17 22:56:20 +00003207 // Check the type of the final cast. We don't need to check the path,
3208 // since a cast can only be formed if the path is unique.
3209 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003210 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3211 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003212 if (NewEntriesSize == D.MostDerivedPathLength)
3213 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3214 else
Richard Smith027bf112011-11-17 22:56:20 +00003215 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003216 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003217 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003218 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003219 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003220 }
Richard Smith027bf112011-11-17 22:56:20 +00003221
3222 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003223 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003224}
3225
Mike Stump876387b2009-10-27 22:09:17 +00003226namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003227enum EvalStmtResult {
3228 /// Evaluation failed.
3229 ESR_Failed,
3230 /// Hit a 'return' statement.
3231 ESR_Returned,
3232 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003233 ESR_Succeeded,
3234 /// Hit a 'continue' statement.
3235 ESR_Continue,
3236 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003237 ESR_Break,
3238 /// Still scanning for 'case' or 'default' statement.
3239 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003240};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003241}
Richard Smith254a73d2011-10-28 22:34:42 +00003242
Richard Smithd9f663b2013-04-22 15:31:51 +00003243static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3244 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3245 // We don't need to evaluate the initializer for a static local.
3246 if (!VD->hasLocalStorage())
3247 return true;
3248
3249 LValue Result;
3250 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003251 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003252
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003253 const Expr *InitE = VD->getInit();
3254 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003255 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3256 << false << VD->getType();
3257 Val = APValue();
3258 return false;
3259 }
3260
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003261 if (InitE->isValueDependent())
3262 return false;
3263
3264 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003265 // Wipe out any partially-computed value, to allow tracking that this
3266 // evaluation failed.
3267 Val = APValue();
3268 return false;
3269 }
3270 }
3271
3272 return true;
3273}
3274
Richard Smith4e18ca52013-05-06 05:56:11 +00003275/// Evaluate a condition (either a variable declaration or an expression).
3276static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3277 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003278 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003279 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3280 return false;
3281 return EvaluateAsBooleanCondition(Cond, Result, Info);
3282}
3283
Richard Smith52a980a2015-08-28 02:43:42 +00003284/// \brief A location where the result (returned value) of evaluating a
3285/// statement should be stored.
3286struct StmtResult {
3287 /// The APValue that should be filled in with the returned value.
3288 APValue &Value;
3289 /// The location containing the result, if any (used to support RVO).
3290 const LValue *Slot;
3291};
3292
3293static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003294 const Stmt *S,
3295 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003296
3297/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003298static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003299 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003300 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003301 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003302 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003303 case ESR_Break:
3304 return ESR_Succeeded;
3305 case ESR_Succeeded:
3306 case ESR_Continue:
3307 return ESR_Continue;
3308 case ESR_Failed:
3309 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003310 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003311 return ESR;
3312 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003313 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003314}
3315
Richard Smith496ddcf2013-05-12 17:32:42 +00003316/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003317static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003318 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003319 BlockScopeRAII Scope(Info);
3320
Richard Smith496ddcf2013-05-12 17:32:42 +00003321 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003322 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003323 {
3324 FullExpressionRAII Scope(Info);
3325 if (SS->getConditionVariable() &&
3326 !EvaluateDecl(Info, SS->getConditionVariable()))
3327 return ESR_Failed;
3328 if (!EvaluateInteger(SS->getCond(), Value, Info))
3329 return ESR_Failed;
3330 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003331
3332 // Find the switch case corresponding to the value of the condition.
3333 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003334 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003335 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3336 SC = SC->getNextSwitchCase()) {
3337 if (isa<DefaultStmt>(SC)) {
3338 Found = SC;
3339 continue;
3340 }
3341
3342 const CaseStmt *CS = cast<CaseStmt>(SC);
3343 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3344 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3345 : LHS;
3346 if (LHS <= Value && Value <= RHS) {
3347 Found = SC;
3348 break;
3349 }
3350 }
3351
3352 if (!Found)
3353 return ESR_Succeeded;
3354
3355 // Search the switch body for the switch case and evaluate it from there.
3356 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3357 case ESR_Break:
3358 return ESR_Succeeded;
3359 case ESR_Succeeded:
3360 case ESR_Continue:
3361 case ESR_Failed:
3362 case ESR_Returned:
3363 return ESR;
3364 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003365 // This can only happen if the switch case is nested within a statement
3366 // expression. We have no intention of supporting that.
3367 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3368 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003369 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003370 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003371}
3372
Richard Smith254a73d2011-10-28 22:34:42 +00003373// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003374static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003375 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003376 if (!Info.nextStep(S))
3377 return ESR_Failed;
3378
Richard Smith496ddcf2013-05-12 17:32:42 +00003379 // If we're hunting down a 'case' or 'default' label, recurse through
3380 // substatements until we hit the label.
3381 if (Case) {
3382 // FIXME: We don't start the lifetime of objects whose initialization we
3383 // jump over. However, such objects must be of class type with a trivial
3384 // default constructor that initialize all subobjects, so must be empty,
3385 // so this almost never matters.
3386 switch (S->getStmtClass()) {
3387 case Stmt::CompoundStmtClass:
3388 // FIXME: Precompute which substatement of a compound statement we
3389 // would jump to, and go straight there rather than performing a
3390 // linear scan each time.
3391 case Stmt::LabelStmtClass:
3392 case Stmt::AttributedStmtClass:
3393 case Stmt::DoStmtClass:
3394 break;
3395
3396 case Stmt::CaseStmtClass:
3397 case Stmt::DefaultStmtClass:
3398 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003399 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003400 break;
3401
3402 case Stmt::IfStmtClass: {
3403 // FIXME: Precompute which side of an 'if' we would jump to, and go
3404 // straight there rather than scanning both sides.
3405 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003406
3407 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3408 // preceded by our switch label.
3409 BlockScopeRAII Scope(Info);
3410
Richard Smith496ddcf2013-05-12 17:32:42 +00003411 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3412 if (ESR != ESR_CaseNotFound || !IS->getElse())
3413 return ESR;
3414 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3415 }
3416
3417 case Stmt::WhileStmtClass: {
3418 EvalStmtResult ESR =
3419 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3420 if (ESR != ESR_Continue)
3421 return ESR;
3422 break;
3423 }
3424
3425 case Stmt::ForStmtClass: {
3426 const ForStmt *FS = cast<ForStmt>(S);
3427 EvalStmtResult ESR =
3428 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3429 if (ESR != ESR_Continue)
3430 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003431 if (FS->getInc()) {
3432 FullExpressionRAII IncScope(Info);
3433 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3434 return ESR_Failed;
3435 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003436 break;
3437 }
3438
3439 case Stmt::DeclStmtClass:
3440 // FIXME: If the variable has initialization that can't be jumped over,
3441 // bail out of any immediately-surrounding compound-statement too.
3442 default:
3443 return ESR_CaseNotFound;
3444 }
3445 }
3446
Richard Smith254a73d2011-10-28 22:34:42 +00003447 switch (S->getStmtClass()) {
3448 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003449 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003450 // Don't bother evaluating beyond an expression-statement which couldn't
3451 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003452 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003453 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003454 return ESR_Failed;
3455 return ESR_Succeeded;
3456 }
3457
3458 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003459 return ESR_Failed;
3460
3461 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003462 return ESR_Succeeded;
3463
Richard Smithd9f663b2013-04-22 15:31:51 +00003464 case Stmt::DeclStmtClass: {
3465 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003466 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003467 // Each declaration initialization is its own full-expression.
3468 // FIXME: This isn't quite right; if we're performing aggregate
3469 // initialization, each braced subexpression is its own full-expression.
3470 FullExpressionRAII Scope(Info);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003471 if (!EvaluateDecl(Info, DclIt) && !Info.keepEvaluatingAfterFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003472 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003473 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003474 return ESR_Succeeded;
3475 }
3476
Richard Smith357362d2011-12-13 06:39:58 +00003477 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003478 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003479 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003480 if (RetExpr &&
3481 !(Result.Slot
3482 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3483 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003484 return ESR_Failed;
3485 return ESR_Returned;
3486 }
Richard Smith254a73d2011-10-28 22:34:42 +00003487
3488 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003489 BlockScopeRAII Scope(Info);
3490
Richard Smith254a73d2011-10-28 22:34:42 +00003491 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003492 for (const auto *BI : CS->body()) {
3493 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003494 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003495 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003496 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003497 return ESR;
3498 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003499 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003500 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003501
3502 case Stmt::IfStmtClass: {
3503 const IfStmt *IS = cast<IfStmt>(S);
3504
3505 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003506 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003507 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003508 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003509 return ESR_Failed;
3510
3511 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3512 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3513 if (ESR != ESR_Succeeded)
3514 return ESR;
3515 }
3516 return ESR_Succeeded;
3517 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003518
3519 case Stmt::WhileStmtClass: {
3520 const WhileStmt *WS = cast<WhileStmt>(S);
3521 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003522 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003523 bool Continue;
3524 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3525 Continue))
3526 return ESR_Failed;
3527 if (!Continue)
3528 break;
3529
3530 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3531 if (ESR != ESR_Continue)
3532 return ESR;
3533 }
3534 return ESR_Succeeded;
3535 }
3536
3537 case Stmt::DoStmtClass: {
3538 const DoStmt *DS = cast<DoStmt>(S);
3539 bool Continue;
3540 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003541 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003542 if (ESR != ESR_Continue)
3543 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003544 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003545
Richard Smith08d6a2c2013-07-24 07:11:57 +00003546 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003547 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3548 return ESR_Failed;
3549 } while (Continue);
3550 return ESR_Succeeded;
3551 }
3552
3553 case Stmt::ForStmtClass: {
3554 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003555 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003556 if (FS->getInit()) {
3557 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3558 if (ESR != ESR_Succeeded)
3559 return ESR;
3560 }
3561 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003562 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003563 bool Continue = true;
3564 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3565 FS->getCond(), Continue))
3566 return ESR_Failed;
3567 if (!Continue)
3568 break;
3569
3570 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3571 if (ESR != ESR_Continue)
3572 return ESR;
3573
Richard Smith08d6a2c2013-07-24 07:11:57 +00003574 if (FS->getInc()) {
3575 FullExpressionRAII IncScope(Info);
3576 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3577 return ESR_Failed;
3578 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003579 }
3580 return ESR_Succeeded;
3581 }
3582
Richard Smith896e0d72013-05-06 06:51:17 +00003583 case Stmt::CXXForRangeStmtClass: {
3584 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003585 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003586
3587 // Initialize the __range variable.
3588 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3589 if (ESR != ESR_Succeeded)
3590 return ESR;
3591
3592 // Create the __begin and __end iterators.
3593 ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
3594 if (ESR != ESR_Succeeded)
3595 return ESR;
3596
3597 while (true) {
3598 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003599 {
3600 bool Continue = true;
3601 FullExpressionRAII CondExpr(Info);
3602 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3603 return ESR_Failed;
3604 if (!Continue)
3605 break;
3606 }
Richard Smith896e0d72013-05-06 06:51:17 +00003607
3608 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003609 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003610 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3611 if (ESR != ESR_Succeeded)
3612 return ESR;
3613
3614 // Loop body.
3615 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3616 if (ESR != ESR_Continue)
3617 return ESR;
3618
3619 // Increment: ++__begin
3620 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3621 return ESR_Failed;
3622 }
3623
3624 return ESR_Succeeded;
3625 }
3626
Richard Smith496ddcf2013-05-12 17:32:42 +00003627 case Stmt::SwitchStmtClass:
3628 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3629
Richard Smith4e18ca52013-05-06 05:56:11 +00003630 case Stmt::ContinueStmtClass:
3631 return ESR_Continue;
3632
3633 case Stmt::BreakStmtClass:
3634 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003635
3636 case Stmt::LabelStmtClass:
3637 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3638
3639 case Stmt::AttributedStmtClass:
3640 // As a general principle, C++11 attributes can be ignored without
3641 // any semantic impact.
3642 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3643 Case);
3644
3645 case Stmt::CaseStmtClass:
3646 case Stmt::DefaultStmtClass:
3647 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003648 }
3649}
3650
Richard Smithcc36f692011-12-22 02:22:31 +00003651/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3652/// default constructor. If so, we'll fold it whether or not it's marked as
3653/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3654/// so we need special handling.
3655static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003656 const CXXConstructorDecl *CD,
3657 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003658 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3659 return false;
3660
Richard Smith66e05fe2012-01-18 05:21:49 +00003661 // Value-initialization does not call a trivial default constructor, so such a
3662 // call is a core constant expression whether or not the constructor is
3663 // constexpr.
3664 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003665 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003666 // FIXME: If DiagDecl is an implicitly-declared special member function,
3667 // we should be much more explicit about why it's not constexpr.
3668 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3669 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3670 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003671 } else {
3672 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3673 }
3674 }
3675 return true;
3676}
3677
Richard Smith357362d2011-12-13 06:39:58 +00003678/// CheckConstexprFunction - Check that a function can be called in a constant
3679/// expression.
3680static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3681 const FunctionDecl *Declaration,
3682 const FunctionDecl *Definition) {
Richard Smith253c2a32012-01-27 01:14:48 +00003683 // Potential constant expressions can contain calls to declared, but not yet
3684 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003685 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003686 Declaration->isConstexpr())
3687 return false;
3688
Richard Smith0838f3a2013-05-14 05:18:44 +00003689 // Bail out with no diagnostic if the function declaration itself is invalid.
3690 // We will have produced a relevant diagnostic while parsing it.
3691 if (Declaration->isInvalidDecl())
3692 return false;
3693
Richard Smith357362d2011-12-13 06:39:58 +00003694 // Can we evaluate this function call?
3695 if (Definition && Definition->isConstexpr() && !Definition->isInvalidDecl())
3696 return true;
3697
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003698 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003699 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smithd0b4dd62011-12-19 06:19:21 +00003700 // FIXME: If DiagDecl is an implicitly-declared special member function, we
3701 // should be much more explicit about why it's not constexpr.
Richard Smith357362d2011-12-13 06:39:58 +00003702 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3703 << DiagDecl->isConstexpr() << isa<CXXConstructorDecl>(DiagDecl)
3704 << DiagDecl;
3705 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3706 } else {
3707 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3708 }
3709 return false;
3710}
3711
Richard Smithbe6dd812014-11-19 21:27:17 +00003712/// Determine if a class has any fields that might need to be copied by a
3713/// trivial copy or move operation.
3714static bool hasFields(const CXXRecordDecl *RD) {
3715 if (!RD || RD->isEmpty())
3716 return false;
3717 for (auto *FD : RD->fields()) {
3718 if (FD->isUnnamedBitfield())
3719 continue;
3720 return true;
3721 }
3722 for (auto &Base : RD->bases())
3723 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3724 return true;
3725 return false;
3726}
3727
Richard Smithd62306a2011-11-10 06:34:14 +00003728namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003729typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003730}
3731
3732/// EvaluateArgs - Evaluate the arguments to a function call.
3733static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3734 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003735 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003736 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003737 I != E; ++I) {
3738 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3739 // If we're checking for a potential constant expression, evaluate all
3740 // initializers even if some of them fail.
3741 if (!Info.keepEvaluatingAfterFailure())
3742 return false;
3743 Success = false;
3744 }
3745 }
3746 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003747}
3748
Richard Smith254a73d2011-10-28 22:34:42 +00003749/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003750static bool HandleFunctionCall(SourceLocation CallLoc,
3751 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003752 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003753 EvalInfo &Info, APValue &Result,
3754 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003755 ArgVector ArgValues(Args.size());
3756 if (!EvaluateArgs(Args, ArgValues, Info))
3757 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003758
Richard Smith253c2a32012-01-27 01:14:48 +00003759 if (!Info.CheckCallLimit(CallLoc))
3760 return false;
3761
3762 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003763
3764 // For a trivial copy or move assignment, perform an APValue copy. This is
3765 // essential for unions, where the operations performed by the assignment
3766 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003767 //
3768 // Skip this for non-union classes with no fields; in that case, the defaulted
3769 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003770 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003771 if (MD && MD->isDefaulted() &&
3772 (MD->getParent()->isUnion() ||
3773 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003774 assert(This &&
3775 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3776 LValue RHS;
3777 RHS.setFrom(Info.Ctx, ArgValues[0]);
3778 APValue RHSValue;
3779 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3780 RHS, RHSValue))
3781 return false;
3782 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3783 RHSValue))
3784 return false;
3785 This->moveInto(Result);
3786 return true;
3787 }
3788
Richard Smith52a980a2015-08-28 02:43:42 +00003789 StmtResult Ret = {Result, ResultSlot};
3790 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003791 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003792 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003793 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003794 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003795 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003796 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003797}
3798
Richard Smithd62306a2011-11-10 06:34:14 +00003799/// Evaluate a constructor call.
Richard Smith253c2a32012-01-27 01:14:48 +00003800static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
Richard Smithe97cbd72011-11-11 04:05:33 +00003801 ArrayRef<const Expr*> Args,
Richard Smithd62306a2011-11-10 06:34:14 +00003802 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003803 EvalInfo &Info, APValue &Result) {
Richard Smithd62306a2011-11-10 06:34:14 +00003804 ArgVector ArgValues(Args.size());
3805 if (!EvaluateArgs(Args, ArgValues, Info))
3806 return false;
3807
Richard Smith253c2a32012-01-27 01:14:48 +00003808 if (!Info.CheckCallLimit(CallLoc))
3809 return false;
3810
Richard Smith3607ffe2012-02-13 03:54:03 +00003811 const CXXRecordDecl *RD = Definition->getParent();
3812 if (RD->getNumVBases()) {
3813 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3814 return false;
3815 }
3816
Richard Smith253c2a32012-01-27 01:14:48 +00003817 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues.data());
Richard Smithd62306a2011-11-10 06:34:14 +00003818
Richard Smith52a980a2015-08-28 02:43:42 +00003819 // FIXME: Creating an APValue just to hold a nonexistent return value is
3820 // wasteful.
3821 APValue RetVal;
3822 StmtResult Ret = {RetVal, nullptr};
3823
Richard Smithd62306a2011-11-10 06:34:14 +00003824 // If it's a delegating constructor, just delegate.
3825 if (Definition->isDelegatingConstructor()) {
3826 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003827 {
3828 FullExpressionRAII InitScope(Info);
3829 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3830 return false;
3831 }
Richard Smith52a980a2015-08-28 02:43:42 +00003832 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003833 }
3834
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003835 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00003836 // essential for unions (or classes with anonymous union members), where the
3837 // operations performed by the constructor cannot be represented by
3838 // ctor-initializers.
3839 //
3840 // Skip this for empty non-union classes; we should not perform an
3841 // lvalue-to-rvalue conversion on them because their copy constructor does not
3842 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00003843 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00003844 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00003845 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003846 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00003847 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith243ef902013-05-05 23:31:59 +00003848 return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
Richard Smith2e312c82012-03-03 22:46:17 +00003849 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00003850 }
3851
3852 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00003853 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00003854 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003855 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00003856
John McCalld7bca762012-05-01 00:38:49 +00003857 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003858 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
3859
Richard Smith08d6a2c2013-07-24 07:11:57 +00003860 // A scope for temporaries lifetime-extended by reference members.
3861 BlockScopeRAII LifetimeExtendedScope(Info);
3862
Richard Smith253c2a32012-01-27 01:14:48 +00003863 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003864 unsigned BasesSeen = 0;
3865#ifndef NDEBUG
3866 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
3867#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003868 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00003869 LValue Subobject = This;
3870 APValue *Value = &Result;
3871
3872 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00003873 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00003874 if (I->isBaseInitializer()) {
3875 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00003876#ifndef NDEBUG
3877 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00003878 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00003879 assert(!BaseIt->isVirtual() && "virtual base for literal type");
3880 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
3881 "base class initializers not in expected order");
3882 ++BaseIt;
3883#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00003884 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00003885 BaseType->getAsCXXRecordDecl(), &Layout))
3886 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00003887 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003888 } else if ((FD = I->getMember())) {
3889 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00003890 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00003891 if (RD->isUnion()) {
3892 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00003893 Value = &Result.getUnionValue();
3894 } else {
3895 Value = &Result.getStructField(FD->getFieldIndex());
3896 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003897 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003898 // Walk the indirect field decl's chain to find the object to initialize,
3899 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00003900 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00003901 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00003902 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
3903 // Switch the union field if it differs. This happens if we had
3904 // preceding zero-initialization, and we're now initializing a union
3905 // subobject other than the first.
3906 // FIXME: In this case, the values of the other subobjects are
3907 // specified, since zero-initialization sets all padding bits to zero.
3908 if (Value->isUninit() ||
3909 (Value->isUnion() && Value->getUnionField() != FD)) {
3910 if (CD->isUnion())
3911 *Value = APValue(FD);
3912 else
3913 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00003914 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00003915 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00003916 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00003917 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00003918 if (CD->isUnion())
3919 Value = &Value->getUnionValue();
3920 else
3921 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00003922 }
Richard Smithd62306a2011-11-10 06:34:14 +00003923 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003924 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00003925 }
Richard Smith253c2a32012-01-27 01:14:48 +00003926
Richard Smith08d6a2c2013-07-24 07:11:57 +00003927 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00003928 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
3929 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00003930 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00003931 // If we're checking for a potential constant expression, evaluate all
3932 // initializers even if some of them fail.
3933 if (!Info.keepEvaluatingAfterFailure())
3934 return false;
3935 Success = false;
3936 }
Richard Smithd62306a2011-11-10 06:34:14 +00003937 }
3938
Richard Smithd9f663b2013-04-22 15:31:51 +00003939 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00003940 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00003941}
3942
Eli Friedman9a156e52008-11-12 09:44:48 +00003943//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00003944// Generic Evaluation
3945//===----------------------------------------------------------------------===//
3946namespace {
3947
Aaron Ballman68af21c2014-01-03 19:26:43 +00003948template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00003949class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00003950 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00003951private:
Richard Smith52a980a2015-08-28 02:43:42 +00003952 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003953 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00003954 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00003955 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00003956 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00003957 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00003958 }
Peter Collingbournee9200682011-05-13 03:29:01 +00003959
Richard Smith17100ba2012-02-16 02:46:34 +00003960 // Check whether a conditional operator with a non-constant condition is a
3961 // potential constant expression. If neither arm is a potential constant
3962 // expression, then the conditional operator is not either.
3963 template<typename ConditionalOperator>
3964 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003965 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00003966
3967 // Speculatively evaluate both arms.
3968 {
Dmitri Gribenkof8579502013-01-12 19:30:44 +00003969 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00003970 SpeculativeEvaluationRAII Speculate(Info, &Diag);
3971
3972 StmtVisitorTy::Visit(E->getFalseExpr());
3973 if (Diag.empty())
3974 return;
3975
3976 Diag.clear();
3977 StmtVisitorTy::Visit(E->getTrueExpr());
3978 if (Diag.empty())
3979 return;
3980 }
3981
3982 Error(E, diag::note_constexpr_conditional_never_const);
3983 }
3984
3985
3986 template<typename ConditionalOperator>
3987 bool HandleConditionalOperator(const ConditionalOperator *E) {
3988 bool BoolResult;
3989 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00003990 if (Info.checkingPotentialConstantExpression())
Richard Smith17100ba2012-02-16 02:46:34 +00003991 CheckPotentialConstantConditional(E);
3992 return false;
3993 }
3994
3995 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
3996 return StmtVisitorTy::Visit(EvalExpr);
3997 }
3998
Peter Collingbournee9200682011-05-13 03:29:01 +00003999protected:
4000 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004001 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004002 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4003
Richard Smith92b1ce02011-12-12 09:28:41 +00004004 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004005 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004006 }
4007
Aaron Ballman68af21c2014-01-03 19:26:43 +00004008 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004009
4010public:
4011 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4012
4013 EvalInfo &getEvalInfo() { return Info; }
4014
Richard Smithf57d8cb2011-12-09 22:58:01 +00004015 /// Report an evaluation error. This should only be called when an error is
4016 /// first discovered. When propagating an error, just return false.
4017 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004018 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004019 return false;
4020 }
4021 bool Error(const Expr *E) {
4022 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4023 }
4024
Aaron Ballman68af21c2014-01-03 19:26:43 +00004025 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004026 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004027 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004028 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004029 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004030 }
4031
Aaron Ballman68af21c2014-01-03 19:26:43 +00004032 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004033 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004034 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004035 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004036 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004037 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004038 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004039 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004040 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004041 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004042 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004043 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004044 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004045 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004046 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004047 // The initializer may not have been parsed yet, or might be erroneous.
4048 if (!E->getExpr())
4049 return Error(E);
4050 return StmtVisitorTy::Visit(E->getExpr());
4051 }
Richard Smith5894a912011-12-19 22:12:41 +00004052 // We cannot create any objects for which cleanups are required, so there is
4053 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004054 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004055 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004056
Aaron Ballman68af21c2014-01-03 19:26:43 +00004057 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004058 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4059 return static_cast<Derived*>(this)->VisitCastExpr(E);
4060 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004061 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004062 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4063 return static_cast<Derived*>(this)->VisitCastExpr(E);
4064 }
4065
Aaron Ballman68af21c2014-01-03 19:26:43 +00004066 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004067 switch (E->getOpcode()) {
4068 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004069 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004070
4071 case BO_Comma:
4072 VisitIgnoredValue(E->getLHS());
4073 return StmtVisitorTy::Visit(E->getRHS());
4074
4075 case BO_PtrMemD:
4076 case BO_PtrMemI: {
4077 LValue Obj;
4078 if (!HandleMemberPointerAccess(Info, E, Obj))
4079 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004080 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004081 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004082 return false;
4083 return DerivedSuccess(Result, E);
4084 }
4085 }
4086 }
4087
Aaron Ballman68af21c2014-01-03 19:26:43 +00004088 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004089 // Evaluate and cache the common expression. We treat it as a temporary,
4090 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004091 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004092 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004093 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004094
Richard Smith17100ba2012-02-16 02:46:34 +00004095 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004096 }
4097
Aaron Ballman68af21c2014-01-03 19:26:43 +00004098 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004099 bool IsBcpCall = false;
4100 // If the condition (ignoring parens) is a __builtin_constant_p call,
4101 // the result is a constant expression if it can be folded without
4102 // side-effects. This is an important GNU extension. See GCC PR38377
4103 // for discussion.
4104 if (const CallExpr *CallCE =
4105 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004106 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004107 IsBcpCall = true;
4108
4109 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4110 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004111 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004112 return false;
4113
Richard Smith6d4c6582013-11-05 22:18:15 +00004114 FoldConstant Fold(Info, IsBcpCall);
4115 if (!HandleConditionalOperator(E)) {
4116 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004117 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004118 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004119
4120 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004121 }
4122
Aaron Ballman68af21c2014-01-03 19:26:43 +00004123 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004124 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4125 return DerivedSuccess(*Value, E);
4126
4127 const Expr *Source = E->getSourceExpr();
4128 if (!Source)
4129 return Error(E);
4130 if (Source == E) { // sanity checking.
4131 assert(0 && "OpaqueValueExpr recursively refers to itself");
4132 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004133 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004134 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004135 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004136
Aaron Ballman68af21c2014-01-03 19:26:43 +00004137 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004138 APValue Result;
4139 if (!handleCallExpr(E, Result, nullptr))
4140 return false;
4141 return DerivedSuccess(Result, E);
4142 }
4143
4144 bool handleCallExpr(const CallExpr *E, APValue &Result,
4145 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004146 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004147 QualType CalleeType = Callee->getType();
4148
Craig Topper36250ad2014-05-12 05:36:57 +00004149 const FunctionDecl *FD = nullptr;
4150 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004151 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004152 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004153
Richard Smithe97cbd72011-11-11 04:05:33 +00004154 // Extract function decl and 'this' pointer from the callee.
4155 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004156 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004157 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4158 // Explicit bound member calls, such as x.f() or p->g();
4159 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004160 return false;
4161 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004162 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004163 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004164 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4165 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004166 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4167 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004168 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004169 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004170 return Error(Callee);
4171
4172 FD = dyn_cast<FunctionDecl>(Member);
4173 if (!FD)
4174 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004175 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004176 LValue Call;
4177 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004178 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004179
Richard Smitha8105bc2012-01-06 16:39:00 +00004180 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004181 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004182 FD = dyn_cast_or_null<FunctionDecl>(
4183 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004184 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004185 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004186
4187 // Overloaded operator calls to member functions are represented as normal
4188 // calls with '*this' as the first argument.
4189 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4190 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004191 // FIXME: When selecting an implicit conversion for an overloaded
4192 // operator delete, we sometimes try to evaluate calls to conversion
4193 // operators without a 'this' parameter!
4194 if (Args.empty())
4195 return Error(E);
4196
Richard Smithe97cbd72011-11-11 04:05:33 +00004197 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4198 return false;
4199 This = &ThisVal;
4200 Args = Args.slice(1);
4201 }
4202
4203 // Don't call function pointers which have been cast to some other type.
4204 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004205 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004206 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004207 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004208
Richard Smith47b34932012-02-01 02:39:43 +00004209 if (This && !This->checkSubobject(Info, E, CSK_This))
4210 return false;
4211
Richard Smith3607ffe2012-02-13 03:54:03 +00004212 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4213 // calls to such functions in constant expressions.
4214 if (This && !HasQualifier &&
4215 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4216 return Error(E, diag::note_constexpr_virtual_call);
4217
Craig Topper36250ad2014-05-12 05:36:57 +00004218 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004219 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004220
Richard Smith357362d2011-12-13 06:39:58 +00004221 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004222 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4223 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004224 return false;
4225
Richard Smith52a980a2015-08-28 02:43:42 +00004226 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004227 }
4228
Aaron Ballman68af21c2014-01-03 19:26:43 +00004229 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004230 return StmtVisitorTy::Visit(E->getInitializer());
4231 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004232 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004233 if (E->getNumInits() == 0)
4234 return DerivedZeroInitialization(E);
4235 if (E->getNumInits() == 1)
4236 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004237 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004238 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004239 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004240 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004241 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004242 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004243 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004244 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004245 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004246 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004247 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004248
Richard Smithd62306a2011-11-10 06:34:14 +00004249 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004250 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004251 assert(!E->isArrow() && "missing call to bound member function?");
4252
Richard Smith2e312c82012-03-03 22:46:17 +00004253 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004254 if (!Evaluate(Val, Info, E->getBase()))
4255 return false;
4256
4257 QualType BaseTy = E->getBase()->getType();
4258
4259 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004260 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004261 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004262 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004263 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4264
Richard Smith3229b742013-05-05 21:17:10 +00004265 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004266 SubobjectDesignator Designator(BaseTy);
4267 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004268
Richard Smith3229b742013-05-05 21:17:10 +00004269 APValue Result;
4270 return extractSubobject(Info, E, Obj, Designator, Result) &&
4271 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004272 }
4273
Aaron Ballman68af21c2014-01-03 19:26:43 +00004274 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004275 switch (E->getCastKind()) {
4276 default:
4277 break;
4278
Richard Smitha23ab512013-05-23 00:30:41 +00004279 case CK_AtomicToNonAtomic: {
4280 APValue AtomicVal;
4281 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4282 return false;
4283 return DerivedSuccess(AtomicVal, E);
4284 }
4285
Richard Smith11562c52011-10-28 17:51:58 +00004286 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004287 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004288 return StmtVisitorTy::Visit(E->getSubExpr());
4289
4290 case CK_LValueToRValue: {
4291 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004292 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4293 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004294 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004295 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004296 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004297 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004298 return false;
4299 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004300 }
4301 }
4302
Richard Smithf57d8cb2011-12-09 22:58:01 +00004303 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004304 }
4305
Aaron Ballman68af21c2014-01-03 19:26:43 +00004306 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004307 return VisitUnaryPostIncDec(UO);
4308 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004309 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004310 return VisitUnaryPostIncDec(UO);
4311 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004312 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004313 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004314 return Error(UO);
4315
4316 LValue LVal;
4317 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4318 return false;
4319 APValue RVal;
4320 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4321 UO->isIncrementOp(), &RVal))
4322 return false;
4323 return DerivedSuccess(RVal, UO);
4324 }
4325
Aaron Ballman68af21c2014-01-03 19:26:43 +00004326 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004327 // We will have checked the full-expressions inside the statement expression
4328 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004329 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004330 return Error(E);
4331
Richard Smith08d6a2c2013-07-24 07:11:57 +00004332 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004333 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004334 if (CS->body_empty())
4335 return true;
4336
Richard Smith51f03172013-06-20 03:00:05 +00004337 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4338 BE = CS->body_end();
4339 /**/; ++BI) {
4340 if (BI + 1 == BE) {
4341 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4342 if (!FinalExpr) {
4343 Info.Diag((*BI)->getLocStart(),
4344 diag::note_constexpr_stmt_expr_unsupported);
4345 return false;
4346 }
4347 return this->Visit(FinalExpr);
4348 }
4349
4350 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004351 StmtResult Result = { ReturnValue, nullptr };
4352 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004353 if (ESR != ESR_Succeeded) {
4354 // FIXME: If the statement-expression terminated due to 'return',
4355 // 'break', or 'continue', it would be nice to propagate that to
4356 // the outer statement evaluation rather than bailing out.
4357 if (ESR != ESR_Failed)
4358 Info.Diag((*BI)->getLocStart(),
4359 diag::note_constexpr_stmt_expr_unsupported);
4360 return false;
4361 }
4362 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004363
4364 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004365 }
4366
Richard Smith4a678122011-10-24 18:44:57 +00004367 /// Visit a value which is evaluated, but whose value is ignored.
4368 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004369 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004370 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004371};
4372
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004373}
Peter Collingbournee9200682011-05-13 03:29:01 +00004374
4375//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004376// Common base class for lvalue and temporary evaluation.
4377//===----------------------------------------------------------------------===//
4378namespace {
4379template<class Derived>
4380class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004381 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004382protected:
4383 LValue &Result;
4384 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004385 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004386
4387 bool Success(APValue::LValueBase B) {
4388 Result.set(B);
4389 return true;
4390 }
4391
4392public:
4393 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4394 ExprEvaluatorBaseTy(Info), Result(Result) {}
4395
Richard Smith2e312c82012-03-03 22:46:17 +00004396 bool Success(const APValue &V, const Expr *E) {
4397 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004398 return true;
4399 }
Richard Smith027bf112011-11-17 22:56:20 +00004400
Richard Smith027bf112011-11-17 22:56:20 +00004401 bool VisitMemberExpr(const MemberExpr *E) {
4402 // Handle non-static data members.
4403 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004404 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004405 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004406 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004407 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004408 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004409 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004410 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004411 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004412 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004413 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004414 BaseTy = E->getBase()->getType();
4415 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004416 if (!EvalOK) {
4417 if (!this->Info.allowInvalidBaseExpr())
4418 return false;
4419 Result.setInvalid(E->getBase());
4420 }
Richard Smith027bf112011-11-17 22:56:20 +00004421
Richard Smith1b78b3d2012-01-25 22:15:11 +00004422 const ValueDecl *MD = E->getMemberDecl();
4423 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4424 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4425 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4426 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004427 if (!HandleLValueMember(this->Info, E, Result, FD))
4428 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004429 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004430 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4431 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004432 } else
4433 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004434
Richard Smith1b78b3d2012-01-25 22:15:11 +00004435 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004436 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004437 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004438 RefValue))
4439 return false;
4440 return Success(RefValue, E);
4441 }
4442 return true;
4443 }
4444
4445 bool VisitBinaryOperator(const BinaryOperator *E) {
4446 switch (E->getOpcode()) {
4447 default:
4448 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4449
4450 case BO_PtrMemD:
4451 case BO_PtrMemI:
4452 return HandleMemberPointerAccess(this->Info, E, Result);
4453 }
4454 }
4455
4456 bool VisitCastExpr(const CastExpr *E) {
4457 switch (E->getCastKind()) {
4458 default:
4459 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4460
4461 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004462 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004463 if (!this->Visit(E->getSubExpr()))
4464 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004465
4466 // Now figure out the necessary offset to add to the base LV to get from
4467 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004468 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4469 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004470 }
4471 }
4472};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004473}
Richard Smith027bf112011-11-17 22:56:20 +00004474
4475//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004476// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004477//
4478// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4479// function designators (in C), decl references to void objects (in C), and
4480// temporaries (if building with -Wno-address-of-temporary).
4481//
4482// LValue evaluation produces values comprising a base expression of one of the
4483// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004484// - Declarations
4485// * VarDecl
4486// * FunctionDecl
4487// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004488// * CompoundLiteralExpr in C
4489// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004490// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004491// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004492// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004493// * ObjCEncodeExpr
4494// * AddrLabelExpr
4495// * BlockExpr
4496// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004497// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004498// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004499// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004500// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4501// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004502// * A MaterializeTemporaryExpr that has static storage duration, with no
4503// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004504// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004505//===----------------------------------------------------------------------===//
4506namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004507class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004508 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004509public:
Richard Smith027bf112011-11-17 22:56:20 +00004510 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4511 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004512
Richard Smith11562c52011-10-28 17:51:58 +00004513 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004514 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004515
Peter Collingbournee9200682011-05-13 03:29:01 +00004516 bool VisitDeclRefExpr(const DeclRefExpr *E);
4517 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004518 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004519 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4520 bool VisitMemberExpr(const MemberExpr *E);
4521 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4522 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004523 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004524 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004525 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4526 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004527 bool VisitUnaryReal(const UnaryOperator *E);
4528 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004529 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4530 return VisitUnaryPreIncDec(UO);
4531 }
4532 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4533 return VisitUnaryPreIncDec(UO);
4534 }
Richard Smith3229b742013-05-05 21:17:10 +00004535 bool VisitBinAssign(const BinaryOperator *BO);
4536 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004537
Peter Collingbournee9200682011-05-13 03:29:01 +00004538 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004539 switch (E->getCastKind()) {
4540 default:
Richard Smith027bf112011-11-17 22:56:20 +00004541 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004542
Eli Friedmance3e02a2011-10-11 00:13:24 +00004543 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004544 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004545 if (!Visit(E->getSubExpr()))
4546 return false;
4547 Result.Designator.setInvalid();
4548 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004549
Richard Smith027bf112011-11-17 22:56:20 +00004550 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004551 if (!Visit(E->getSubExpr()))
4552 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004553 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004554 }
4555 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004556};
4557} // end anonymous namespace
4558
Richard Smith11562c52011-10-28 17:51:58 +00004559/// Evaluate an expression as an lvalue. This can be legitimately called on
Richard Smith9f8400e2013-05-01 19:00:39 +00004560/// expressions which are not glvalues, in two cases:
4561/// * function designators in C, and
4562/// * "extern void" objects
4563static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4564 assert(E->isGLValue() || E->getType()->isFunctionType() ||
4565 E->getType()->isVoidType());
Peter Collingbournee9200682011-05-13 03:29:01 +00004566 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004567}
4568
Peter Collingbournee9200682011-05-13 03:29:01 +00004569bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004570 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004571 return Success(FD);
4572 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004573 return VisitVarDecl(E, VD);
4574 return Error(E);
4575}
Richard Smith733237d2011-10-24 23:14:33 +00004576
Richard Smith11562c52011-10-28 17:51:58 +00004577bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004578 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004579 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4580 Frame = Info.CurrentCall;
4581
Richard Smithfec09922011-11-01 16:57:24 +00004582 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004583 if (Frame) {
4584 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004585 return true;
4586 }
Richard Smithce40ad62011-11-12 22:28:03 +00004587 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004588 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004589
Richard Smith3229b742013-05-05 21:17:10 +00004590 APValue *V;
4591 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004592 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004593 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004594 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004595 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4596 return false;
4597 }
Richard Smith3229b742013-05-05 21:17:10 +00004598 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004599}
4600
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004601bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4602 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004603 // Walk through the expression to find the materialized temporary itself.
4604 SmallVector<const Expr *, 2> CommaLHSs;
4605 SmallVector<SubobjectAdjustment, 2> Adjustments;
4606 const Expr *Inner = E->GetTemporaryExpr()->
4607 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004608
Richard Smith84401042013-06-03 05:03:02 +00004609 // If we passed any comma operators, evaluate their LHSs.
4610 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4611 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4612 return false;
4613
Richard Smithe6c01442013-06-05 00:46:14 +00004614 // A materialized temporary with static storage duration can appear within the
4615 // result of a constant expression evaluation, so we need to preserve its
4616 // value for use outside this evaluation.
4617 APValue *Value;
4618 if (E->getStorageDuration() == SD_Static) {
4619 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004620 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004621 Result.set(E);
4622 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004623 Value = &Info.CurrentCall->
4624 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004625 Result.set(E, Info.CurrentCall->Index);
4626 }
4627
Richard Smithea4ad5d2013-06-06 08:19:16 +00004628 QualType Type = Inner->getType();
4629
Richard Smith84401042013-06-03 05:03:02 +00004630 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004631 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4632 (E->getStorageDuration() == SD_Static &&
4633 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4634 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004635 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004636 }
Richard Smith84401042013-06-03 05:03:02 +00004637
4638 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004639 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4640 --I;
4641 switch (Adjustments[I].Kind) {
4642 case SubobjectAdjustment::DerivedToBaseAdjustment:
4643 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4644 Type, Result))
4645 return false;
4646 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4647 break;
4648
4649 case SubobjectAdjustment::FieldAdjustment:
4650 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4651 return false;
4652 Type = Adjustments[I].Field->getType();
4653 break;
4654
4655 case SubobjectAdjustment::MemberPointerAdjustment:
4656 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4657 Adjustments[I].Ptr.RHS))
4658 return false;
4659 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4660 break;
4661 }
4662 }
4663
4664 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004665}
4666
Peter Collingbournee9200682011-05-13 03:29:01 +00004667bool
4668LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004669 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4670 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4671 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004672 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004673}
4674
Richard Smith6e525142011-12-27 12:18:28 +00004675bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004676 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004677 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004678
4679 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4680 << E->getExprOperand()->getType()
4681 << E->getExprOperand()->getSourceRange();
4682 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004683}
4684
Francois Pichet0066db92012-04-16 04:08:35 +00004685bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4686 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004687}
Francois Pichet0066db92012-04-16 04:08:35 +00004688
Peter Collingbournee9200682011-05-13 03:29:01 +00004689bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004690 // Handle static data members.
4691 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
4692 VisitIgnoredValue(E->getBase());
4693 return VisitVarDecl(E, VD);
4694 }
4695
Richard Smith254a73d2011-10-28 22:34:42 +00004696 // Handle static member functions.
4697 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4698 if (MD->isStatic()) {
4699 VisitIgnoredValue(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004700 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004701 }
4702 }
4703
Richard Smithd62306a2011-11-10 06:34:14 +00004704 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004705 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004706}
4707
Peter Collingbournee9200682011-05-13 03:29:01 +00004708bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004709 // FIXME: Deal with vectors as array subscript bases.
4710 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004711 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004712
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004713 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004714 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004715
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004716 APSInt Index;
4717 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004718 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004719
Richard Smith861b5b52013-05-07 23:34:45 +00004720 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4721 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004722}
Eli Friedman9a156e52008-11-12 09:44:48 +00004723
Peter Collingbournee9200682011-05-13 03:29:01 +00004724bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004725 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004726}
4727
Richard Smith66c96992012-02-18 22:04:06 +00004728bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4729 if (!Visit(E->getSubExpr()))
4730 return false;
4731 // __real is a no-op on scalar lvalues.
4732 if (E->getSubExpr()->getType()->isAnyComplexType())
4733 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4734 return true;
4735}
4736
4737bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4738 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4739 "lvalue __imag__ on scalar?");
4740 if (!Visit(E->getSubExpr()))
4741 return false;
4742 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4743 return true;
4744}
4745
Richard Smith243ef902013-05-05 23:31:59 +00004746bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004747 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004748 return Error(UO);
4749
4750 if (!this->Visit(UO->getSubExpr()))
4751 return false;
4752
Richard Smith243ef902013-05-05 23:31:59 +00004753 return handleIncDec(
4754 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004755 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004756}
4757
4758bool LValueExprEvaluator::VisitCompoundAssignOperator(
4759 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004760 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004761 return Error(CAO);
4762
Richard Smith3229b742013-05-05 21:17:10 +00004763 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004764
4765 // The overall lvalue result is the result of evaluating the LHS.
4766 if (!this->Visit(CAO->getLHS())) {
4767 if (Info.keepEvaluatingAfterFailure())
4768 Evaluate(RHS, this->Info, CAO->getRHS());
4769 return false;
4770 }
4771
Richard Smith3229b742013-05-05 21:17:10 +00004772 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4773 return false;
4774
Richard Smith43e77732013-05-07 04:50:00 +00004775 return handleCompoundAssignment(
4776 this->Info, CAO,
4777 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4778 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004779}
4780
4781bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004782 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004783 return Error(E);
4784
Richard Smith3229b742013-05-05 21:17:10 +00004785 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004786
4787 if (!this->Visit(E->getLHS())) {
4788 if (Info.keepEvaluatingAfterFailure())
4789 Evaluate(NewVal, this->Info, E->getRHS());
4790 return false;
4791 }
4792
Richard Smith3229b742013-05-05 21:17:10 +00004793 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4794 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004795
4796 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004797 NewVal);
4798}
4799
Eli Friedman9a156e52008-11-12 09:44:48 +00004800//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004801// Pointer Evaluation
4802//===----------------------------------------------------------------------===//
4803
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004804namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004805class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00004806 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00004807 LValue &Result;
4808
Peter Collingbournee9200682011-05-13 03:29:01 +00004809 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00004810 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00004811 return true;
4812 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004813public:
Mike Stump11289f42009-09-09 15:08:12 +00004814
John McCall45d55e42010-05-07 21:00:08 +00004815 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00004816 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00004817
Richard Smith2e312c82012-03-03 22:46:17 +00004818 bool Success(const APValue &V, const Expr *E) {
4819 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00004820 return true;
4821 }
Richard Smithfddd3842011-12-30 21:15:51 +00004822 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00004823 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00004824 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00004825
John McCall45d55e42010-05-07 21:00:08 +00004826 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004827 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00004828 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004829 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00004830 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00004831 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00004832 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004833 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00004834 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004835 bool VisitCallExpr(const CallExpr *E);
4836 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00004837 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00004838 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004839 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00004840 }
Richard Smithd62306a2011-11-10 06:34:14 +00004841 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004842 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00004843 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00004844 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00004845 if (!Info.CurrentCall->This) {
4846 if (Info.getLangOpts().CPlusPlus11)
4847 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
4848 else
4849 Info.Diag(E);
4850 return false;
4851 }
Richard Smithd62306a2011-11-10 06:34:14 +00004852 Result = *Info.CurrentCall->This;
4853 return true;
4854 }
John McCallc07a0c72011-02-17 10:25:35 +00004855
Eli Friedman449fe542009-03-23 04:56:01 +00004856 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004857};
Chris Lattner05706e882008-07-11 18:11:29 +00004858} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00004859
John McCall45d55e42010-05-07 21:00:08 +00004860static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00004861 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00004862 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00004863}
4864
John McCall45d55e42010-05-07 21:00:08 +00004865bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00004866 if (E->getOpcode() != BO_Add &&
4867 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00004868 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00004869
Chris Lattner05706e882008-07-11 18:11:29 +00004870 const Expr *PExp = E->getLHS();
4871 const Expr *IExp = E->getRHS();
4872 if (IExp->getType()->isPointerType())
4873 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00004874
Richard Smith253c2a32012-01-27 01:14:48 +00004875 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
4876 if (!EvalPtrOK && !Info.keepEvaluatingAfterFailure())
John McCall45d55e42010-05-07 21:00:08 +00004877 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004878
John McCall45d55e42010-05-07 21:00:08 +00004879 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00004880 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00004881 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00004882
4883 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00004884 if (E->getOpcode() == BO_Sub)
4885 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00004886
Ted Kremenek28831752012-08-23 20:46:57 +00004887 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00004888 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
4889 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00004890}
Eli Friedman9a156e52008-11-12 09:44:48 +00004891
John McCall45d55e42010-05-07 21:00:08 +00004892bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
4893 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004894}
Mike Stump11289f42009-09-09 15:08:12 +00004895
Peter Collingbournee9200682011-05-13 03:29:01 +00004896bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
4897 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00004898
Eli Friedman847a2bc2009-12-27 05:43:15 +00004899 switch (E->getCastKind()) {
4900 default:
4901 break;
4902
John McCalle3027922010-08-25 11:45:40 +00004903 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00004904 case CK_CPointerToObjCPointerCast:
4905 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00004906 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00004907 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00004908 if (!Visit(SubExpr))
4909 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00004910 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
4911 // permitted in constant expressions in C++11. Bitcasts from cv void* are
4912 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00004913 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00004914 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00004915 if (SubExpr->getType()->isVoidPointerType())
4916 CCEDiag(E, diag::note_constexpr_invalid_cast)
4917 << 3 << SubExpr->getType();
4918 else
4919 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4920 }
Richard Smith96e0c102011-11-04 02:25:55 +00004921 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00004922
Anders Carlsson18275092010-10-31 20:41:46 +00004923 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004924 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00004925 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00004926 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004927 if (!Result.Base && Result.Offset.isZero())
4928 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00004929
Richard Smithd62306a2011-11-10 06:34:14 +00004930 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00004931 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004932 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
4933 castAs<PointerType>()->getPointeeType(),
4934 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00004935
Richard Smith027bf112011-11-17 22:56:20 +00004936 case CK_BaseToDerived:
4937 if (!Visit(E->getSubExpr()))
4938 return false;
4939 if (!Result.Base && Result.Offset.isZero())
4940 return true;
4941 return HandleBaseToDerivedCast(Info, E, Result);
4942
Richard Smith0b0a0b62011-10-29 20:57:55 +00004943 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00004944 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00004945 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00004946
John McCalle3027922010-08-25 11:45:40 +00004947 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004948 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
4949
Richard Smith2e312c82012-03-03 22:46:17 +00004950 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00004951 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00004952 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00004953
John McCall45d55e42010-05-07 21:00:08 +00004954 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00004955 unsigned Size = Info.Ctx.getTypeSize(E->getType());
4956 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00004957 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004958 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00004959 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00004960 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00004961 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00004962 return true;
4963 } else {
4964 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00004965 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00004966 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00004967 }
4968 }
John McCalle3027922010-08-25 11:45:40 +00004969 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00004970 if (SubExpr->isGLValue()) {
4971 if (!EvaluateLValue(SubExpr, Result, Info))
4972 return false;
4973 } else {
Richard Smithb228a862012-02-15 02:18:13 +00004974 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004975 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00004976 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00004977 return false;
4978 }
Richard Smith96e0c102011-11-04 02:25:55 +00004979 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00004980 if (const ConstantArrayType *CAT
4981 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
4982 Result.addArray(Info, E, CAT);
4983 else
4984 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00004985 return true;
Richard Smithdd785442011-10-31 20:57:44 +00004986
John McCalle3027922010-08-25 11:45:40 +00004987 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00004988 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00004989 }
4990
Richard Smith11562c52011-10-28 17:51:58 +00004991 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00004992}
Chris Lattner05706e882008-07-11 18:11:29 +00004993
Hal Finkel0dd05d42014-10-03 17:18:37 +00004994static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
4995 // C++ [expr.alignof]p3:
4996 // When alignof is applied to a reference type, the result is the
4997 // alignment of the referenced type.
4998 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
4999 T = Ref->getPointeeType();
5000
5001 // __alignof is defined to return the preferred alignment.
5002 return Info.Ctx.toCharUnitsFromBits(
5003 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5004}
5005
5006static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5007 E = E->IgnoreParens();
5008
5009 // The kinds of expressions that we have special-case logic here for
5010 // should be kept up to date with the special checks for those
5011 // expressions in Sema.
5012
5013 // alignof decl is always accepted, even if it doesn't make sense: we default
5014 // to 1 in those cases.
5015 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5016 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5017 /*RefAsPointee*/true);
5018
5019 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5020 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5021 /*RefAsPointee*/true);
5022
5023 return GetAlignOfType(Info, E->getType());
5024}
5025
Peter Collingbournee9200682011-05-13 03:29:01 +00005026bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005027 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005028 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005029
Alp Tokera724cff2013-12-28 21:59:02 +00005030 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005031 case Builtin::BI__builtin_addressof:
5032 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005033 case Builtin::BI__builtin_assume_aligned: {
5034 // We need to be very careful here because: if the pointer does not have the
5035 // asserted alignment, then the behavior is undefined, and undefined
5036 // behavior is non-constant.
5037 if (!EvaluatePointer(E->getArg(0), Result, Info))
5038 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005039
Hal Finkel0dd05d42014-10-03 17:18:37 +00005040 LValue OffsetResult(Result);
5041 APSInt Alignment;
5042 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5043 return false;
5044 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5045
5046 if (E->getNumArgs() > 2) {
5047 APSInt Offset;
5048 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5049 return false;
5050
5051 int64_t AdditionalOffset = -getExtValue(Offset);
5052 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5053 }
5054
5055 // If there is a base object, then it must have the correct alignment.
5056 if (OffsetResult.Base) {
5057 CharUnits BaseAlignment;
5058 if (const ValueDecl *VD =
5059 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5060 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5061 } else {
5062 BaseAlignment =
5063 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5064 }
5065
5066 if (BaseAlignment < Align) {
5067 Result.Designator.setInvalid();
5068 // FIXME: Quantities here cast to integers because the plural modifier
5069 // does not work on APSInts yet.
5070 CCEDiag(E->getArg(0),
5071 diag::note_constexpr_baa_insufficient_alignment) << 0
5072 << (int) BaseAlignment.getQuantity()
5073 << (unsigned) getExtValue(Alignment);
5074 return false;
5075 }
5076 }
5077
5078 // The offset must also have the correct alignment.
5079 if (OffsetResult.Offset.RoundUpToAlignment(Align) != OffsetResult.Offset) {
5080 Result.Designator.setInvalid();
5081 APSInt Offset(64, false);
5082 Offset = OffsetResult.Offset.getQuantity();
5083
5084 if (OffsetResult.Base)
5085 CCEDiag(E->getArg(0),
5086 diag::note_constexpr_baa_insufficient_alignment) << 1
5087 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5088 else
5089 CCEDiag(E->getArg(0),
5090 diag::note_constexpr_baa_value_insufficient_alignment)
5091 << Offset << (unsigned) getExtValue(Alignment);
5092
5093 return false;
5094 }
5095
5096 return true;
5097 }
Richard Smith6cbd65d2013-07-11 02:27:57 +00005098 default:
5099 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5100 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005101}
Chris Lattner05706e882008-07-11 18:11:29 +00005102
5103//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005104// Member Pointer Evaluation
5105//===----------------------------------------------------------------------===//
5106
5107namespace {
5108class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005109 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005110 MemberPtr &Result;
5111
5112 bool Success(const ValueDecl *D) {
5113 Result = MemberPtr(D);
5114 return true;
5115 }
5116public:
5117
5118 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5119 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5120
Richard Smith2e312c82012-03-03 22:46:17 +00005121 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005122 Result.setFrom(V);
5123 return true;
5124 }
Richard Smithfddd3842011-12-30 21:15:51 +00005125 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005126 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005127 }
5128
5129 bool VisitCastExpr(const CastExpr *E);
5130 bool VisitUnaryAddrOf(const UnaryOperator *E);
5131};
5132} // end anonymous namespace
5133
5134static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5135 EvalInfo &Info) {
5136 assert(E->isRValue() && E->getType()->isMemberPointerType());
5137 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5138}
5139
5140bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5141 switch (E->getCastKind()) {
5142 default:
5143 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5144
5145 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005146 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005147 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005148
5149 case CK_BaseToDerivedMemberPointer: {
5150 if (!Visit(E->getSubExpr()))
5151 return false;
5152 if (E->path_empty())
5153 return true;
5154 // Base-to-derived member pointer casts store the path in derived-to-base
5155 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5156 // the wrong end of the derived->base arc, so stagger the path by one class.
5157 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5158 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5159 PathI != PathE; ++PathI) {
5160 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5161 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5162 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005163 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005164 }
5165 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5166 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005167 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005168 return true;
5169 }
5170
5171 case CK_DerivedToBaseMemberPointer:
5172 if (!Visit(E->getSubExpr()))
5173 return false;
5174 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5175 PathE = E->path_end(); PathI != PathE; ++PathI) {
5176 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5177 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5178 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005179 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005180 }
5181 return true;
5182 }
5183}
5184
5185bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5186 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5187 // member can be formed.
5188 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5189}
5190
5191//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005192// Record Evaluation
5193//===----------------------------------------------------------------------===//
5194
5195namespace {
5196 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005197 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005198 const LValue &This;
5199 APValue &Result;
5200 public:
5201
5202 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5203 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5204
Richard Smith2e312c82012-03-03 22:46:17 +00005205 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005206 Result = V;
5207 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005208 }
Richard Smithfddd3842011-12-30 21:15:51 +00005209 bool ZeroInitialization(const Expr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005210
Richard Smith52a980a2015-08-28 02:43:42 +00005211 bool VisitCallExpr(const CallExpr *E) {
5212 return handleCallExpr(E, Result, &This);
5213 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005214 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005215 bool VisitInitListExpr(const InitListExpr *E);
5216 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005217 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005218 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005219}
Richard Smithd62306a2011-11-10 06:34:14 +00005220
Richard Smithfddd3842011-12-30 21:15:51 +00005221/// Perform zero-initialization on an object of non-union class type.
5222/// C++11 [dcl.init]p5:
5223/// To zero-initialize an object or reference of type T means:
5224/// [...]
5225/// -- if T is a (possibly cv-qualified) non-union class type,
5226/// each non-static data member and each base-class subobject is
5227/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005228static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5229 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005230 const LValue &This, APValue &Result) {
5231 assert(!RD->isUnion() && "Expected non-union class type");
5232 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5233 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005234 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005235
John McCalld7bca762012-05-01 00:38:49 +00005236 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005237 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5238
5239 if (CD) {
5240 unsigned Index = 0;
5241 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005242 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005243 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5244 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005245 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5246 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005247 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005248 Result.getStructBase(Index)))
5249 return false;
5250 }
5251 }
5252
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005253 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005254 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005255 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005256 continue;
5257
5258 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005259 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005260 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005261
David Blaikie2d7c57e2012-04-30 02:36:29 +00005262 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005263 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005264 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005265 return false;
5266 }
5267
5268 return true;
5269}
5270
5271bool RecordExprEvaluator::ZeroInitialization(const Expr *E) {
5272 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005273 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005274 if (RD->isUnion()) {
5275 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5276 // object's first non-static named data member is zero-initialized
5277 RecordDecl::field_iterator I = RD->field_begin();
5278 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005279 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005280 return true;
5281 }
5282
5283 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005284 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005285 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005286 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005287 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005288 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005289 }
5290
Richard Smith5d108602012-02-17 00:44:16 +00005291 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005292 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005293 return false;
5294 }
5295
Richard Smitha8105bc2012-01-06 16:39:00 +00005296 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005297}
5298
Richard Smithe97cbd72011-11-11 04:05:33 +00005299bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5300 switch (E->getCastKind()) {
5301 default:
5302 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5303
5304 case CK_ConstructorConversion:
5305 return Visit(E->getSubExpr());
5306
5307 case CK_DerivedToBase:
5308 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005309 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005310 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005311 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005312 if (!DerivedObject.isStruct())
5313 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005314
5315 // Derived-to-base rvalue conversion: just slice off the derived part.
5316 APValue *Value = &DerivedObject;
5317 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5318 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5319 PathE = E->path_end(); PathI != PathE; ++PathI) {
5320 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5321 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5322 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5323 RD = Base;
5324 }
5325 Result = *Value;
5326 return true;
5327 }
5328 }
5329}
5330
Richard Smithd62306a2011-11-10 06:34:14 +00005331bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5332 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005333 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005334 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5335
5336 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005337 const FieldDecl *Field = E->getInitializedFieldInUnion();
5338 Result = APValue(Field);
5339 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005340 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005341
5342 // If the initializer list for a union does not contain any elements, the
5343 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005344 // FIXME: The element should be initialized from an initializer list.
5345 // Is this difference ever observable for initializer lists which
5346 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005347 ImplicitValueInitExpr VIE(Field->getType());
5348 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5349
Richard Smithd62306a2011-11-10 06:34:14 +00005350 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005351 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5352 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005353
5354 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5355 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5356 isa<CXXDefaultInitExpr>(InitExpr));
5357
Richard Smithb228a862012-02-15 02:18:13 +00005358 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005359 }
5360
5361 assert((!isa<CXXRecordDecl>(RD) || !cast<CXXRecordDecl>(RD)->getNumBases()) &&
5362 "initializer list for class with base classes");
Aaron Ballman62e47c42014-03-10 13:43:55 +00005363 Result = APValue(APValue::UninitStruct(), 0,
5364 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005365 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005366 bool Success = true;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005367 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005368 // Anonymous bit-fields are not considered members of the class for
5369 // purposes of aggregate initialization.
5370 if (Field->isUnnamedBitfield())
5371 continue;
5372
5373 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005374
Richard Smith253c2a32012-01-27 01:14:48 +00005375 bool HaveInit = ElementNo < E->getNumInits();
5376
5377 // FIXME: Diagnostics here should point to the end of the initializer
5378 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005379 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005380 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005381 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005382
5383 // Perform an implicit value-initialization for members beyond the end of
5384 // the initializer list.
5385 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005386 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005387
Richard Smith852c9db2013-04-20 22:23:05 +00005388 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5389 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5390 isa<CXXDefaultInitExpr>(Init));
5391
Richard Smith49ca8aa2013-08-06 07:09:20 +00005392 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5393 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5394 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005395 FieldVal, Field))) {
Richard Smith253c2a32012-01-27 01:14:48 +00005396 if (!Info.keepEvaluatingAfterFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005397 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005398 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005399 }
5400 }
5401
Richard Smith253c2a32012-01-27 01:14:48 +00005402 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005403}
5404
5405bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
5406 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005407 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5408
Richard Smithfddd3842011-12-30 21:15:51 +00005409 bool ZeroInit = E->requiresZeroInitialization();
5410 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005411 // If we've already performed zero-initialization, we're already done.
5412 if (!Result.isUninit())
5413 return true;
5414
Richard Smithda3f4fd2014-03-05 23:32:50 +00005415 // We can get here in two different ways:
5416 // 1) We're performing value-initialization, and should zero-initialize
5417 // the object, or
5418 // 2) We're performing default-initialization of an object with a trivial
5419 // constexpr default constructor, in which case we should start the
5420 // lifetimes of all the base subobjects (there can be no data member
5421 // subobjects in this case) per [basic.life]p1.
5422 // Either way, ZeroInitialization is appropriate.
5423 return ZeroInitialization(E);
Richard Smithcc36f692011-12-22 02:22:31 +00005424 }
5425
Craig Topper36250ad2014-05-12 05:36:57 +00005426 const FunctionDecl *Definition = nullptr;
Richard Smithd62306a2011-11-10 06:34:14 +00005427 FD->getBody(Definition);
5428
Richard Smith357362d2011-12-13 06:39:58 +00005429 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5430 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005431
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005432 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005433 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005434 if (const MaterializeTemporaryExpr *ME
5435 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5436 return Visit(ME->GetTemporaryExpr());
5437
Richard Smithfddd3842011-12-30 21:15:51 +00005438 if (ZeroInit && !ZeroInitialization(E))
5439 return false;
5440
Craig Topper5fc8fc22014-08-27 06:28:36 +00005441 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005442 return HandleConstructorCall(E->getExprLoc(), This, Args,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005443 cast<CXXConstructorDecl>(Definition), Info,
5444 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005445}
5446
Richard Smithcc1b96d2013-06-12 22:31:48 +00005447bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5448 const CXXStdInitializerListExpr *E) {
5449 const ConstantArrayType *ArrayType =
5450 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5451
5452 LValue Array;
5453 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5454 return false;
5455
5456 // Get a pointer to the first element of the array.
5457 Array.addArray(Info, E, ArrayType);
5458
5459 // FIXME: Perform the checks on the field types in SemaInit.
5460 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5461 RecordDecl::field_iterator Field = Record->field_begin();
5462 if (Field == Record->field_end())
5463 return Error(E);
5464
5465 // Start pointer.
5466 if (!Field->getType()->isPointerType() ||
5467 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5468 ArrayType->getElementType()))
5469 return Error(E);
5470
5471 // FIXME: What if the initializer_list type has base classes, etc?
5472 Result = APValue(APValue::UninitStruct(), 0, 2);
5473 Array.moveInto(Result.getStructField(0));
5474
5475 if (++Field == Record->field_end())
5476 return Error(E);
5477
5478 if (Field->getType()->isPointerType() &&
5479 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5480 ArrayType->getElementType())) {
5481 // End pointer.
5482 if (!HandleLValueArrayAdjustment(Info, E, Array,
5483 ArrayType->getElementType(),
5484 ArrayType->getSize().getZExtValue()))
5485 return false;
5486 Array.moveInto(Result.getStructField(1));
5487 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5488 // Length.
5489 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5490 else
5491 return Error(E);
5492
5493 if (++Field != Record->field_end())
5494 return Error(E);
5495
5496 return true;
5497}
5498
Richard Smithd62306a2011-11-10 06:34:14 +00005499static bool EvaluateRecord(const Expr *E, const LValue &This,
5500 APValue &Result, EvalInfo &Info) {
5501 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005502 "can't evaluate expression as a record rvalue");
5503 return RecordExprEvaluator(Info, This, Result).Visit(E);
5504}
5505
5506//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005507// Temporary Evaluation
5508//
5509// Temporaries are represented in the AST as rvalues, but generally behave like
5510// lvalues. The full-object of which the temporary is a subobject is implicitly
5511// materialized so that a reference can bind to it.
5512//===----------------------------------------------------------------------===//
5513namespace {
5514class TemporaryExprEvaluator
5515 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5516public:
5517 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5518 LValueExprEvaluatorBaseTy(Info, Result) {}
5519
5520 /// Visit an expression which constructs the value of this temporary.
5521 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005522 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005523 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5524 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005525 }
5526
5527 bool VisitCastExpr(const CastExpr *E) {
5528 switch (E->getCastKind()) {
5529 default:
5530 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5531
5532 case CK_ConstructorConversion:
5533 return VisitConstructExpr(E->getSubExpr());
5534 }
5535 }
5536 bool VisitInitListExpr(const InitListExpr *E) {
5537 return VisitConstructExpr(E);
5538 }
5539 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5540 return VisitConstructExpr(E);
5541 }
5542 bool VisitCallExpr(const CallExpr *E) {
5543 return VisitConstructExpr(E);
5544 }
Richard Smith513955c2014-12-17 19:24:30 +00005545 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5546 return VisitConstructExpr(E);
5547 }
Richard Smith027bf112011-11-17 22:56:20 +00005548};
5549} // end anonymous namespace
5550
5551/// Evaluate an expression of record type as a temporary.
5552static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005553 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005554 return TemporaryExprEvaluator(Info, Result).Visit(E);
5555}
5556
5557//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005558// Vector Evaluation
5559//===----------------------------------------------------------------------===//
5560
5561namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005562 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005563 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005564 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005565 public:
Mike Stump11289f42009-09-09 15:08:12 +00005566
Richard Smith2d406342011-10-22 21:10:00 +00005567 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5568 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005569
Richard Smith2d406342011-10-22 21:10:00 +00005570 bool Success(const ArrayRef<APValue> &V, const Expr *E) {
5571 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5572 // FIXME: remove this APValue copy.
5573 Result = APValue(V.data(), V.size());
5574 return true;
5575 }
Richard Smith2e312c82012-03-03 22:46:17 +00005576 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005577 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005578 Result = V;
5579 return true;
5580 }
Richard Smithfddd3842011-12-30 21:15:51 +00005581 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005582
Richard Smith2d406342011-10-22 21:10:00 +00005583 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005584 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005585 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005586 bool VisitInitListExpr(const InitListExpr *E);
5587 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005588 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005589 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005590 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005591 };
5592} // end anonymous namespace
5593
5594static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005595 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005596 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005597}
5598
Richard Smith2d406342011-10-22 21:10:00 +00005599bool VectorExprEvaluator::VisitCastExpr(const CastExpr* E) {
5600 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005601 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005602
Richard Smith161f09a2011-12-06 22:44:34 +00005603 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005604 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005605
Eli Friedmanc757de22011-03-25 00:43:55 +00005606 switch (E->getCastKind()) {
5607 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005608 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005609 if (SETy->isIntegerType()) {
5610 APSInt IntResult;
5611 if (!EvaluateInteger(SE, IntResult, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005612 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005613 Val = APValue(IntResult);
Eli Friedmanc757de22011-03-25 00:43:55 +00005614 } else if (SETy->isRealFloatingType()) {
5615 APFloat F(0.0);
5616 if (!EvaluateFloat(SE, F, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005617 return false;
Richard Smith2d406342011-10-22 21:10:00 +00005618 Val = APValue(F);
Eli Friedmanc757de22011-03-25 00:43:55 +00005619 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005620 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005621 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005622
5623 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005624 SmallVector<APValue, 4> Elts(NElts, Val);
5625 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005626 }
Eli Friedman803acb32011-12-22 03:51:45 +00005627 case CK_BitCast: {
5628 // Evaluate the operand into an APInt we can extract from.
5629 llvm::APInt SValInt;
5630 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5631 return false;
5632 // Extract the elements
5633 QualType EltTy = VTy->getElementType();
5634 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5635 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5636 SmallVector<APValue, 4> Elts;
5637 if (EltTy->isRealFloatingType()) {
5638 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005639 unsigned FloatEltSize = EltSize;
5640 if (&Sem == &APFloat::x87DoubleExtended)
5641 FloatEltSize = 80;
5642 for (unsigned i = 0; i < NElts; i++) {
5643 llvm::APInt Elt;
5644 if (BigEndian)
5645 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5646 else
5647 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005648 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005649 }
5650 } else if (EltTy->isIntegerType()) {
5651 for (unsigned i = 0; i < NElts; i++) {
5652 llvm::APInt Elt;
5653 if (BigEndian)
5654 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5655 else
5656 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5657 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5658 }
5659 } else {
5660 return Error(E);
5661 }
5662 return Success(Elts, E);
5663 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005664 default:
Richard Smith11562c52011-10-28 17:51:58 +00005665 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005666 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005667}
5668
Richard Smith2d406342011-10-22 21:10:00 +00005669bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005670VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005671 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005672 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005673 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005674
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005675 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005676 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005677
Eli Friedmanb9c71292012-01-03 23:24:20 +00005678 // The number of initializers can be less than the number of
5679 // vector elements. For OpenCL, this can be due to nested vector
5680 // initialization. For GCC compatibility, missing trailing elements
5681 // should be initialized with zeroes.
5682 unsigned CountInits = 0, CountElts = 0;
5683 while (CountElts < NumElements) {
5684 // Handle nested vector initialization.
5685 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005686 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005687 APValue v;
5688 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5689 return Error(E);
5690 unsigned vlen = v.getVectorLength();
5691 for (unsigned j = 0; j < vlen; j++)
5692 Elements.push_back(v.getVectorElt(j));
5693 CountElts += vlen;
5694 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005695 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005696 if (CountInits < NumInits) {
5697 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005698 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005699 } else // trailing integer zero.
5700 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5701 Elements.push_back(APValue(sInt));
5702 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005703 } else {
5704 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005705 if (CountInits < NumInits) {
5706 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005707 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005708 } else // trailing float zero.
5709 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5710 Elements.push_back(APValue(f));
5711 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005712 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005713 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005714 }
Richard Smith2d406342011-10-22 21:10:00 +00005715 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005716}
5717
Richard Smith2d406342011-10-22 21:10:00 +00005718bool
Richard Smithfddd3842011-12-30 21:15:51 +00005719VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005720 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005721 QualType EltTy = VT->getElementType();
5722 APValue ZeroElement;
5723 if (EltTy->isIntegerType())
5724 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5725 else
5726 ZeroElement =
5727 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5728
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005729 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005730 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005731}
5732
Richard Smith2d406342011-10-22 21:10:00 +00005733bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005734 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005735 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005736}
5737
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005738//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005739// Array Evaluation
5740//===----------------------------------------------------------------------===//
5741
5742namespace {
5743 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005744 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005745 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005746 APValue &Result;
5747 public:
5748
Richard Smithd62306a2011-11-10 06:34:14 +00005749 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5750 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00005751
5752 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00005753 assert((V.isArray() || V.isLValue()) &&
5754 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00005755 Result = V;
5756 return true;
5757 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005758
Richard Smithfddd3842011-12-30 21:15:51 +00005759 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005760 const ConstantArrayType *CAT =
5761 Info.Ctx.getAsConstantArrayType(E->getType());
5762 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005763 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00005764
5765 Result = APValue(APValue::UninitArray(), 0,
5766 CAT->getSize().getZExtValue());
5767 if (!Result.hasArrayFiller()) return true;
5768
Richard Smithfddd3842011-12-30 21:15:51 +00005769 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00005770 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005771 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00005772 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00005773 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00005774 }
5775
Richard Smith52a980a2015-08-28 02:43:42 +00005776 bool VisitCallExpr(const CallExpr *E) {
5777 return handleCallExpr(E, Result, &This);
5778 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005779 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00005780 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00005781 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
5782 const LValue &Subobject,
5783 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00005784 };
5785} // end anonymous namespace
5786
Richard Smithd62306a2011-11-10 06:34:14 +00005787static bool EvaluateArray(const Expr *E, const LValue &This,
5788 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00005789 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00005790 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005791}
5792
5793bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5794 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
5795 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00005796 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00005797
Richard Smithca2cfbf2011-12-22 01:07:19 +00005798 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
5799 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00005800 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00005801 LValue LV;
5802 if (!EvaluateLValue(E->getInit(0), LV, Info))
5803 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00005804 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00005805 LV.moveInto(Val);
5806 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00005807 }
5808
Richard Smith253c2a32012-01-27 01:14:48 +00005809 bool Success = true;
5810
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005811 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
5812 "zero-initialized array shouldn't have any initialized elts");
5813 APValue Filler;
5814 if (Result.isArray() && Result.hasArrayFiller())
5815 Filler = Result.getArrayFiller();
5816
Richard Smith9543c5e2013-04-22 14:44:29 +00005817 unsigned NumEltsToInit = E->getNumInits();
5818 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005819 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00005820
5821 // If the initializer might depend on the array index, run it for each
5822 // array element. For now, just whitelist non-class value-initialization.
5823 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
5824 NumEltsToInit = NumElts;
5825
5826 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005827
5828 // If the array was previously zero-initialized, preserve the
5829 // zero-initialized values.
5830 if (!Filler.isUninit()) {
5831 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
5832 Result.getArrayInitializedElt(I) = Filler;
5833 if (Result.hasArrayFiller())
5834 Result.getArrayFiller() = Filler;
5835 }
5836
Richard Smithd62306a2011-11-10 06:34:14 +00005837 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00005838 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00005839 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
5840 const Expr *Init =
5841 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00005842 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00005843 Info, Subobject, Init) ||
5844 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00005845 CAT->getElementType(), 1)) {
5846 if (!Info.keepEvaluatingAfterFailure())
5847 return false;
5848 Success = false;
5849 }
Richard Smithd62306a2011-11-10 06:34:14 +00005850 }
Richard Smithf3e9e432011-11-07 09:22:26 +00005851
Richard Smith9543c5e2013-04-22 14:44:29 +00005852 if (!Result.hasArrayFiller())
5853 return Success;
5854
5855 // If we get here, we have a trivial filler, which we can just evaluate
5856 // once and splat over the rest of the array elements.
5857 assert(FillerExpr && "no array filler for incomplete init list");
5858 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
5859 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00005860}
5861
Richard Smith027bf112011-11-17 22:56:20 +00005862bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005863 return VisitCXXConstructExpr(E, This, &Result, E->getType());
5864}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005865
Richard Smith9543c5e2013-04-22 14:44:29 +00005866bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5867 const LValue &Subobject,
5868 APValue *Value,
5869 QualType Type) {
5870 bool HadZeroInit = !Value->isUninit();
5871
5872 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
5873 unsigned N = CAT->getSize().getZExtValue();
5874
5875 // Preserve the array filler if we had prior zero-initialization.
5876 APValue Filler =
5877 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
5878 : APValue();
5879
5880 *Value = APValue(APValue::UninitArray(), N, N);
5881
5882 if (HadZeroInit)
5883 for (unsigned I = 0; I != N; ++I)
5884 Value->getArrayInitializedElt(I) = Filler;
5885
5886 // Initialize the elements.
5887 LValue ArrayElt = Subobject;
5888 ArrayElt.addArray(Info, E, CAT);
5889 for (unsigned I = 0; I != N; ++I)
5890 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
5891 CAT->getElementType()) ||
5892 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
5893 CAT->getElementType(), 1))
5894 return false;
5895
5896 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005897 }
Richard Smith027bf112011-11-17 22:56:20 +00005898
Richard Smith9543c5e2013-04-22 14:44:29 +00005899 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00005900 return Error(E);
5901
Richard Smith027bf112011-11-17 22:56:20 +00005902 const CXXConstructorDecl *FD = E->getConstructor();
Richard Smithcc36f692011-12-22 02:22:31 +00005903
Richard Smithfddd3842011-12-30 21:15:51 +00005904 bool ZeroInit = E->requiresZeroInitialization();
5905 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005906 if (HadZeroInit)
5907 return true;
5908
Richard Smithda3f4fd2014-03-05 23:32:50 +00005909 // See RecordExprEvaluator::VisitCXXConstructExpr for explanation.
5910 ImplicitValueInitExpr VIE(Type);
5911 return EvaluateInPlace(*Value, Info, Subobject, &VIE);
Richard Smithcc36f692011-12-22 02:22:31 +00005912 }
5913
Craig Topper36250ad2014-05-12 05:36:57 +00005914 const FunctionDecl *Definition = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00005915 FD->getBody(Definition);
5916
Richard Smith357362d2011-12-13 06:39:58 +00005917 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition))
5918 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005919
Richard Smith9eae7232012-01-12 18:54:33 +00005920 if (ZeroInit && !HadZeroInit) {
Richard Smith9543c5e2013-04-22 14:44:29 +00005921 ImplicitValueInitExpr VIE(Type);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005922 if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005923 return false;
5924 }
5925
Craig Topper5fc8fc22014-08-27 06:28:36 +00005926 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith253c2a32012-01-27 01:14:48 +00005927 return HandleConstructorCall(E->getExprLoc(), Subobject, Args,
Richard Smith027bf112011-11-17 22:56:20 +00005928 cast<CXXConstructorDecl>(Definition),
Richard Smith1b9f2eb2012-07-07 22:48:24 +00005929 Info, *Value);
Richard Smith027bf112011-11-17 22:56:20 +00005930}
5931
Richard Smithf3e9e432011-11-07 09:22:26 +00005932//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005933// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005934//
5935// As a GNU extension, we support casting pointers to sufficiently-wide integer
5936// types and back in constant folding. Integer values are thus represented
5937// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00005938//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005939
5940namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005941class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005942 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00005943 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005944public:
Richard Smith2e312c82012-03-03 22:46:17 +00005945 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005946 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005947
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005948 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005949 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00005950 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005951 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005952 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00005953 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005954 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005955 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005956 return true;
5957 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005958 bool Success(const llvm::APSInt &SI, const Expr *E) {
5959 return Success(SI, E, Result);
5960 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005961
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005962 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005963 assert(E->getType()->isIntegralOrEnumerationType() &&
5964 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00005965 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00005966 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005967 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00005968 Result.getInt().setIsUnsigned(
5969 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005970 return true;
5971 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005972 bool Success(const llvm::APInt &I, const Expr *E) {
5973 return Success(I, E, Result);
5974 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005975
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005976 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00005977 assert(E->getType()->isIntegralOrEnumerationType() &&
5978 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00005979 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005980 return true;
5981 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00005982 bool Success(uint64_t Value, const Expr *E) {
5983 return Success(Value, E, Result);
5984 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00005985
Ken Dyckdbc01912011-03-11 02:13:43 +00005986 bool Success(CharUnits Size, const Expr *E) {
5987 return Success(Size.getQuantity(), E);
5988 }
5989
Richard Smith2e312c82012-03-03 22:46:17 +00005990 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00005991 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00005992 Result = V;
5993 return true;
5994 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005995 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00005996 }
Mike Stump11289f42009-09-09 15:08:12 +00005997
Richard Smithfddd3842011-12-30 21:15:51 +00005998 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00005999
Peter Collingbournee9200682011-05-13 03:29:01 +00006000 //===--------------------------------------------------------------------===//
6001 // Visitor Methods
6002 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006003
Chris Lattner7174bf32008-07-12 00:38:25 +00006004 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006005 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006006 }
6007 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006008 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006009 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006010
6011 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6012 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006013 if (CheckReferencedDecl(E, E->getDecl()))
6014 return true;
6015
6016 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006017 }
6018 bool VisitMemberExpr(const MemberExpr *E) {
6019 if (CheckReferencedDecl(E, E->getMemberDecl())) {
Richard Smith11562c52011-10-28 17:51:58 +00006020 VisitIgnoredValue(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006021 return true;
6022 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006023
6024 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006025 }
6026
Peter Collingbournee9200682011-05-13 03:29:01 +00006027 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006028 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006029 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006030 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006031
Peter Collingbournee9200682011-05-13 03:29:01 +00006032 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006033 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006034
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006035 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006036 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006037 }
Mike Stump11289f42009-09-09 15:08:12 +00006038
Ted Kremeneke65b0862012-03-06 20:05:56 +00006039 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6040 return Success(E->getValue(), E);
6041 }
6042
Richard Smith4ce706a2011-10-11 21:43:33 +00006043 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006044 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006045 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006046 }
6047
Douglas Gregor29c42f22012-02-24 07:38:34 +00006048 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6049 return Success(E->getValue(), E);
6050 }
6051
John Wiegley6242b6a2011-04-28 00:16:57 +00006052 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6053 return Success(E->getValue(), E);
6054 }
6055
John Wiegleyf9f65842011-04-25 06:54:41 +00006056 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6057 return Success(E->getValue(), E);
6058 }
6059
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006060 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006061 bool VisitUnaryImag(const UnaryOperator *E);
6062
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006063 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006064 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006065
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006066private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006067 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006068 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006069};
Chris Lattner05706e882008-07-11 18:11:29 +00006070} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006071
Richard Smith11562c52011-10-28 17:51:58 +00006072/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6073/// produce either the integer value or a pointer.
6074///
6075/// GCC has a heinous extension which folds casts between pointer types and
6076/// pointer-sized integral types. We support this by allowing the evaluation of
6077/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6078/// Some simple arithmetic on such values is supported (they are treated much
6079/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006080static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006081 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006082 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006083 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006084}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006085
Richard Smithf57d8cb2011-12-09 22:58:01 +00006086static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006087 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006088 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006089 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006090 if (!Val.isInt()) {
6091 // FIXME: It would be better to produce the diagnostic for casting
6092 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00006093 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006094 return false;
6095 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006096 Result = Val.getInt();
6097 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006098}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006099
Richard Smithf57d8cb2011-12-09 22:58:01 +00006100/// Check whether the given declaration can be directly converted to an integral
6101/// rvalue. If not, no diagnostic is produced; there are other things we can
6102/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006103bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006104 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006105 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006106 // Check for signedness/width mismatches between E type and ECD value.
6107 bool SameSign = (ECD->getInitVal().isSigned()
6108 == E->getType()->isSignedIntegerOrEnumerationType());
6109 bool SameWidth = (ECD->getInitVal().getBitWidth()
6110 == Info.Ctx.getIntWidth(E->getType()));
6111 if (SameSign && SameWidth)
6112 return Success(ECD->getInitVal(), E);
6113 else {
6114 // Get rid of mismatch (otherwise Success assertions will fail)
6115 // by computing a new value matching the type of E.
6116 llvm::APSInt Val = ECD->getInitVal();
6117 if (!SameSign)
6118 Val.setIsSigned(!ECD->getInitVal().isSigned());
6119 if (!SameWidth)
6120 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6121 return Success(Val, E);
6122 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006123 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006124 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006125}
6126
Chris Lattner86ee2862008-10-06 06:40:35 +00006127/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6128/// as GCC.
6129static int EvaluateBuiltinClassifyType(const CallExpr *E) {
6130 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006131 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006132 enum gcc_type_class {
6133 no_type_class = -1,
6134 void_type_class, integer_type_class, char_type_class,
6135 enumeral_type_class, boolean_type_class,
6136 pointer_type_class, reference_type_class, offset_type_class,
6137 real_type_class, complex_type_class,
6138 function_type_class, method_type_class,
6139 record_type_class, union_type_class,
6140 array_type_class, string_type_class,
6141 lang_type_class
6142 };
Mike Stump11289f42009-09-09 15:08:12 +00006143
6144 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006145 // ideal, however it is what gcc does.
6146 if (E->getNumArgs() == 0)
6147 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006148
Chris Lattner86ee2862008-10-06 06:40:35 +00006149 QualType ArgTy = E->getArg(0)->getType();
6150 if (ArgTy->isVoidType())
6151 return void_type_class;
6152 else if (ArgTy->isEnumeralType())
6153 return enumeral_type_class;
6154 else if (ArgTy->isBooleanType())
6155 return boolean_type_class;
6156 else if (ArgTy->isCharType())
6157 return string_type_class; // gcc doesn't appear to use char_type_class
6158 else if (ArgTy->isIntegerType())
6159 return integer_type_class;
6160 else if (ArgTy->isPointerType())
6161 return pointer_type_class;
6162 else if (ArgTy->isReferenceType())
6163 return reference_type_class;
6164 else if (ArgTy->isRealType())
6165 return real_type_class;
6166 else if (ArgTy->isComplexType())
6167 return complex_type_class;
6168 else if (ArgTy->isFunctionType())
6169 return function_type_class;
Douglas Gregor8385a062010-04-26 21:31:17 +00006170 else if (ArgTy->isStructureOrClassType())
Chris Lattner86ee2862008-10-06 06:40:35 +00006171 return record_type_class;
6172 else if (ArgTy->isUnionType())
6173 return union_type_class;
6174 else if (ArgTy->isArrayType())
6175 return array_type_class;
6176 else if (ArgTy->isUnionType())
6177 return union_type_class;
6178 else // FIXME: offset_type_class, method_type_class, & lang_type_class?
David Blaikie83d382b2011-09-23 05:06:16 +00006179 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006180}
6181
Richard Smith5fab0c92011-12-28 19:48:30 +00006182/// EvaluateBuiltinConstantPForLValue - Determine the result of
6183/// __builtin_constant_p when applied to the given lvalue.
6184///
6185/// An lvalue is only "constant" if it is a pointer or reference to the first
6186/// character of a string literal.
6187template<typename LValue>
6188static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006189 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006190 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6191}
6192
6193/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6194/// GCC as we can manage.
6195static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6196 QualType ArgType = Arg->getType();
6197
6198 // __builtin_constant_p always has one operand. The rules which gcc follows
6199 // are not precisely documented, but are as follows:
6200 //
6201 // - If the operand is of integral, floating, complex or enumeration type,
6202 // and can be folded to a known value of that type, it returns 1.
6203 // - If the operand and can be folded to a pointer to the first character
6204 // of a string literal (or such a pointer cast to an integral type), it
6205 // returns 1.
6206 //
6207 // Otherwise, it returns 0.
6208 //
6209 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6210 // its support for this does not currently work.
6211 if (ArgType->isIntegralOrEnumerationType()) {
6212 Expr::EvalResult Result;
6213 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6214 return false;
6215
6216 APValue &V = Result.Val;
6217 if (V.getKind() == APValue::Int)
6218 return true;
6219
6220 return EvaluateBuiltinConstantPForLValue(V);
6221 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6222 return Arg->isEvaluatable(Ctx);
6223 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6224 LValue LV;
6225 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006226 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006227 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6228 : EvaluatePointer(Arg, LV, Info)) &&
6229 !Status.HasSideEffects)
6230 return EvaluateBuiltinConstantPForLValue(LV);
6231 }
6232
6233 // Anything else isn't considered to be sufficiently constant.
6234 return false;
6235}
6236
John McCall95007602010-05-10 23:27:23 +00006237/// Retrieves the "underlying object type" of the given expression,
6238/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006239static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006240 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6241 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006242 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006243 } else if (const Expr *E = B.get<const Expr*>()) {
6244 if (isa<CompoundLiteralExpr>(E))
6245 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006246 }
6247
6248 return QualType();
6249}
6250
George Burgess IV3a03fab2015-09-04 21:28:13 +00006251/// A more selective version of E->IgnoreParenCasts for
6252/// TryEvaluateBuiltinObjectSize. This ignores casts/parens that serve only to
6253/// change the type of E.
6254/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6255///
6256/// Always returns an RValue with a pointer representation.
6257static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6258 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6259
6260 auto *NoParens = E->IgnoreParens();
6261 auto *Cast = dyn_cast<CastExpr>(NoParens);
6262 if (Cast == nullptr || Cast->getCastKind() == CK_DerivedToBase)
6263 return NoParens;
6264
6265 auto *SubExpr = Cast->getSubExpr();
6266 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6267 return NoParens;
6268 return ignorePointerCastsAndParens(SubExpr);
6269}
6270
George Burgess IVbdb5b262015-08-19 02:19:07 +00006271bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6272 unsigned Type) {
6273 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006274 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006275 {
6276 // The operand of __builtin_object_size is never evaluated for side-effects.
6277 // If there are any, but we can determine the pointed-to object anyway, then
6278 // ignore the side-effects.
6279 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006280 FoldOffsetRAII Fold(Info, Type & 1);
6281 const Expr *Ptr = ignorePointerCastsAndParens(E->getArg(0));
6282 if (!EvaluatePointer(Ptr, Base, Info))
Richard Smith01ade172012-05-23 04:13:20 +00006283 return false;
6284 }
John McCall95007602010-05-10 23:27:23 +00006285
George Burgess IVbdb5b262015-08-19 02:19:07 +00006286 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00006287 // If we point to before the start of the object, there are no accessible
6288 // bytes.
6289 if (BaseOffset.isNegative())
George Burgess IVbdb5b262015-08-19 02:19:07 +00006290 return Success(0, E);
6291
George Burgess IV3a03fab2015-09-04 21:28:13 +00006292 // In the case where we're not dealing with a subobject, we discard the
6293 // subobject bit.
6294 if (!Base.Designator.Invalid && Base.Designator.Entries.empty())
6295 Type = Type & ~1U;
6296
6297 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6298 // exist. If we can't verify the base, then we can't do that.
6299 //
6300 // As a special case, we produce a valid object size for an unknown object
6301 // with a known designator if Type & 1 is 1. For instance:
6302 //
6303 // extern struct X { char buff[32]; int a, b, c; } *p;
6304 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6305 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6306 //
6307 // This matches GCC's behavior.
6308 if ((Type & 1) == 0 && Base.InvalidBase)
Nico Weber19999b42015-08-18 20:32:55 +00006309 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006310
6311 // If Type & 1 is 0, the object in question is the complete object; reset to
6312 // a complete object designator in that case.
6313 //
6314 // If Type is 1 and we've lost track of the subobject, just find the complete
6315 // object instead. (If Type is 3, that's not correct behavior and we should
6316 // return 0 instead.)
6317 LValue End = Base;
6318 if (((Type & 1) == 0) || (End.Designator.Invalid && Type == 1)) {
6319 QualType T = getObjectType(End.getLValueBase());
6320 if (T.isNull())
6321 End.Designator.setInvalid();
6322 else {
6323 End.Designator = SubobjectDesignator(T);
6324 End.Offset = CharUnits::Zero();
6325 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006326 }
John McCall95007602010-05-10 23:27:23 +00006327
George Burgess IVbdb5b262015-08-19 02:19:07 +00006328 // If it is not possible to determine which objects ptr points to at compile
6329 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6330 // and (size_t) 0 for type 2 or 3.
6331 if (End.Designator.Invalid)
6332 return false;
6333
6334 // According to the GCC documentation, we want the size of the subobject
6335 // denoted by the pointer. But that's not quite right -- what we actually
6336 // want is the size of the immediately-enclosing array, if there is one.
6337 int64_t AmountToAdd = 1;
6338 if (End.Designator.MostDerivedArraySize &&
6339 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6340 // We got a pointer to an array. Step to its end.
6341 AmountToAdd = End.Designator.MostDerivedArraySize -
George Burgess IV3a03fab2015-09-04 21:28:13 +00006342 End.Designator.Entries.back().ArrayIndex;
6343 } else if (End.Designator.isOnePastTheEnd()) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006344 // We're already pointing at the end of the object.
6345 AmountToAdd = 0;
6346 }
6347
George Burgess IV3a03fab2015-09-04 21:28:13 +00006348 QualType PointeeType = End.Designator.MostDerivedType;
6349 assert(!PointeeType.isNull());
6350 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006351 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006352
George Burgess IVbdb5b262015-08-19 02:19:07 +00006353 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6354 AmountToAdd))
6355 return false;
John McCall95007602010-05-10 23:27:23 +00006356
George Burgess IVbdb5b262015-08-19 02:19:07 +00006357 auto EndOffset = End.getLValueOffset();
6358 if (BaseOffset > EndOffset)
6359 return Success(0, E);
6360
6361 return Success(EndOffset - BaseOffset, E);
John McCall95007602010-05-10 23:27:23 +00006362}
6363
Peter Collingbournee9200682011-05-13 03:29:01 +00006364bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006365 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006366 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006367 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006368
6369 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006370 // The type was checked when we built the expression.
6371 unsigned Type =
6372 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6373 assert(Type <= 3 && "unexpected type");
6374
6375 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00006376 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006377
Richard Smith0421ce72012-08-07 04:16:51 +00006378 // If evaluating the argument has side-effects, we can't determine the size
6379 // of the object, and so we lower it to unknown now. CodeGen relies on us to
6380 // handle all cases where the expression has side-effects.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006381 // Likewise, if Type is 3, we must handle this because CodeGen cannot give a
6382 // conservatively correct answer in that case.
6383 if (E->getArg(0)->HasSideEffects(Info.Ctx) || Type == 3)
6384 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00006385
Richard Smith01ade172012-05-23 04:13:20 +00006386 // Expression had no side effects, but we couldn't statically determine the
6387 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006388 switch (Info.EvalMode) {
6389 case EvalInfo::EM_ConstantExpression:
6390 case EvalInfo::EM_PotentialConstantExpression:
6391 case EvalInfo::EM_ConstantFold:
6392 case EvalInfo::EM_EvaluateForOverflow:
6393 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +00006394 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006395 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006396 return Error(E);
6397 case EvalInfo::EM_ConstantExpressionUnevaluated:
6398 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006399 // Reduce it to a constant now.
6400 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006401 }
Mike Stump722cedf2009-10-26 18:35:08 +00006402 }
6403
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006404 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006405 case Builtin::BI__builtin_bswap32:
6406 case Builtin::BI__builtin_bswap64: {
6407 APSInt Val;
6408 if (!EvaluateInteger(E->getArg(0), Val, Info))
6409 return false;
6410
6411 return Success(Val.byteSwap(), E);
6412 }
6413
Richard Smith8889a3d2013-06-13 06:26:32 +00006414 case Builtin::BI__builtin_classify_type:
6415 return Success(EvaluateBuiltinClassifyType(E), E);
6416
6417 // FIXME: BI__builtin_clrsb
6418 // FIXME: BI__builtin_clrsbl
6419 // FIXME: BI__builtin_clrsbll
6420
Richard Smith80b3c8e2013-06-13 05:04:16 +00006421 case Builtin::BI__builtin_clz:
6422 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006423 case Builtin::BI__builtin_clzll:
6424 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006425 APSInt Val;
6426 if (!EvaluateInteger(E->getArg(0), Val, Info))
6427 return false;
6428 if (!Val)
6429 return Error(E);
6430
6431 return Success(Val.countLeadingZeros(), E);
6432 }
6433
Richard Smith8889a3d2013-06-13 06:26:32 +00006434 case Builtin::BI__builtin_constant_p:
6435 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6436
Richard Smith80b3c8e2013-06-13 05:04:16 +00006437 case Builtin::BI__builtin_ctz:
6438 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006439 case Builtin::BI__builtin_ctzll:
6440 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006441 APSInt Val;
6442 if (!EvaluateInteger(E->getArg(0), Val, Info))
6443 return false;
6444 if (!Val)
6445 return Error(E);
6446
6447 return Success(Val.countTrailingZeros(), E);
6448 }
6449
Richard Smith8889a3d2013-06-13 06:26:32 +00006450 case Builtin::BI__builtin_eh_return_data_regno: {
6451 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6452 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6453 return Success(Operand, E);
6454 }
6455
6456 case Builtin::BI__builtin_expect:
6457 return Visit(E->getArg(0));
6458
6459 case Builtin::BI__builtin_ffs:
6460 case Builtin::BI__builtin_ffsl:
6461 case Builtin::BI__builtin_ffsll: {
6462 APSInt Val;
6463 if (!EvaluateInteger(E->getArg(0), Val, Info))
6464 return false;
6465
6466 unsigned N = Val.countTrailingZeros();
6467 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6468 }
6469
6470 case Builtin::BI__builtin_fpclassify: {
6471 APFloat Val(0.0);
6472 if (!EvaluateFloat(E->getArg(5), Val, Info))
6473 return false;
6474 unsigned Arg;
6475 switch (Val.getCategory()) {
6476 case APFloat::fcNaN: Arg = 0; break;
6477 case APFloat::fcInfinity: Arg = 1; break;
6478 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6479 case APFloat::fcZero: Arg = 4; break;
6480 }
6481 return Visit(E->getArg(Arg));
6482 }
6483
6484 case Builtin::BI__builtin_isinf_sign: {
6485 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006486 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006487 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6488 }
6489
Richard Smithea3019d2013-10-15 19:07:14 +00006490 case Builtin::BI__builtin_isinf: {
6491 APFloat Val(0.0);
6492 return EvaluateFloat(E->getArg(0), Val, Info) &&
6493 Success(Val.isInfinity() ? 1 : 0, E);
6494 }
6495
6496 case Builtin::BI__builtin_isfinite: {
6497 APFloat Val(0.0);
6498 return EvaluateFloat(E->getArg(0), Val, Info) &&
6499 Success(Val.isFinite() ? 1 : 0, E);
6500 }
6501
6502 case Builtin::BI__builtin_isnan: {
6503 APFloat Val(0.0);
6504 return EvaluateFloat(E->getArg(0), Val, Info) &&
6505 Success(Val.isNaN() ? 1 : 0, E);
6506 }
6507
6508 case Builtin::BI__builtin_isnormal: {
6509 APFloat Val(0.0);
6510 return EvaluateFloat(E->getArg(0), Val, Info) &&
6511 Success(Val.isNormal() ? 1 : 0, E);
6512 }
6513
Richard Smith8889a3d2013-06-13 06:26:32 +00006514 case Builtin::BI__builtin_parity:
6515 case Builtin::BI__builtin_parityl:
6516 case Builtin::BI__builtin_parityll: {
6517 APSInt Val;
6518 if (!EvaluateInteger(E->getArg(0), Val, Info))
6519 return false;
6520
6521 return Success(Val.countPopulation() % 2, E);
6522 }
6523
Richard Smith80b3c8e2013-06-13 05:04:16 +00006524 case Builtin::BI__builtin_popcount:
6525 case Builtin::BI__builtin_popcountl:
6526 case Builtin::BI__builtin_popcountll: {
6527 APSInt Val;
6528 if (!EvaluateInteger(E->getArg(0), Val, Info))
6529 return false;
6530
6531 return Success(Val.countPopulation(), E);
6532 }
6533
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006534 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006535 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006536 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006537 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006538 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6539 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006540 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006541 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006542 case Builtin::BI__builtin_strlen: {
6543 // As an extension, we support __builtin_strlen() as a constant expression,
6544 // and support folding strlen() to a constant.
6545 LValue String;
6546 if (!EvaluatePointer(E->getArg(0), String, Info))
6547 return false;
6548
6549 // Fast path: if it's a string literal, search the string value.
6550 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
6551 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006552 // The string literal may have embedded null characters. Find the first
6553 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00006554 StringRef Str = S->getBytes();
6555 int64_t Off = String.Offset.getQuantity();
6556 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
6557 S->getCharByteWidth() == 1) {
6558 Str = Str.substr(Off);
6559
6560 StringRef::size_type Pos = Str.find(0);
6561 if (Pos != StringRef::npos)
6562 Str = Str.substr(0, Pos);
6563
6564 return Success(Str.size(), E);
6565 }
6566
6567 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006568 }
Richard Smithe6c19f22013-11-15 02:10:04 +00006569
6570 // Slow path: scan the bytes of the string looking for the terminating 0.
6571 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
6572 for (uint64_t Strlen = 0; /**/; ++Strlen) {
6573 APValue Char;
6574 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
6575 !Char.isInt())
6576 return false;
6577 if (!Char.getInt())
6578 return Success(Strlen, E);
6579 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
6580 return false;
6581 }
6582 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006583
Richard Smith01ba47d2012-04-13 00:45:38 +00006584 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00006585 case Builtin::BI__atomic_is_lock_free:
6586 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00006587 APSInt SizeVal;
6588 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
6589 return false;
6590
6591 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
6592 // of two less than the maximum inline atomic width, we know it is
6593 // lock-free. If the size isn't a power of two, or greater than the
6594 // maximum alignment where we promote atomics, we know it is not lock-free
6595 // (at least not in the sense of atomic_is_lock_free). Otherwise,
6596 // the answer can only be determined at runtime; for example, 16-byte
6597 // atomics have lock-free implementations on some, but not all,
6598 // x86-64 processors.
6599
6600 // Check power-of-two.
6601 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00006602 if (Size.isPowerOfTwo()) {
6603 // Check against inlining width.
6604 unsigned InlineWidthBits =
6605 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
6606 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
6607 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
6608 Size == CharUnits::One() ||
6609 E->getArg(1)->isNullPointerConstant(Info.Ctx,
6610 Expr::NPC_NeverValueDependent))
6611 // OK, we will inline appropriately-aligned operations of this size,
6612 // and _Atomic(T) is appropriately-aligned.
6613 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006614
Richard Smith01ba47d2012-04-13 00:45:38 +00006615 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
6616 castAs<PointerType>()->getPointeeType();
6617 if (!PointeeType->isIncompleteType() &&
6618 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
6619 // OK, we will inline operations on this object.
6620 return Success(1, E);
6621 }
6622 }
6623 }
Eli Friedmana4c26022011-10-17 21:44:23 +00006624
Richard Smith01ba47d2012-04-13 00:45:38 +00006625 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
6626 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00006627 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006628 }
Chris Lattner7174bf32008-07-12 00:38:25 +00006629}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006630
Richard Smith8b3497e2011-10-31 01:37:14 +00006631static bool HasSameBase(const LValue &A, const LValue &B) {
6632 if (!A.getLValueBase())
6633 return !B.getLValueBase();
6634 if (!B.getLValueBase())
6635 return false;
6636
Richard Smithce40ad62011-11-12 22:28:03 +00006637 if (A.getLValueBase().getOpaqueValue() !=
6638 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00006639 const Decl *ADecl = GetLValueBaseDecl(A);
6640 if (!ADecl)
6641 return false;
6642 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00006643 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00006644 return false;
6645 }
6646
6647 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00006648 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00006649}
6650
Richard Smithd20f1e62014-10-21 23:01:04 +00006651/// \brief Determine whether this is a pointer past the end of the complete
6652/// object referred to by the lvalue.
6653static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
6654 const LValue &LV) {
6655 // A null pointer can be viewed as being "past the end" but we don't
6656 // choose to look at it that way here.
6657 if (!LV.getLValueBase())
6658 return false;
6659
6660 // If the designator is valid and refers to a subobject, we're not pointing
6661 // past the end.
6662 if (!LV.getLValueDesignator().Invalid &&
6663 !LV.getLValueDesignator().isOnePastTheEnd())
6664 return false;
6665
David Majnemerc378ca52015-08-29 08:32:55 +00006666 // A pointer to an incomplete type might be past-the-end if the type's size is
6667 // zero. We cannot tell because the type is incomplete.
6668 QualType Ty = getType(LV.getLValueBase());
6669 if (Ty->isIncompleteType())
6670 return true;
6671
Richard Smithd20f1e62014-10-21 23:01:04 +00006672 // We're a past-the-end pointer if we point to the byte after the object,
6673 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00006674 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00006675 return LV.getLValueOffset() == Size;
6676}
6677
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006678namespace {
Richard Smith11562c52011-10-28 17:51:58 +00006679
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006680/// \brief Data recursive integer evaluator of certain binary operators.
6681///
6682/// We use a data recursive algorithm for binary operators so that we are able
6683/// to handle extreme cases of chained binary operators without causing stack
6684/// overflow.
6685class DataRecursiveIntBinOpEvaluator {
6686 struct EvalResult {
6687 APValue Val;
6688 bool Failed;
6689
6690 EvalResult() : Failed(false) { }
6691
6692 void swap(EvalResult &RHS) {
6693 Val.swap(RHS.Val);
6694 Failed = RHS.Failed;
6695 RHS.Failed = false;
6696 }
6697 };
6698
6699 struct Job {
6700 const Expr *E;
6701 EvalResult LHSResult; // meaningful only for binary operator expression.
6702 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00006703
David Blaikie73726062015-08-12 23:09:24 +00006704 Job() = default;
6705 Job(Job &&J)
6706 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
6707 StoredInfo(J.StoredInfo), OldEvalStatus(J.OldEvalStatus) {
6708 J.StoredInfo = nullptr;
6709 }
6710
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006711 void startSpeculativeEval(EvalInfo &Info) {
6712 OldEvalStatus = Info.EvalStatus;
Craig Topper36250ad2014-05-12 05:36:57 +00006713 Info.EvalStatus.Diag = nullptr;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006714 StoredInfo = &Info;
6715 }
6716 ~Job() {
6717 if (StoredInfo) {
6718 StoredInfo->EvalStatus = OldEvalStatus;
6719 }
6720 }
6721 private:
David Blaikie73726062015-08-12 23:09:24 +00006722 EvalInfo *StoredInfo = nullptr; // non-null if status changed.
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006723 Expr::EvalStatus OldEvalStatus;
6724 };
6725
6726 SmallVector<Job, 16> Queue;
6727
6728 IntExprEvaluator &IntEval;
6729 EvalInfo &Info;
6730 APValue &FinalResult;
6731
6732public:
6733 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
6734 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
6735
6736 /// \brief True if \param E is a binary operator that we are going to handle
6737 /// data recursively.
6738 /// We handle binary operators that are comma, logical, or that have operands
6739 /// with integral or enumeration type.
6740 static bool shouldEnqueue(const BinaryOperator *E) {
6741 return E->getOpcode() == BO_Comma ||
6742 E->isLogicalOp() ||
6743 (E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6744 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00006745 }
6746
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006747 bool Traverse(const BinaryOperator *E) {
6748 enqueue(E);
6749 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00006750 while (!Queue.empty())
6751 process(PrevResult);
6752
6753 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006754
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006755 FinalResult.swap(PrevResult.Val);
6756 return true;
6757 }
6758
6759private:
6760 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
6761 return IntEval.Success(Value, E, Result);
6762 }
6763 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
6764 return IntEval.Success(Value, E, Result);
6765 }
6766 bool Error(const Expr *E) {
6767 return IntEval.Error(E);
6768 }
6769 bool Error(const Expr *E, diag::kind D) {
6770 return IntEval.Error(E, D);
6771 }
6772
6773 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
6774 return Info.CCEDiag(E, D);
6775 }
6776
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006777 // \brief Returns true if visiting the RHS is necessary, false otherwise.
6778 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006779 bool &SuppressRHSDiags);
6780
6781 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6782 const BinaryOperator *E, APValue &Result);
6783
6784 void EvaluateExpr(const Expr *E, EvalResult &Result) {
6785 Result.Failed = !Evaluate(Result.Val, Info, E);
6786 if (Result.Failed)
6787 Result.Val = APValue();
6788 }
6789
Richard Trieuba4d0872012-03-21 23:30:30 +00006790 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006791
6792 void enqueue(const Expr *E) {
6793 E = E->IgnoreParens();
6794 Queue.resize(Queue.size()+1);
6795 Queue.back().E = E;
6796 Queue.back().Kind = Job::AnyExprKind;
6797 }
6798};
6799
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006800}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006801
6802bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006803 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006804 bool &SuppressRHSDiags) {
6805 if (E->getOpcode() == BO_Comma) {
6806 // Ignore LHS but note if we could not evaluate it.
6807 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00006808 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006809 return true;
6810 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006811
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006812 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006813 bool LHSAsBool;
6814 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006815 // We were able to evaluate the LHS, see if we can get away with not
6816 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00006817 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
6818 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006819 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006820 }
6821 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00006822 LHSResult.Failed = true;
6823
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006824 // Since we weren't able to evaluate the left hand side, it
6825 // must have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00006826 if (!Info.noteSideEffect())
6827 return false;
6828
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006829 // We can't evaluate the LHS; however, sometimes the result
6830 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6831 // Don't ignore RHS and suppress diagnostics from this arm.
6832 SuppressRHSDiags = true;
6833 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006834
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006835 return true;
6836 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00006837
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006838 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6839 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00006840
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006841 if (LHSResult.Failed && !Info.keepEvaluatingAfterFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006842 return false; // Ignore RHS;
6843
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006844 return true;
6845}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006846
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006847bool DataRecursiveIntBinOpEvaluator::
6848 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
6849 const BinaryOperator *E, APValue &Result) {
6850 if (E->getOpcode() == BO_Comma) {
6851 if (RHSResult.Failed)
6852 return false;
6853 Result = RHSResult.Val;
6854 return true;
6855 }
6856
6857 if (E->isLogicalOp()) {
6858 bool lhsResult, rhsResult;
6859 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
6860 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
6861
6862 if (LHSIsOK) {
6863 if (RHSIsOK) {
6864 if (E->getOpcode() == BO_LOr)
6865 return Success(lhsResult || rhsResult, E, Result);
6866 else
6867 return Success(lhsResult && rhsResult, E, Result);
6868 }
6869 } else {
6870 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006871 // We can't evaluate the LHS; however, sometimes the result
6872 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
6873 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006874 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006875 }
6876 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006877
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00006878 return false;
6879 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006880
6881 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
6882 E->getRHS()->getType()->isIntegralOrEnumerationType());
6883
6884 if (LHSResult.Failed || RHSResult.Failed)
6885 return false;
6886
6887 const APValue &LHSVal = LHSResult.Val;
6888 const APValue &RHSVal = RHSResult.Val;
6889
6890 // Handle cases like (unsigned long)&a + 4.
6891 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
6892 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006893 CharUnits AdditionalOffset =
6894 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006895 if (E->getOpcode() == BO_Add)
6896 Result.getLValueOffset() += AdditionalOffset;
6897 else
6898 Result.getLValueOffset() -= AdditionalOffset;
6899 return true;
6900 }
6901
6902 // Handle cases like 4 + (unsigned long)&a
6903 if (E->getOpcode() == BO_Add &&
6904 RHSVal.isLValue() && LHSVal.isInt()) {
6905 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00006906 Result.getLValueOffset() +=
6907 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006908 return true;
6909 }
6910
6911 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
6912 // Handle (intptr_t)&&A - (intptr_t)&&B.
6913 if (!LHSVal.getLValueOffset().isZero() ||
6914 !RHSVal.getLValueOffset().isZero())
6915 return false;
6916 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
6917 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
6918 if (!LHSExpr || !RHSExpr)
6919 return false;
6920 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
6921 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
6922 if (!LHSAddrExpr || !RHSAddrExpr)
6923 return false;
6924 // Make sure both labels come from the same function.
6925 if (LHSAddrExpr->getLabel()->getDeclContext() !=
6926 RHSAddrExpr->getLabel()->getDeclContext())
6927 return false;
6928 Result = APValue(LHSAddrExpr, RHSAddrExpr);
6929 return true;
6930 }
Richard Smith43e77732013-05-07 04:50:00 +00006931
6932 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006933 if (!LHSVal.isInt() || !RHSVal.isInt())
6934 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00006935
6936 // Set up the width and signedness manually, in case it can't be deduced
6937 // from the operation we're performing.
6938 // FIXME: Don't do this in the cases where we can deduce it.
6939 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
6940 E->getType()->isUnsignedIntegerOrEnumerationType());
6941 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
6942 RHSVal.getInt(), Value))
6943 return false;
6944 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006945}
6946
Richard Trieuba4d0872012-03-21 23:30:30 +00006947void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006948 Job &job = Queue.back();
6949
6950 switch (job.Kind) {
6951 case Job::AnyExprKind: {
6952 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
6953 if (shouldEnqueue(Bop)) {
6954 job.Kind = Job::BinOpKind;
6955 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006956 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006957 }
6958 }
6959
6960 EvaluateExpr(job.E, Result);
6961 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006962 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006963 }
6964
6965 case Job::BinOpKind: {
6966 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006967 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006968 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006969 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006970 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006971 }
6972 if (SuppressRHSDiags)
6973 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00006974 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006975 job.Kind = Job::BinOpVisitedLHSKind;
6976 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00006977 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006978 }
6979
6980 case Job::BinOpVisitedLHSKind: {
6981 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
6982 EvalResult RHS;
6983 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00006984 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006985 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00006986 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006987 }
6988 }
6989
6990 llvm_unreachable("Invalid Job::Kind!");
6991}
6992
6993bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Josh Magee4d1a79b2015-02-04 21:50:20 +00006994 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006995 return Error(E);
6996
6997 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
6998 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00006999
Anders Carlssonacc79812008-11-16 07:17:21 +00007000 QualType LHSTy = E->getLHS()->getType();
7001 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007002
Chandler Carruthb29a7432014-10-11 11:03:30 +00007003 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007004 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007005 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007006 if (E->isAssignmentOp()) {
7007 LValue LV;
7008 EvaluateLValue(E->getLHS(), LV, Info);
7009 LHSOK = false;
7010 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007011 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7012 if (LHSOK) {
7013 LHS.makeComplexFloat();
7014 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7015 }
7016 } else {
7017 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7018 }
Richard Smith253c2a32012-01-27 01:14:48 +00007019 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007020 return false;
7021
Chandler Carruthb29a7432014-10-11 11:03:30 +00007022 if (E->getRHS()->getType()->isRealFloatingType()) {
7023 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7024 return false;
7025 RHS.makeComplexFloat();
7026 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7027 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007028 return false;
7029
7030 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007031 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007032 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007033 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007034 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7035
John McCalle3027922010-08-25 11:45:40 +00007036 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007037 return Success((CR_r == APFloat::cmpEqual &&
7038 CR_i == APFloat::cmpEqual), E);
7039 else {
John McCalle3027922010-08-25 11:45:40 +00007040 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007041 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007042 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007043 CR_r == APFloat::cmpLessThan ||
7044 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007045 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007046 CR_i == APFloat::cmpLessThan ||
7047 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007048 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007049 } else {
John McCalle3027922010-08-25 11:45:40 +00007050 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007051 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7052 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7053 else {
John McCalle3027922010-08-25 11:45:40 +00007054 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007055 "Invalid compex comparison.");
7056 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7057 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7058 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007059 }
7060 }
Mike Stump11289f42009-09-09 15:08:12 +00007061
Anders Carlssonacc79812008-11-16 07:17:21 +00007062 if (LHSTy->isRealFloatingType() &&
7063 RHSTy->isRealFloatingType()) {
7064 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007065
Richard Smith253c2a32012-01-27 01:14:48 +00007066 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
7067 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007068 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007069
Richard Smith253c2a32012-01-27 01:14:48 +00007070 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007071 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007072
Anders Carlssonacc79812008-11-16 07:17:21 +00007073 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007074
Anders Carlssonacc79812008-11-16 07:17:21 +00007075 switch (E->getOpcode()) {
7076 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007077 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007078 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007079 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007080 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007081 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007082 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007083 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007084 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007085 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007086 E);
John McCalle3027922010-08-25 11:45:40 +00007087 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007088 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007089 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007090 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007091 || CR == APFloat::cmpLessThan
7092 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007093 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007094 }
Mike Stump11289f42009-09-09 15:08:12 +00007095
Eli Friedmana38da572009-04-28 19:17:36 +00007096 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007097 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007098 LValue LHSValue, RHSValue;
7099
7100 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
7101 if (!LHSOK && Info.keepEvaluatingAfterFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007102 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007103
Richard Smith253c2a32012-01-27 01:14:48 +00007104 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007105 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007106
Richard Smith8b3497e2011-10-31 01:37:14 +00007107 // Reject differing bases from the normal codepath; we special-case
7108 // comparisons to null.
7109 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007110 if (E->getOpcode() == BO_Sub) {
7111 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007112 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
7113 return false;
7114 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007115 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007116 if (!LHSExpr || !RHSExpr)
7117 return false;
7118 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7119 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7120 if (!LHSAddrExpr || !RHSAddrExpr)
7121 return false;
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007122 // Make sure both labels come from the same function.
7123 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7124 RHSAddrExpr->getLabel()->getDeclContext())
7125 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00007126 Result = APValue(LHSAddrExpr, RHSAddrExpr);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007127 return true;
7128 }
Richard Smith83c68212011-10-31 05:11:32 +00007129 // Inequalities and subtractions between unrelated pointers have
7130 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007131 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007132 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007133 // A constant address may compare equal to the address of a symbol.
7134 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007135 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007136 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7137 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007138 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007139 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007140 // distinct addresses. In clang, the result of such a comparison is
7141 // unspecified, so it is not a constant expression. However, we do know
7142 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007143 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7144 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007145 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007146 // We can't tell whether weak symbols will end up pointing to the same
7147 // object.
7148 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007149 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007150 // We can't compare the address of the start of one object with the
7151 // past-the-end address of another object, per C++ DR1652.
7152 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7153 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7154 (RHSValue.Base && RHSValue.Offset.isZero() &&
7155 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7156 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007157 // We can't tell whether an object is at the same address as another
7158 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007159 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7160 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007161 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007162 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007163 // (Note that clang defaults to -fmerge-all-constants, which can
7164 // lead to inconsistent results for comparisons involving the address
7165 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007166 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007167 }
Eli Friedman64004332009-03-23 04:38:34 +00007168
Richard Smith1b470412012-02-01 08:10:20 +00007169 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7170 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7171
Richard Smith84f6dcf2012-02-02 01:16:57 +00007172 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7173 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7174
John McCalle3027922010-08-25 11:45:40 +00007175 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007176 // C++11 [expr.add]p6:
7177 // Unless both pointers point to elements of the same array object, or
7178 // one past the last element of the array object, the behavior is
7179 // undefined.
7180 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7181 !AreElementsOfSameArray(getType(LHSValue.Base),
7182 LHSDesignator, RHSDesignator))
7183 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7184
Chris Lattner882bdf22010-04-20 17:13:14 +00007185 QualType Type = E->getLHS()->getType();
7186 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007187
Richard Smithd62306a2011-11-10 06:34:14 +00007188 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007189 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007190 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007191
Richard Smith84c6b3d2013-09-10 21:34:14 +00007192 // As an extension, a type may have zero size (empty struct or union in
7193 // C, array of zero length). Pointer subtraction in such cases has
7194 // undefined behavior, so is not constant.
7195 if (ElementSize.isZero()) {
7196 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7197 << ElementType;
7198 return false;
7199 }
7200
Richard Smith1b470412012-02-01 08:10:20 +00007201 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7202 // and produce incorrect results when it overflows. Such behavior
7203 // appears to be non-conforming, but is common, so perhaps we should
7204 // assume the standard intended for such cases to be undefined behavior
7205 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007206
Richard Smith1b470412012-02-01 08:10:20 +00007207 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7208 // overflow in the final conversion to ptrdiff_t.
7209 APSInt LHS(
7210 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7211 APSInt RHS(
7212 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7213 APSInt ElemSize(
7214 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7215 APSInt TrueResult = (LHS - RHS) / ElemSize;
7216 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7217
7218 if (Result.extend(65) != TrueResult)
7219 HandleOverflow(Info, E, TrueResult, E->getType());
7220 return Success(Result, E);
7221 }
Richard Smithde21b242012-01-31 06:41:30 +00007222
7223 // C++11 [expr.rel]p3:
7224 // Pointers to void (after pointer conversions) can be compared, with a
7225 // result defined as follows: If both pointers represent the same
7226 // address or are both the null pointer value, the result is true if the
7227 // operator is <= or >= and false otherwise; otherwise the result is
7228 // unspecified.
7229 // We interpret this as applying to pointers to *cv* void.
7230 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007231 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007232 CCEDiag(E, diag::note_constexpr_void_comparison);
7233
Richard Smith84f6dcf2012-02-02 01:16:57 +00007234 // C++11 [expr.rel]p2:
7235 // - If two pointers point to non-static data members of the same object,
7236 // or to subobjects or array elements fo such members, recursively, the
7237 // pointer to the later declared member compares greater provided the
7238 // two members have the same access control and provided their class is
7239 // not a union.
7240 // [...]
7241 // - Otherwise pointer comparisons are unspecified.
7242 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7243 E->isRelationalOp()) {
7244 bool WasArrayIndex;
7245 unsigned Mismatch =
7246 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7247 RHSDesignator, WasArrayIndex);
7248 // At the point where the designators diverge, the comparison has a
7249 // specified value if:
7250 // - we are comparing array indices
7251 // - we are comparing fields of a union, or fields with the same access
7252 // Otherwise, the result is unspecified and thus the comparison is not a
7253 // constant expression.
7254 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7255 Mismatch < RHSDesignator.Entries.size()) {
7256 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7257 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7258 if (!LF && !RF)
7259 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7260 else if (!LF)
7261 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7262 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7263 << RF->getParent() << RF;
7264 else if (!RF)
7265 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7266 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7267 << LF->getParent() << LF;
7268 else if (!LF->getParent()->isUnion() &&
7269 LF->getAccess() != RF->getAccess())
7270 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7271 << LF << LF->getAccess() << RF << RF->getAccess()
7272 << LF->getParent();
7273 }
7274 }
7275
Eli Friedman6c31cb42012-04-16 04:30:08 +00007276 // The comparison here must be unsigned, and performed with the same
7277 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007278 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7279 uint64_t CompareLHS = LHSOffset.getQuantity();
7280 uint64_t CompareRHS = RHSOffset.getQuantity();
7281 assert(PtrSize <= 64 && "Unexpected pointer width");
7282 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7283 CompareLHS &= Mask;
7284 CompareRHS &= Mask;
7285
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007286 // If there is a base and this is a relational operator, we can only
7287 // compare pointers within the object in question; otherwise, the result
7288 // depends on where the object is located in memory.
7289 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7290 QualType BaseTy = getType(LHSValue.Base);
7291 if (BaseTy->isIncompleteType())
7292 return Error(E);
7293 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7294 uint64_t OffsetLimit = Size.getQuantity();
7295 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7296 return Error(E);
7297 }
7298
Richard Smith8b3497e2011-10-31 01:37:14 +00007299 switch (E->getOpcode()) {
7300 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007301 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7302 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7303 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7304 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7305 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7306 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00007307 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007308 }
7309 }
Richard Smith7bb00672012-02-01 01:42:44 +00007310
7311 if (LHSTy->isMemberPointerType()) {
7312 assert(E->isEqualityOp() && "unexpected member pointer operation");
7313 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7314
7315 MemberPtr LHSValue, RHSValue;
7316
7317 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
7318 if (!LHSOK && Info.keepEvaluatingAfterFailure())
7319 return false;
7320
7321 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7322 return false;
7323
7324 // C++11 [expr.eq]p2:
7325 // If both operands are null, they compare equal. Otherwise if only one is
7326 // null, they compare unequal.
7327 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7328 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7329 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7330 }
7331
7332 // Otherwise if either is a pointer to a virtual member function, the
7333 // result is unspecified.
7334 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7335 if (MD->isVirtual())
7336 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7337 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7338 if (MD->isVirtual())
7339 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7340
7341 // Otherwise they compare equal if and only if they would refer to the
7342 // same member of the same most derived object or the same subobject if
7343 // they were dereferenced with a hypothetical object of the associated
7344 // class type.
7345 bool Equal = LHSValue == RHSValue;
7346 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7347 }
7348
Richard Smithab44d9b2012-02-14 22:35:28 +00007349 if (LHSTy->isNullPtrType()) {
7350 assert(E->isComparisonOp() && "unexpected nullptr operation");
7351 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7352 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7353 // are compared, the result is true of the operator is <=, >= or ==, and
7354 // false otherwise.
7355 BinaryOperator::Opcode Opcode = E->getOpcode();
7356 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7357 }
7358
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007359 assert((!LHSTy->isIntegralOrEnumerationType() ||
7360 !RHSTy->isIntegralOrEnumerationType()) &&
7361 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7362 // We can't continue from here for non-integral types.
7363 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00007364}
7365
Peter Collingbournee190dee2011-03-11 19:24:49 +00007366/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7367/// a result as the expression's type.
7368bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7369 const UnaryExprOrTypeTraitExpr *E) {
7370 switch(E->getKind()) {
7371 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00007372 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00007373 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007374 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00007375 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007376 }
Eli Friedman64004332009-03-23 04:38:34 +00007377
Peter Collingbournee190dee2011-03-11 19:24:49 +00007378 case UETT_VecStep: {
7379 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00007380
Peter Collingbournee190dee2011-03-11 19:24:49 +00007381 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00007382 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00007383
Peter Collingbournee190dee2011-03-11 19:24:49 +00007384 // The vec_step built-in functions that take a 3-component
7385 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7386 if (n == 3)
7387 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00007388
Peter Collingbournee190dee2011-03-11 19:24:49 +00007389 return Success(n, E);
7390 } else
7391 return Success(1, E);
7392 }
7393
7394 case UETT_SizeOf: {
7395 QualType SrcTy = E->getTypeOfArgument();
7396 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7397 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007398 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7399 SrcTy = Ref->getPointeeType();
7400
Richard Smithd62306a2011-11-10 06:34:14 +00007401 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007402 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007403 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007404 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007405 }
Alexey Bataev00396512015-07-02 03:40:19 +00007406 case UETT_OpenMPRequiredSimdAlign:
7407 assert(E->isArgumentType());
7408 return Success(
7409 Info.Ctx.toCharUnitsFromBits(
7410 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7411 .getQuantity(),
7412 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007413 }
7414
7415 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007416}
7417
Peter Collingbournee9200682011-05-13 03:29:01 +00007418bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007419 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007420 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007421 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007422 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007423 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007424 for (unsigned i = 0; i != n; ++i) {
7425 OffsetOfExpr::OffsetOfNode ON = OOE->getComponent(i);
7426 switch (ON.getKind()) {
7427 case OffsetOfExpr::OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007428 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007429 APSInt IdxResult;
7430 if (!EvaluateInteger(Idx, IdxResult, Info))
7431 return false;
7432 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7433 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007434 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007435 CurrentType = AT->getElementType();
7436 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7437 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007438 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007439 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007440
Douglas Gregor882211c2010-04-28 22:16:22 +00007441 case OffsetOfExpr::OffsetOfNode::Field: {
7442 FieldDecl *MemberDecl = ON.getField();
7443 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007444 if (!RT)
7445 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007446 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007447 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007448 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007449 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007450 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007451 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007452 CurrentType = MemberDecl->getType().getNonReferenceType();
7453 break;
7454 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007455
Douglas Gregor882211c2010-04-28 22:16:22 +00007456 case OffsetOfExpr::OffsetOfNode::Identifier:
7457 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007458
Douglas Gregord1702062010-04-29 00:18:15 +00007459 case OffsetOfExpr::OffsetOfNode::Base: {
7460 CXXBaseSpecifier *BaseSpec = ON.getBase();
7461 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007462 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007463
7464 // Find the layout of the class whose base we are looking into.
7465 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007466 if (!RT)
7467 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007468 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007469 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007470 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7471
7472 // Find the base class itself.
7473 CurrentType = BaseSpec->getType();
7474 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7475 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007476 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007477
7478 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007479 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007480 break;
7481 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007482 }
7483 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007484 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007485}
7486
Chris Lattnere13042c2008-07-11 19:10:17 +00007487bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007488 switch (E->getOpcode()) {
7489 default:
7490 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7491 // See C99 6.6p3.
7492 return Error(E);
7493 case UO_Extension:
7494 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7495 // If so, we could clear the diagnostic ID.
7496 return Visit(E->getSubExpr());
7497 case UO_Plus:
7498 // The result is just the value.
7499 return Visit(E->getSubExpr());
7500 case UO_Minus: {
7501 if (!Visit(E->getSubExpr()))
7502 return false;
7503 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007504 const APSInt &Value = Result.getInt();
7505 if (Value.isSigned() && Value.isMinSignedValue())
7506 HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7507 E->getType());
7508 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007509 }
7510 case UO_Not: {
7511 if (!Visit(E->getSubExpr()))
7512 return false;
7513 if (!Result.isInt()) return Error(E);
7514 return Success(~Result.getInt(), E);
7515 }
7516 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007517 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007518 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007519 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007520 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007521 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007522 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007523}
Mike Stump11289f42009-09-09 15:08:12 +00007524
Chris Lattner477c4be2008-07-12 01:15:53 +00007525/// HandleCast - This is used to evaluate implicit or explicit casts where the
7526/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007527bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
7528 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007529 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00007530 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00007531
Eli Friedmanc757de22011-03-25 00:43:55 +00007532 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00007533 case CK_BaseToDerived:
7534 case CK_DerivedToBase:
7535 case CK_UncheckedDerivedToBase:
7536 case CK_Dynamic:
7537 case CK_ToUnion:
7538 case CK_ArrayToPointerDecay:
7539 case CK_FunctionToPointerDecay:
7540 case CK_NullToPointer:
7541 case CK_NullToMemberPointer:
7542 case CK_BaseToDerivedMemberPointer:
7543 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00007544 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00007545 case CK_ConstructorConversion:
7546 case CK_IntegralToPointer:
7547 case CK_ToVoid:
7548 case CK_VectorSplat:
7549 case CK_IntegralToFloating:
7550 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00007551 case CK_CPointerToObjCPointerCast:
7552 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007553 case CK_AnyPointerToBlockPointerCast:
7554 case CK_ObjCObjectLValueCast:
7555 case CK_FloatingRealToComplex:
7556 case CK_FloatingComplexToReal:
7557 case CK_FloatingComplexCast:
7558 case CK_FloatingComplexToIntegralComplex:
7559 case CK_IntegralRealToComplex:
7560 case CK_IntegralComplexCast:
7561 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00007562 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00007563 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00007564 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00007565 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007566 llvm_unreachable("invalid cast kind for integral value");
7567
Eli Friedman9faf2f92011-03-25 19:07:11 +00007568 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00007569 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00007570 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00007571 case CK_ARCProduceObject:
7572 case CK_ARCConsumeObject:
7573 case CK_ARCReclaimReturnedObject:
7574 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00007575 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007576 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007577
Richard Smith4ef685b2012-01-17 21:17:26 +00007578 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00007579 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00007580 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00007581 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00007582 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007583
7584 case CK_MemberPointerToBoolean:
7585 case CK_PointerToBoolean:
7586 case CK_IntegralToBoolean:
7587 case CK_FloatingToBoolean:
7588 case CK_FloatingComplexToBoolean:
7589 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007590 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00007591 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00007592 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007593 return Success(BoolResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007594 }
7595
Eli Friedmanc757de22011-03-25 00:43:55 +00007596 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00007597 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00007598 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00007599
Eli Friedman742421e2009-02-20 01:15:07 +00007600 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007601 // Allow casts of address-of-label differences if they are no-ops
7602 // or narrowing. (The narrowing case isn't actually guaranteed to
7603 // be constant-evaluatable except in some narrow cases which are hard
7604 // to detect here. We let it through on the assumption the user knows
7605 // what they are doing.)
7606 if (Result.isAddrLabelDiff())
7607 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00007608 // Only allow casts of lvalues if they are lossless.
7609 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
7610 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007611
Richard Smith911e1422012-01-30 22:27:01 +00007612 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
7613 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00007614 }
Mike Stump11289f42009-09-09 15:08:12 +00007615
Eli Friedmanc757de22011-03-25 00:43:55 +00007616 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00007617 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
7618
John McCall45d55e42010-05-07 21:00:08 +00007619 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00007620 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00007621 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00007622
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007623 if (LV.getLValueBase()) {
7624 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00007625 // FIXME: Allow a larger integer size than the pointer size, and allow
7626 // narrowing back down to pointer width in subsequent integral casts.
7627 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007628 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007629 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00007630
Richard Smithcf74da72011-11-16 07:18:12 +00007631 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00007632 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00007633 return true;
7634 }
7635
Ken Dyck02990832010-01-15 12:37:54 +00007636 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
7637 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00007638 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007639 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007640
Eli Friedmanc757de22011-03-25 00:43:55 +00007641 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00007642 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007643 if (!EvaluateComplex(SubExpr, C, Info))
7644 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00007645 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00007646 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00007647
Eli Friedmanc757de22011-03-25 00:43:55 +00007648 case CK_FloatingToIntegral: {
7649 APFloat F(0.0);
7650 if (!EvaluateFloat(SubExpr, F, Info))
7651 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00007652
Richard Smith357362d2011-12-13 06:39:58 +00007653 APSInt Value;
7654 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
7655 return false;
7656 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00007657 }
7658 }
Mike Stump11289f42009-09-09 15:08:12 +00007659
Eli Friedmanc757de22011-03-25 00:43:55 +00007660 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00007661}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00007662
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007663bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
7664 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007665 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007666 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7667 return false;
7668 if (!LV.isComplexInt())
7669 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007670 return Success(LV.getComplexIntReal(), E);
7671 }
7672
7673 return Visit(E->getSubExpr());
7674}
7675
Eli Friedman4e7a2412009-02-27 04:45:43 +00007676bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007677 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007678 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007679 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
7680 return false;
7681 if (!LV.isComplexInt())
7682 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007683 return Success(LV.getComplexIntImag(), E);
7684 }
7685
Richard Smith4a678122011-10-24 18:44:57 +00007686 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00007687 return Success(0, E);
7688}
7689
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007690bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
7691 return Success(E->getPackLength(), E);
7692}
7693
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007694bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
7695 return Success(E->getValue(), E);
7696}
7697
Chris Lattner05706e882008-07-11 18:11:29 +00007698//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00007699// Float Evaluation
7700//===----------------------------------------------------------------------===//
7701
7702namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007703class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007704 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00007705 APFloat &Result;
7706public:
7707 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007708 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00007709
Richard Smith2e312c82012-03-03 22:46:17 +00007710 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007711 Result = V.getFloat();
7712 return true;
7713 }
Eli Friedman24c01542008-08-22 00:06:13 +00007714
Richard Smithfddd3842011-12-30 21:15:51 +00007715 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00007716 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
7717 return true;
7718 }
7719
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007720 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007721
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007722 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00007723 bool VisitBinaryOperator(const BinaryOperator *E);
7724 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007725 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00007726
John McCallb1fb0d32010-05-07 22:08:54 +00007727 bool VisitUnaryReal(const UnaryOperator *E);
7728 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00007729
Richard Smithfddd3842011-12-30 21:15:51 +00007730 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00007731};
7732} // end anonymous namespace
7733
7734static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007735 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007736 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00007737}
7738
Jay Foad39c79802011-01-12 09:06:06 +00007739static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00007740 QualType ResultTy,
7741 const Expr *Arg,
7742 bool SNaN,
7743 llvm::APFloat &Result) {
7744 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
7745 if (!S) return false;
7746
7747 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
7748
7749 llvm::APInt fill;
7750
7751 // Treat empty strings as if they were zero.
7752 if (S->getString().empty())
7753 fill = llvm::APInt(32, 0);
7754 else if (S->getString().getAsInteger(0, fill))
7755 return false;
7756
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00007757 if (Context.getTargetInfo().isNan2008()) {
7758 if (SNaN)
7759 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7760 else
7761 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7762 } else {
7763 // Prior to IEEE 754-2008, architectures were allowed to choose whether
7764 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
7765 // a different encoding to what became a standard in 2008, and for pre-
7766 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
7767 // sNaN. This is now known as "legacy NaN" encoding.
7768 if (SNaN)
7769 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
7770 else
7771 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
7772 }
7773
John McCall16291492010-02-28 13:00:19 +00007774 return true;
7775}
7776
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007777bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00007778 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007779 default:
7780 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7781
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007782 case Builtin::BI__builtin_huge_val:
7783 case Builtin::BI__builtin_huge_valf:
7784 case Builtin::BI__builtin_huge_vall:
7785 case Builtin::BI__builtin_inf:
7786 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007787 case Builtin::BI__builtin_infl: {
7788 const llvm::fltSemantics &Sem =
7789 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00007790 Result = llvm::APFloat::getInf(Sem);
7791 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00007792 }
Mike Stump11289f42009-09-09 15:08:12 +00007793
John McCall16291492010-02-28 13:00:19 +00007794 case Builtin::BI__builtin_nans:
7795 case Builtin::BI__builtin_nansf:
7796 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00007797 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7798 true, Result))
7799 return Error(E);
7800 return true;
John McCall16291492010-02-28 13:00:19 +00007801
Chris Lattner0b7282e2008-10-06 06:31:58 +00007802 case Builtin::BI__builtin_nan:
7803 case Builtin::BI__builtin_nanf:
7804 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00007805 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00007806 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00007807 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
7808 false, Result))
7809 return Error(E);
7810 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007811
7812 case Builtin::BI__builtin_fabs:
7813 case Builtin::BI__builtin_fabsf:
7814 case Builtin::BI__builtin_fabsl:
7815 if (!EvaluateFloat(E->getArg(0), Result, Info))
7816 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007817
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007818 if (Result.isNegative())
7819 Result.changeSign();
7820 return true;
7821
Richard Smith8889a3d2013-06-13 06:26:32 +00007822 // FIXME: Builtin::BI__builtin_powi
7823 // FIXME: Builtin::BI__builtin_powif
7824 // FIXME: Builtin::BI__builtin_powil
7825
Mike Stump11289f42009-09-09 15:08:12 +00007826 case Builtin::BI__builtin_copysign:
7827 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007828 case Builtin::BI__builtin_copysignl: {
7829 APFloat RHS(0.);
7830 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
7831 !EvaluateFloat(E->getArg(1), RHS, Info))
7832 return false;
7833 Result.copySign(RHS);
7834 return true;
7835 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007836 }
7837}
7838
John McCallb1fb0d32010-05-07 22:08:54 +00007839bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007840 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7841 ComplexValue CV;
7842 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7843 return false;
7844 Result = CV.FloatReal;
7845 return true;
7846 }
7847
7848 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00007849}
7850
7851bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00007852 if (E->getSubExpr()->getType()->isAnyComplexType()) {
7853 ComplexValue CV;
7854 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
7855 return false;
7856 Result = CV.FloatImag;
7857 return true;
7858 }
7859
Richard Smith4a678122011-10-24 18:44:57 +00007860 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00007861 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
7862 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00007863 return true;
7864}
7865
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007866bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007867 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007868 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00007869 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00007870 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00007871 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00007872 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
7873 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007874 Result.changeSign();
7875 return true;
7876 }
7877}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007878
Eli Friedman24c01542008-08-22 00:06:13 +00007879bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00007880 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
7881 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00007882
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00007883 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00007884 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
7885 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00007886 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00007887 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
7888 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00007889}
7890
7891bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
7892 Result = E->getValue();
7893 return true;
7894}
7895
Peter Collingbournee9200682011-05-13 03:29:01 +00007896bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
7897 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00007898
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007899 switch (E->getCastKind()) {
7900 default:
Richard Smith11562c52011-10-28 17:51:58 +00007901 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007902
7903 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007904 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00007905 return EvaluateInteger(SubExpr, IntResult, Info) &&
7906 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
7907 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007908 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007909
7910 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00007911 if (!Visit(SubExpr))
7912 return false;
Richard Smith357362d2011-12-13 06:39:58 +00007913 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
7914 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00007915 }
John McCalld7646252010-11-14 08:17:51 +00007916
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007917 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00007918 ComplexValue V;
7919 if (!EvaluateComplex(SubExpr, V, Info))
7920 return false;
7921 Result = V.getComplexFloatReal();
7922 return true;
7923 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00007924 }
Eli Friedman9a156e52008-11-12 09:44:48 +00007925}
7926
Eli Friedman24c01542008-08-22 00:06:13 +00007927//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00007928// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00007929//===----------------------------------------------------------------------===//
7930
7931namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00007932class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00007933 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00007934 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00007935
Anders Carlsson537969c2008-11-16 20:27:53 +00007936public:
John McCall93d91dc2010-05-07 17:22:02 +00007937 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00007938 : ExprEvaluatorBaseTy(info), Result(Result) {}
7939
Richard Smith2e312c82012-03-03 22:46:17 +00007940 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007941 Result.setFrom(V);
7942 return true;
7943 }
Mike Stump11289f42009-09-09 15:08:12 +00007944
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007945 bool ZeroInitialization(const Expr *E);
7946
Anders Carlsson537969c2008-11-16 20:27:53 +00007947 //===--------------------------------------------------------------------===//
7948 // Visitor Methods
7949 //===--------------------------------------------------------------------===//
7950
Peter Collingbournee9200682011-05-13 03:29:01 +00007951 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00007952 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00007953 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00007954 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007955 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007956};
7957} // end anonymous namespace
7958
John McCall93d91dc2010-05-07 17:22:02 +00007959static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
7960 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007961 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007962 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00007963}
7964
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007965bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00007966 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00007967 if (ElemTy->isRealFloatingType()) {
7968 Result.makeComplexFloat();
7969 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
7970 Result.FloatReal = Zero;
7971 Result.FloatImag = Zero;
7972 } else {
7973 Result.makeComplexInt();
7974 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
7975 Result.IntReal = Zero;
7976 Result.IntImag = Zero;
7977 }
7978 return true;
7979}
7980
Peter Collingbournee9200682011-05-13 03:29:01 +00007981bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
7982 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00007983
7984 if (SubExpr->getType()->isRealFloatingType()) {
7985 Result.makeComplexFloat();
7986 APFloat &Imag = Result.FloatImag;
7987 if (!EvaluateFloat(SubExpr, Imag, Info))
7988 return false;
7989
7990 Result.FloatReal = APFloat(Imag.getSemantics());
7991 return true;
7992 } else {
7993 assert(SubExpr->getType()->isIntegerType() &&
7994 "Unexpected imaginary literal.");
7995
7996 Result.makeComplexInt();
7997 APSInt &Imag = Result.IntImag;
7998 if (!EvaluateInteger(SubExpr, Imag, Info))
7999 return false;
8000
8001 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8002 return true;
8003 }
8004}
8005
Peter Collingbournee9200682011-05-13 03:29:01 +00008006bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008007
John McCallfcef3cf2010-12-14 17:51:41 +00008008 switch (E->getCastKind()) {
8009 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008010 case CK_BaseToDerived:
8011 case CK_DerivedToBase:
8012 case CK_UncheckedDerivedToBase:
8013 case CK_Dynamic:
8014 case CK_ToUnion:
8015 case CK_ArrayToPointerDecay:
8016 case CK_FunctionToPointerDecay:
8017 case CK_NullToPointer:
8018 case CK_NullToMemberPointer:
8019 case CK_BaseToDerivedMemberPointer:
8020 case CK_DerivedToBaseMemberPointer:
8021 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008022 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008023 case CK_ConstructorConversion:
8024 case CK_IntegralToPointer:
8025 case CK_PointerToIntegral:
8026 case CK_PointerToBoolean:
8027 case CK_ToVoid:
8028 case CK_VectorSplat:
8029 case CK_IntegralCast:
8030 case CK_IntegralToBoolean:
8031 case CK_IntegralToFloating:
8032 case CK_FloatingToIntegral:
8033 case CK_FloatingToBoolean:
8034 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008035 case CK_CPointerToObjCPointerCast:
8036 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008037 case CK_AnyPointerToBlockPointerCast:
8038 case CK_ObjCObjectLValueCast:
8039 case CK_FloatingComplexToReal:
8040 case CK_FloatingComplexToBoolean:
8041 case CK_IntegralComplexToReal:
8042 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008043 case CK_ARCProduceObject:
8044 case CK_ARCConsumeObject:
8045 case CK_ARCReclaimReturnedObject:
8046 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008047 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008048 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008049 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008050 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008051 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00008052 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008053
John McCallfcef3cf2010-12-14 17:51:41 +00008054 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008055 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008056 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008057 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008058
8059 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008060 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008061 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008062 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008063
8064 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008065 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008066 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008067 return false;
8068
John McCallfcef3cf2010-12-14 17:51:41 +00008069 Result.makeComplexFloat();
8070 Result.FloatImag = APFloat(Real.getSemantics());
8071 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008072 }
8073
John McCallfcef3cf2010-12-14 17:51:41 +00008074 case CK_FloatingComplexCast: {
8075 if (!Visit(E->getSubExpr()))
8076 return false;
8077
8078 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8079 QualType From
8080 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8081
Richard Smith357362d2011-12-13 06:39:58 +00008082 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8083 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008084 }
8085
8086 case CK_FloatingComplexToIntegralComplex: {
8087 if (!Visit(E->getSubExpr()))
8088 return false;
8089
8090 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8091 QualType From
8092 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8093 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008094 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8095 To, Result.IntReal) &&
8096 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8097 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008098 }
8099
8100 case CK_IntegralRealToComplex: {
8101 APSInt &Real = Result.IntReal;
8102 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8103 return false;
8104
8105 Result.makeComplexInt();
8106 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8107 return true;
8108 }
8109
8110 case CK_IntegralComplexCast: {
8111 if (!Visit(E->getSubExpr()))
8112 return false;
8113
8114 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8115 QualType From
8116 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8117
Richard Smith911e1422012-01-30 22:27:01 +00008118 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8119 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008120 return true;
8121 }
8122
8123 case CK_IntegralComplexToFloatingComplex: {
8124 if (!Visit(E->getSubExpr()))
8125 return false;
8126
Ted Kremenek28831752012-08-23 20:46:57 +00008127 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008128 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008129 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008130 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008131 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8132 To, Result.FloatReal) &&
8133 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8134 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008135 }
8136 }
8137
8138 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008139}
8140
John McCall93d91dc2010-05-07 17:22:02 +00008141bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008142 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008143 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8144
Chandler Carrutha216cad2014-10-11 00:57:18 +00008145 // Track whether the LHS or RHS is real at the type system level. When this is
8146 // the case we can simplify our evaluation strategy.
8147 bool LHSReal = false, RHSReal = false;
8148
8149 bool LHSOK;
8150 if (E->getLHS()->getType()->isRealFloatingType()) {
8151 LHSReal = true;
8152 APFloat &Real = Result.FloatReal;
8153 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8154 if (LHSOK) {
8155 Result.makeComplexFloat();
8156 Result.FloatImag = APFloat(Real.getSemantics());
8157 }
8158 } else {
8159 LHSOK = Visit(E->getLHS());
8160 }
Richard Smith253c2a32012-01-27 01:14:48 +00008161 if (!LHSOK && !Info.keepEvaluatingAfterFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008162 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008163
John McCall93d91dc2010-05-07 17:22:02 +00008164 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008165 if (E->getRHS()->getType()->isRealFloatingType()) {
8166 RHSReal = true;
8167 APFloat &Real = RHS.FloatReal;
8168 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8169 return false;
8170 RHS.makeComplexFloat();
8171 RHS.FloatImag = APFloat(Real.getSemantics());
8172 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008173 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008174
Chandler Carrutha216cad2014-10-11 00:57:18 +00008175 assert(!(LHSReal && RHSReal) &&
8176 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008177 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008178 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008179 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008180 if (Result.isComplexFloat()) {
8181 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8182 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008183 if (LHSReal)
8184 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8185 else if (!RHSReal)
8186 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8187 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008188 } else {
8189 Result.getComplexIntReal() += RHS.getComplexIntReal();
8190 Result.getComplexIntImag() += RHS.getComplexIntImag();
8191 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008192 break;
John McCalle3027922010-08-25 11:45:40 +00008193 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008194 if (Result.isComplexFloat()) {
8195 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8196 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008197 if (LHSReal) {
8198 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8199 Result.getComplexFloatImag().changeSign();
8200 } else if (!RHSReal) {
8201 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8202 APFloat::rmNearestTiesToEven);
8203 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008204 } else {
8205 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8206 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8207 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008208 break;
John McCalle3027922010-08-25 11:45:40 +00008209 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008210 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008211 // This is an implementation of complex multiplication according to the
8212 // constraints laid out in C11 Annex G. The implemantion uses the
8213 // following naming scheme:
8214 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008215 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008216 APFloat &A = LHS.getComplexFloatReal();
8217 APFloat &B = LHS.getComplexFloatImag();
8218 APFloat &C = RHS.getComplexFloatReal();
8219 APFloat &D = RHS.getComplexFloatImag();
8220 APFloat &ResR = Result.getComplexFloatReal();
8221 APFloat &ResI = Result.getComplexFloatImag();
8222 if (LHSReal) {
8223 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8224 ResR = A * C;
8225 ResI = A * D;
8226 } else if (RHSReal) {
8227 ResR = C * A;
8228 ResI = C * B;
8229 } else {
8230 // In the fully general case, we need to handle NaNs and infinities
8231 // robustly.
8232 APFloat AC = A * C;
8233 APFloat BD = B * D;
8234 APFloat AD = A * D;
8235 APFloat BC = B * C;
8236 ResR = AC - BD;
8237 ResI = AD + BC;
8238 if (ResR.isNaN() && ResI.isNaN()) {
8239 bool Recalc = false;
8240 if (A.isInfinity() || B.isInfinity()) {
8241 A = APFloat::copySign(
8242 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8243 B = APFloat::copySign(
8244 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8245 if (C.isNaN())
8246 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8247 if (D.isNaN())
8248 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8249 Recalc = true;
8250 }
8251 if (C.isInfinity() || D.isInfinity()) {
8252 C = APFloat::copySign(
8253 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8254 D = APFloat::copySign(
8255 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8256 if (A.isNaN())
8257 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8258 if (B.isNaN())
8259 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8260 Recalc = true;
8261 }
8262 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8263 AD.isInfinity() || BC.isInfinity())) {
8264 if (A.isNaN())
8265 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8266 if (B.isNaN())
8267 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8268 if (C.isNaN())
8269 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8270 if (D.isNaN())
8271 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8272 Recalc = true;
8273 }
8274 if (Recalc) {
8275 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8276 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8277 }
8278 }
8279 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008280 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008281 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008282 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008283 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8284 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008285 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008286 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8287 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8288 }
8289 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008290 case BO_Div:
8291 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008292 // This is an implementation of complex division according to the
8293 // constraints laid out in C11 Annex G. The implemantion uses the
8294 // following naming scheme:
8295 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008296 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008297 APFloat &A = LHS.getComplexFloatReal();
8298 APFloat &B = LHS.getComplexFloatImag();
8299 APFloat &C = RHS.getComplexFloatReal();
8300 APFloat &D = RHS.getComplexFloatImag();
8301 APFloat &ResR = Result.getComplexFloatReal();
8302 APFloat &ResI = Result.getComplexFloatImag();
8303 if (RHSReal) {
8304 ResR = A / C;
8305 ResI = B / C;
8306 } else {
8307 if (LHSReal) {
8308 // No real optimizations we can do here, stub out with zero.
8309 B = APFloat::getZero(A.getSemantics());
8310 }
8311 int DenomLogB = 0;
8312 APFloat MaxCD = maxnum(abs(C), abs(D));
8313 if (MaxCD.isFinite()) {
8314 DenomLogB = ilogb(MaxCD);
8315 C = scalbn(C, -DenomLogB);
8316 D = scalbn(D, -DenomLogB);
8317 }
8318 APFloat Denom = C * C + D * D;
8319 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB);
8320 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB);
8321 if (ResR.isNaN() && ResI.isNaN()) {
8322 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8323 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8324 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8325 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8326 D.isFinite()) {
8327 A = APFloat::copySign(
8328 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8329 B = APFloat::copySign(
8330 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8331 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8332 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8333 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8334 C = APFloat::copySign(
8335 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8336 D = APFloat::copySign(
8337 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8338 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8339 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8340 }
8341 }
8342 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008343 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008344 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8345 return Error(E, diag::note_expr_divide_by_zero);
8346
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008347 ComplexValue LHS = Result;
8348 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8349 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8350 Result.getComplexIntReal() =
8351 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8352 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8353 Result.getComplexIntImag() =
8354 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8355 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8356 }
8357 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008358 }
8359
John McCall93d91dc2010-05-07 17:22:02 +00008360 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008361}
8362
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008363bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8364 // Get the operand value into 'Result'.
8365 if (!Visit(E->getSubExpr()))
8366 return false;
8367
8368 switch (E->getOpcode()) {
8369 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008370 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008371 case UO_Extension:
8372 return true;
8373 case UO_Plus:
8374 // The result is always just the subexpr.
8375 return true;
8376 case UO_Minus:
8377 if (Result.isComplexFloat()) {
8378 Result.getComplexFloatReal().changeSign();
8379 Result.getComplexFloatImag().changeSign();
8380 }
8381 else {
8382 Result.getComplexIntReal() = -Result.getComplexIntReal();
8383 Result.getComplexIntImag() = -Result.getComplexIntImag();
8384 }
8385 return true;
8386 case UO_Not:
8387 if (Result.isComplexFloat())
8388 Result.getComplexFloatImag().changeSign();
8389 else
8390 Result.getComplexIntImag() = -Result.getComplexIntImag();
8391 return true;
8392 }
8393}
8394
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008395bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8396 if (E->getNumInits() == 2) {
8397 if (E->getType()->isComplexType()) {
8398 Result.makeComplexFloat();
8399 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8400 return false;
8401 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8402 return false;
8403 } else {
8404 Result.makeComplexInt();
8405 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8406 return false;
8407 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8408 return false;
8409 }
8410 return true;
8411 }
8412 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8413}
8414
Anders Carlsson537969c2008-11-16 20:27:53 +00008415//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00008416// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8417// implicit conversion.
8418//===----------------------------------------------------------------------===//
8419
8420namespace {
8421class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00008422 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00008423 APValue &Result;
8424public:
8425 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8426 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8427
8428 bool Success(const APValue &V, const Expr *E) {
8429 Result = V;
8430 return true;
8431 }
8432
8433 bool ZeroInitialization(const Expr *E) {
8434 ImplicitValueInitExpr VIE(
8435 E->getType()->castAs<AtomicType>()->getValueType());
8436 return Evaluate(Result, Info, &VIE);
8437 }
8438
8439 bool VisitCastExpr(const CastExpr *E) {
8440 switch (E->getCastKind()) {
8441 default:
8442 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8443 case CK_NonAtomicToAtomic:
8444 return Evaluate(Result, Info, E->getSubExpr());
8445 }
8446 }
8447};
8448} // end anonymous namespace
8449
8450static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8451 assert(E->isRValue() && E->getType()->isAtomicType());
8452 return AtomicExprEvaluator(Info, Result).Visit(E);
8453}
8454
8455//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00008456// Void expression evaluation, primarily for a cast to void on the LHS of a
8457// comma operator
8458//===----------------------------------------------------------------------===//
8459
8460namespace {
8461class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008462 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00008463public:
8464 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8465
Richard Smith2e312c82012-03-03 22:46:17 +00008466 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00008467
8468 bool VisitCastExpr(const CastExpr *E) {
8469 switch (E->getCastKind()) {
8470 default:
8471 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8472 case CK_ToVoid:
8473 VisitIgnoredValue(E->getSubExpr());
8474 return true;
8475 }
8476 }
Hal Finkela8443c32014-07-17 14:49:58 +00008477
8478 bool VisitCallExpr(const CallExpr *E) {
8479 switch (E->getBuiltinCallee()) {
8480 default:
8481 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8482 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00008483 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00008484 // The argument is not evaluated!
8485 return true;
8486 }
8487 }
Richard Smith42d3af92011-12-07 00:43:50 +00008488};
8489} // end anonymous namespace
8490
8491static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8492 assert(E->isRValue() && E->getType()->isVoidType());
8493 return VoidExprEvaluator(Info).Visit(E);
8494}
8495
8496//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00008497// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00008498//===----------------------------------------------------------------------===//
8499
Richard Smith2e312c82012-03-03 22:46:17 +00008500static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00008501 // In C, function designators are not lvalues, but we evaluate them as if they
8502 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00008503 QualType T = E->getType();
8504 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00008505 LValue LV;
8506 if (!EvaluateLValue(E, LV, Info))
8507 return false;
8508 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008509 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008510 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008511 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008512 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008513 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008514 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008515 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00008516 LValue LV;
8517 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008518 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008519 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008520 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00008521 llvm::APFloat F(0.0);
8522 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008523 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00008524 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00008525 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00008526 ComplexValue C;
8527 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008528 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008529 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008530 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00008531 MemberPtr P;
8532 if (!EvaluateMemberPointer(E, P, Info))
8533 return false;
8534 P.moveInto(Result);
8535 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00008536 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008537 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008538 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008539 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8540 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00008541 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008542 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008543 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00008544 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008545 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00008546 APValue &Value = Info.CurrentCall->createTemporary(E, false);
8547 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00008548 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00008549 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00008550 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008551 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00008552 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00008553 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00008554 if (!EvaluateVoid(E, Info))
8555 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008556 } else if (T->isAtomicType()) {
8557 if (!EvaluateAtomic(E, Result, Info))
8558 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008559 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008560 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00008561 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008562 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00008563 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00008564 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008565 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008566
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00008567 return true;
8568}
8569
Richard Smithb228a862012-02-15 02:18:13 +00008570/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
8571/// cases, the in-place evaluation is essential, since later initializers for
8572/// an object can indirectly refer to subobjects which were initialized earlier.
8573static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00008574 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00008575 assert(!E->isValueDependent());
8576
Richard Smith7525ff62013-05-09 07:14:00 +00008577 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00008578 return false;
8579
8580 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00008581 // Evaluate arrays and record types in-place, so that later initializers can
8582 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00008583 if (E->getType()->isArrayType())
8584 return EvaluateArray(E, This, Result, Info);
8585 else if (E->getType()->isRecordType())
8586 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00008587 }
8588
8589 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00008590 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00008591}
8592
Richard Smithf57d8cb2011-12-09 22:58:01 +00008593/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
8594/// lvalue-to-rvalue cast if it is an lvalue.
8595static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00008596 if (E->getType().isNull())
8597 return false;
8598
Richard Smithfddd3842011-12-30 21:15:51 +00008599 if (!CheckLiteralType(Info, E))
8600 return false;
8601
Richard Smith2e312c82012-03-03 22:46:17 +00008602 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008603 return false;
8604
8605 if (E->isGLValue()) {
8606 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00008607 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00008608 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008609 return false;
8610 }
8611
Richard Smith2e312c82012-03-03 22:46:17 +00008612 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00008613 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008614}
Richard Smith11562c52011-10-28 17:51:58 +00008615
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008616static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
8617 const ASTContext &Ctx, bool &IsConst) {
8618 // Fast-path evaluations of integer literals, since we sometimes see files
8619 // containing vast quantities of these.
8620 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
8621 Result.Val = APValue(APSInt(L->getValue(),
8622 L->getType()->isUnsignedIntegerType()));
8623 IsConst = true;
8624 return true;
8625 }
James Dennett0492ef02014-03-14 17:44:10 +00008626
8627 // This case should be rare, but we need to check it before we check on
8628 // the type below.
8629 if (Exp->getType().isNull()) {
8630 IsConst = false;
8631 return true;
8632 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008633
8634 // FIXME: Evaluating values of large array and record types can cause
8635 // performance problems. Only do so in C++11 for now.
8636 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
8637 Exp->getType()->isRecordType()) &&
8638 !Ctx.getLangOpts().CPlusPlus11) {
8639 IsConst = false;
8640 return true;
8641 }
8642 return false;
8643}
8644
8645
Richard Smith7b553f12011-10-29 00:50:52 +00008646/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00008647/// any crazy technique (that has nothing to do with language standards) that
8648/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00008649/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
8650/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00008651bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008652 bool IsConst;
8653 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
8654 return IsConst;
8655
Richard Smith6d4c6582013-11-05 22:18:15 +00008656 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008657 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00008658}
8659
Jay Foad39c79802011-01-12 09:06:06 +00008660bool Expr::EvaluateAsBooleanCondition(bool &Result,
8661 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00008662 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00008663 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00008664 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00008665}
8666
Richard Smith5fab0c92011-12-28 19:48:30 +00008667bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
8668 SideEffectsKind AllowSideEffects) const {
8669 if (!getType()->isIntegralOrEnumerationType())
8670 return false;
8671
Richard Smith11562c52011-10-28 17:51:58 +00008672 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00008673 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
8674 (!AllowSideEffects && ExprResult.HasSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00008675 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008676
Richard Smith11562c52011-10-28 17:51:58 +00008677 Result = ExprResult.Val.getInt();
8678 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00008679}
8680
Jay Foad39c79802011-01-12 09:06:06 +00008681bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00008682 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00008683
John McCall45d55e42010-05-07 21:00:08 +00008684 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00008685 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
8686 !CheckLValueConstantExpression(Info, getExprLoc(),
8687 Ctx.getLValueReferenceType(getType()), LV))
8688 return false;
8689
Richard Smith2e312c82012-03-03 22:46:17 +00008690 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00008691 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00008692}
8693
Richard Smithd0b4dd62011-12-19 06:19:21 +00008694bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
8695 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008696 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00008697 // FIXME: Evaluating initializers for large array and record types can cause
8698 // performance problems. Only do so in C++11 for now.
8699 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00008700 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00008701 return false;
8702
Richard Smithd0b4dd62011-12-19 06:19:21 +00008703 Expr::EvalStatus EStatus;
8704 EStatus.Diag = &Notes;
8705
Richard Smith6d4c6582013-11-05 22:18:15 +00008706 EvalInfo InitInfo(Ctx, EStatus, EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008707 InitInfo.setEvaluatingDecl(VD, Value);
8708
8709 LValue LVal;
8710 LVal.set(VD);
8711
Richard Smithfddd3842011-12-30 21:15:51 +00008712 // C++11 [basic.start.init]p2:
8713 // Variables with static storage duration or thread storage duration shall be
8714 // zero-initialized before any other initialization takes place.
8715 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00008716 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00008717 !VD->getType()->isReferenceType()) {
8718 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00008719 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00008720 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00008721 return false;
8722 }
8723
Richard Smith7525ff62013-05-09 07:14:00 +00008724 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
8725 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00008726 EStatus.HasSideEffects)
8727 return false;
8728
8729 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
8730 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00008731}
8732
Richard Smith7b553f12011-10-29 00:50:52 +00008733/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
8734/// constant folded, but discard the result.
Jay Foad39c79802011-01-12 09:06:06 +00008735bool Expr::isEvaluatable(const ASTContext &Ctx) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00008736 EvalResult Result;
Richard Smith7b553f12011-10-29 00:50:52 +00008737 return EvaluateAsRValue(Result, Ctx) && !Result.HasSideEffects;
Chris Lattnercb136912008-10-06 06:49:02 +00008738}
Anders Carlsson59689ed2008-11-22 21:04:56 +00008739
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008740APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00008741 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008742 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00008743 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00008744 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00008745 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00008746 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008747 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00008748
Anders Carlsson6736d1a22008-12-19 20:58:05 +00008749 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00008750}
John McCall864e3962010-05-07 05:32:02 +00008751
Richard Smithe9ff7702013-11-05 22:23:30 +00008752void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008753 bool IsConst;
8754 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008755 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00008756 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00008757 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
8758 }
8759}
8760
Richard Smithe6c01442013-06-05 00:46:14 +00008761bool Expr::EvalResult::isGlobalLValue() const {
8762 assert(Val.isLValue());
8763 return IsGlobalLValue(Val.getLValueBase());
8764}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00008765
8766
John McCall864e3962010-05-07 05:32:02 +00008767/// isIntegerConstantExpr - this recursive routine will test if an expression is
8768/// an integer constant expression.
8769
8770/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
8771/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00008772
8773// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00008774// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
8775// and a (possibly null) SourceLocation indicating the location of the problem.
8776//
John McCall864e3962010-05-07 05:32:02 +00008777// Note that to reduce code duplication, this helper does no evaluation
8778// itself; the caller checks whether the expression is evaluatable, and
8779// in the rare cases where CheckICE actually cares about the evaluated
8780// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00008781
Dan Gohman28ade552010-07-26 21:25:24 +00008782namespace {
8783
Richard Smith9e575da2012-12-28 13:25:52 +00008784enum ICEKind {
8785 /// This expression is an ICE.
8786 IK_ICE,
8787 /// This expression is not an ICE, but if it isn't evaluated, it's
8788 /// a legal subexpression for an ICE. This return value is used to handle
8789 /// the comma operator in C99 mode, and non-constant subexpressions.
8790 IK_ICEIfUnevaluated,
8791 /// This expression is not an ICE, and is not a legal subexpression for one.
8792 IK_NotICE
8793};
8794
John McCall864e3962010-05-07 05:32:02 +00008795struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00008796 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00008797 SourceLocation Loc;
8798
Richard Smith9e575da2012-12-28 13:25:52 +00008799 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00008800};
8801
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008802}
Dan Gohman28ade552010-07-26 21:25:24 +00008803
Richard Smith9e575da2012-12-28 13:25:52 +00008804static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
8805
8806static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00008807
Craig Toppera31a8822013-08-22 07:09:37 +00008808static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008809 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00008810 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00008811 !EVResult.Val.isInt())
8812 return ICEDiag(IK_NotICE, E->getLocStart());
8813
John McCall864e3962010-05-07 05:32:02 +00008814 return NoDiag();
8815}
8816
Craig Toppera31a8822013-08-22 07:09:37 +00008817static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00008818 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00008819 if (!E->getType()->isIntegralOrEnumerationType())
8820 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008821
8822 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00008823#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00008824#define STMT(Node, Base) case Expr::Node##Class:
8825#define EXPR(Node, Base)
8826#include "clang/AST/StmtNodes.inc"
8827 case Expr::PredefinedExprClass:
8828 case Expr::FloatingLiteralClass:
8829 case Expr::ImaginaryLiteralClass:
8830 case Expr::StringLiteralClass:
8831 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00008832 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00008833 case Expr::MemberExprClass:
8834 case Expr::CompoundAssignOperatorClass:
8835 case Expr::CompoundLiteralExprClass:
8836 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00008837 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00008838 case Expr::NoInitExprClass:
8839 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00008840 case Expr::ImplicitValueInitExprClass:
8841 case Expr::ParenListExprClass:
8842 case Expr::VAArgExprClass:
8843 case Expr::AddrLabelExprClass:
8844 case Expr::StmtExprClass:
8845 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00008846 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00008847 case Expr::CXXDynamicCastExprClass:
8848 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00008849 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00008850 case Expr::MSPropertyRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008851 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00008852 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008853 case Expr::CXXThisExprClass:
8854 case Expr::CXXThrowExprClass:
8855 case Expr::CXXNewExprClass:
8856 case Expr::CXXDeleteExprClass:
8857 case Expr::CXXPseudoDestructorExprClass:
8858 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00008859 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00008860 case Expr::DependentScopeDeclRefExprClass:
8861 case Expr::CXXConstructExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00008862 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00008863 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00008864 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00008865 case Expr::CXXTemporaryObjectExprClass:
8866 case Expr::CXXUnresolvedConstructExprClass:
8867 case Expr::CXXDependentScopeMemberExprClass:
8868 case Expr::UnresolvedMemberExprClass:
8869 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00008870 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008871 case Expr::ObjCArrayLiteralClass:
8872 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00008873 case Expr::ObjCEncodeExprClass:
8874 case Expr::ObjCMessageExprClass:
8875 case Expr::ObjCSelectorExprClass:
8876 case Expr::ObjCProtocolExprClass:
8877 case Expr::ObjCIvarRefExprClass:
8878 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008879 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00008880 case Expr::ObjCIsaExprClass:
8881 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00008882 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00008883 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00008884 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00008885 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00008886 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00008887 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00008888 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00008889 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00008890 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00008891 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00008892 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00008893 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00008894 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00008895 case Expr::CXXFoldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00008896 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00008897
Richard Smithf137f932014-01-25 20:50:08 +00008898 case Expr::InitListExprClass: {
8899 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
8900 // form "T x = { a };" is equivalent to "T x = a;".
8901 // Unless we're initializing a reference, T is a scalar as it is known to be
8902 // of integral or enumeration type.
8903 if (E->isRValue())
8904 if (cast<InitListExpr>(E)->getNumInits() == 1)
8905 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
8906 return ICEDiag(IK_NotICE, E->getLocStart());
8907 }
8908
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008909 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00008910 case Expr::GNUNullExprClass:
8911 // GCC considers the GNU __null value to be an integral constant expression.
8912 return NoDiag();
8913
John McCall7c454bb2011-07-15 05:09:51 +00008914 case Expr::SubstNonTypeTemplateParmExprClass:
8915 return
8916 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
8917
John McCall864e3962010-05-07 05:32:02 +00008918 case Expr::ParenExprClass:
8919 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00008920 case Expr::GenericSelectionExprClass:
8921 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008922 case Expr::IntegerLiteralClass:
8923 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00008924 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00008925 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00008926 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00008927 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00008928 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00008929 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00008930 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00008931 return NoDiag();
8932 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00008933 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00008934 // C99 6.6/3 allows function calls within unevaluated subexpressions of
8935 // constant expressions, but they can never be ICEs because an ICE cannot
8936 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00008937 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00008938 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00008939 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00008940 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00008941 }
Richard Smith6365c912012-02-24 22:12:32 +00008942 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00008943 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
8944 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00008945 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00008946 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00008947 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00008948 // Parameter variables are never constants. Without this check,
8949 // getAnyInitializer() can find a default argument, which leads
8950 // to chaos.
8951 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00008952 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008953
8954 // C++ 7.1.5.1p2
8955 // A variable of non-volatile const-qualified integral or enumeration
8956 // type initialized by an ICE can be used in ICEs.
8957 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00008958 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00008959 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00008960
Richard Smithd0b4dd62011-12-19 06:19:21 +00008961 const VarDecl *VD;
8962 // Look for a declaration of this variable that has an initializer, and
8963 // check whether it is an ICE.
8964 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
8965 return NoDiag();
8966 else
Richard Smith9e575da2012-12-28 13:25:52 +00008967 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00008968 }
8969 }
Richard Smith9e575da2012-12-28 13:25:52 +00008970 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00008971 }
John McCall864e3962010-05-07 05:32:02 +00008972 case Expr::UnaryOperatorClass: {
8973 const UnaryOperator *Exp = cast<UnaryOperator>(E);
8974 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00008975 case UO_PostInc:
8976 case UO_PostDec:
8977 case UO_PreInc:
8978 case UO_PreDec:
8979 case UO_AddrOf:
8980 case UO_Deref:
Richard Smith62f65952011-10-24 22:35:48 +00008981 // C99 6.6/3 allows increment and decrement within unevaluated
8982 // subexpressions of constant expressions, but they can never be ICEs
8983 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00008984 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00008985 case UO_Extension:
8986 case UO_LNot:
8987 case UO_Plus:
8988 case UO_Minus:
8989 case UO_Not:
8990 case UO_Real:
8991 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00008992 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00008993 }
Richard Smith9e575da2012-12-28 13:25:52 +00008994
John McCall864e3962010-05-07 05:32:02 +00008995 // OffsetOf falls through here.
8996 }
8997 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00008998 // Note that per C99, offsetof must be an ICE. And AFAIK, using
8999 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9000 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9001 // compliance: we should warn earlier for offsetof expressions with
9002 // array subscripts that aren't ICEs, and if the array subscripts
9003 // are ICEs, the value of the offsetof must be an integer constant.
9004 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009005 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009006 case Expr::UnaryExprOrTypeTraitExprClass: {
9007 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9008 if ((Exp->getKind() == UETT_SizeOf) &&
9009 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009010 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009011 return NoDiag();
9012 }
9013 case Expr::BinaryOperatorClass: {
9014 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9015 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009016 case BO_PtrMemD:
9017 case BO_PtrMemI:
9018 case BO_Assign:
9019 case BO_MulAssign:
9020 case BO_DivAssign:
9021 case BO_RemAssign:
9022 case BO_AddAssign:
9023 case BO_SubAssign:
9024 case BO_ShlAssign:
9025 case BO_ShrAssign:
9026 case BO_AndAssign:
9027 case BO_XorAssign:
9028 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009029 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9030 // constant expressions, but they can never be ICEs because an ICE cannot
9031 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009032 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009033
John McCalle3027922010-08-25 11:45:40 +00009034 case BO_Mul:
9035 case BO_Div:
9036 case BO_Rem:
9037 case BO_Add:
9038 case BO_Sub:
9039 case BO_Shl:
9040 case BO_Shr:
9041 case BO_LT:
9042 case BO_GT:
9043 case BO_LE:
9044 case BO_GE:
9045 case BO_EQ:
9046 case BO_NE:
9047 case BO_And:
9048 case BO_Xor:
9049 case BO_Or:
9050 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009051 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9052 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009053 if (Exp->getOpcode() == BO_Div ||
9054 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009055 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009056 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009057 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009058 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009059 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009060 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009061 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009062 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009063 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009064 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009065 }
9066 }
9067 }
John McCalle3027922010-08-25 11:45:40 +00009068 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009069 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009070 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9071 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009072 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9073 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009074 } else {
9075 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009076 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009077 }
9078 }
Richard Smith9e575da2012-12-28 13:25:52 +00009079 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009080 }
John McCalle3027922010-08-25 11:45:40 +00009081 case BO_LAnd:
9082 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009083 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9084 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009085 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009086 // Rare case where the RHS has a comma "side-effect"; we need
9087 // to actually check the condition to see whether the side
9088 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009089 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009090 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009091 return RHSResult;
9092 return NoDiag();
9093 }
9094
Richard Smith9e575da2012-12-28 13:25:52 +00009095 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009096 }
9097 }
9098 }
9099 case Expr::ImplicitCastExprClass:
9100 case Expr::CStyleCastExprClass:
9101 case Expr::CXXFunctionalCastExprClass:
9102 case Expr::CXXStaticCastExprClass:
9103 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009104 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009105 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009106 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009107 if (isa<ExplicitCastExpr>(E)) {
9108 if (const FloatingLiteral *FL
9109 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9110 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9111 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9112 APSInt IgnoredVal(DestWidth, !DestSigned);
9113 bool Ignored;
9114 // If the value does not fit in the destination type, the behavior is
9115 // undefined, so we are not required to treat it as a constant
9116 // expression.
9117 if (FL->getValue().convertToInteger(IgnoredVal,
9118 llvm::APFloat::rmTowardZero,
9119 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009120 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009121 return NoDiag();
9122 }
9123 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009124 switch (cast<CastExpr>(E)->getCastKind()) {
9125 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009126 case CK_AtomicToNonAtomic:
9127 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009128 case CK_NoOp:
9129 case CK_IntegralToBoolean:
9130 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009131 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009132 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009133 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009134 }
John McCall864e3962010-05-07 05:32:02 +00009135 }
John McCallc07a0c72011-02-17 10:25:35 +00009136 case Expr::BinaryConditionalOperatorClass: {
9137 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9138 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009139 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009140 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009141 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9142 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9143 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009144 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009145 return FalseResult;
9146 }
John McCall864e3962010-05-07 05:32:02 +00009147 case Expr::ConditionalOperatorClass: {
9148 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9149 // If the condition (ignoring parens) is a __builtin_constant_p call,
9150 // then only the true side is actually considered in an integer constant
9151 // expression, and it is fully evaluated. This is an important GNU
9152 // extension. See GCC PR38377 for discussion.
9153 if (const CallExpr *CallCE
9154 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009155 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009156 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009157 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009158 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009159 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009160
Richard Smithf57d8cb2011-12-09 22:58:01 +00009161 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9162 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009163
Richard Smith9e575da2012-12-28 13:25:52 +00009164 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009165 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009166 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009167 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009168 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009169 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009170 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009171 return NoDiag();
9172 // Rare case where the diagnostics depend on which side is evaluated
9173 // Note that if we get here, CondResult is 0, and at least one of
9174 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009175 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009176 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009177 return TrueResult;
9178 }
9179 case Expr::CXXDefaultArgExprClass:
9180 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009181 case Expr::CXXDefaultInitExprClass:
9182 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009183 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009184 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009185 }
9186 }
9187
David Blaikiee4d798f2012-01-20 21:50:17 +00009188 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009189}
9190
Richard Smithf57d8cb2011-12-09 22:58:01 +00009191/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009192static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009193 const Expr *E,
9194 llvm::APSInt *Value,
9195 SourceLocation *Loc) {
9196 if (!E->getType()->isIntegralOrEnumerationType()) {
9197 if (Loc) *Loc = E->getExprLoc();
9198 return false;
9199 }
9200
Richard Smith66e05fe2012-01-18 05:21:49 +00009201 APValue Result;
9202 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00009203 return false;
9204
Richard Smith98710fc2014-11-13 23:03:19 +00009205 if (!Result.isInt()) {
9206 if (Loc) *Loc = E->getExprLoc();
9207 return false;
9208 }
9209
Richard Smith66e05fe2012-01-18 05:21:49 +00009210 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00009211 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009212}
9213
Craig Toppera31a8822013-08-22 07:09:37 +00009214bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9215 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009216 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00009217 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009218
Richard Smith9e575da2012-12-28 13:25:52 +00009219 ICEDiag D = CheckICE(this, Ctx);
9220 if (D.Kind != IK_ICE) {
9221 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00009222 return false;
9223 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009224 return true;
9225}
9226
Craig Toppera31a8822013-08-22 07:09:37 +00009227bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009228 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009229 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009230 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9231
9232 if (!isIntegerConstantExpr(Ctx, Loc))
9233 return false;
9234 if (!EvaluateAsInt(Value, Ctx))
John McCall864e3962010-05-07 05:32:02 +00009235 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00009236 return true;
9237}
Richard Smith66e05fe2012-01-18 05:21:49 +00009238
Craig Toppera31a8822013-08-22 07:09:37 +00009239bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00009240 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00009241}
9242
Craig Toppera31a8822013-08-22 07:09:37 +00009243bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00009244 SourceLocation *Loc) const {
9245 // We support this checking in C++98 mode in order to diagnose compatibility
9246 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009247 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00009248
Richard Smith98a0a492012-02-14 21:38:30 +00009249 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00009250 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009251 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00009252 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00009253 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00009254
9255 APValue Scratch;
9256 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9257
9258 if (!Diags.empty()) {
9259 IsConstExpr = false;
9260 if (Loc) *Loc = Diags[0].first;
9261 } else if (!IsConstExpr) {
9262 // FIXME: This shouldn't happen.
9263 if (Loc) *Loc = getExprLoc();
9264 }
9265
9266 return IsConstExpr;
9267}
Richard Smith253c2a32012-01-27 01:14:48 +00009268
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009269bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9270 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00009271 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009272 Expr::EvalStatus Status;
9273 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9274
9275 ArgVector ArgValues(Args.size());
9276 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9277 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00009278 if ((*I)->isValueDependent() ||
9279 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009280 // If evaluation fails, throw away the argument entirely.
9281 ArgValues[I - Args.begin()] = APValue();
9282 if (Info.EvalStatus.HasSideEffects)
9283 return false;
9284 }
9285
9286 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00009287 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009288 ArgValues.data());
9289 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9290}
9291
Richard Smith253c2a32012-01-27 01:14:48 +00009292bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009293 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00009294 PartialDiagnosticAt> &Diags) {
9295 // FIXME: It would be useful to check constexpr function templates, but at the
9296 // moment the constant expression evaluator cannot cope with the non-rigorous
9297 // ASTs which we build for dependent expressions.
9298 if (FD->isDependentContext())
9299 return true;
9300
9301 Expr::EvalStatus Status;
9302 Status.Diag = &Diags;
9303
Richard Smith6d4c6582013-11-05 22:18:15 +00009304 EvalInfo Info(FD->getASTContext(), Status,
9305 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00009306
9307 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00009308 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00009309
Richard Smith7525ff62013-05-09 07:14:00 +00009310 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00009311 // is a temporary being used as the 'this' pointer.
9312 LValue This;
9313 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00009314 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00009315
Richard Smith253c2a32012-01-27 01:14:48 +00009316 ArrayRef<const Expr*> Args;
9317
9318 SourceLocation Loc = FD->getLocation();
9319
Richard Smith2e312c82012-03-03 22:46:17 +00009320 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00009321 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9322 // Evaluate the call as a constant initializer, to allow the construction
9323 // of objects of non-literal types.
9324 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith253c2a32012-01-27 01:14:48 +00009325 HandleConstructorCall(Loc, This, Args, CD, Info, Scratch);
Richard Smith7525ff62013-05-09 07:14:00 +00009326 } else
Craig Topper36250ad2014-05-12 05:36:57 +00009327 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +00009328 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith253c2a32012-01-27 01:14:48 +00009329
9330 return Diags.empty();
9331}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009332
9333bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9334 const FunctionDecl *FD,
9335 SmallVectorImpl<
9336 PartialDiagnosticAt> &Diags) {
9337 Expr::EvalStatus Status;
9338 Status.Diag = &Diags;
9339
9340 EvalInfo Info(FD->getASTContext(), Status,
9341 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9342
9343 // Fabricate a call stack frame to give the arguments a plausible cover story.
9344 ArrayRef<const Expr*> Args;
9345 ArgVector ArgValues(0);
9346 bool Success = EvaluateArgs(Args, ArgValues, Info);
9347 (void)Success;
9348 assert(Success &&
9349 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00009350 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009351
9352 APValue ResultScratch;
9353 Evaluate(ResultScratch, Info, E);
9354 return Diags.empty();
9355}