blob: e44cb1d23cf93461f560388a65e2f0997b240960 [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"
Faisal Valia734ab92016-03-26 16:11:37 +000039#include "clang/AST/ASTLambda.h"
Ken Dyck40775002010-01-11 17:06:35 +000040#include "clang/AST/CharUnits.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000041#include "clang/AST/Expr.h"
Anders Carlsson15b73de2009-07-18 19:43:29 +000042#include "clang/AST/RecordLayout.h"
Seo Sanghyeon1904f442008-07-08 07:23:12 +000043#include "clang/AST/StmtVisitor.h"
Douglas Gregor882211c2010-04-28 22:16:22 +000044#include "clang/AST/TypeLoc.h"
Chris Lattner15ba9492009-06-14 01:54:56 +000045#include "clang/Basic/Builtins.h"
Anders Carlsson374b93d2008-07-08 05:49:43 +000046#include "clang/Basic/TargetInfo.h"
Mike Stumpb807c9c2009-05-30 14:43:18 +000047#include "llvm/ADT/SmallString.h"
Benjamin Kramer444a1302012-12-01 17:12:56 +000048#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000049#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000050#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000051
Anders Carlsson7a241ba2008-07-03 04:20:39 +000052using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000053using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000054using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000055
Richard Smithb228a862012-02-15 02:18:13 +000056static bool IsGlobalLValue(APValue::LValueBase B);
57
John McCall93d91dc2010-05-07 17:22:02 +000058namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000059 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000060 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000061 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000062
Richard Smithb228a862012-02-15 02:18:13 +000063 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000064 if (!B) return QualType();
65 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
66 return D->getType();
Richard Smith84401042013-06-03 05:03:02 +000067
68 const Expr *Base = B.get<const Expr*>();
69
70 // For a materialized temporary, the type of the temporary we materialized
71 // may not be the type of the expression.
72 if (const MaterializeTemporaryExpr *MTE =
73 dyn_cast<MaterializeTemporaryExpr>(Base)) {
74 SmallVector<const Expr *, 2> CommaLHSs;
75 SmallVector<SubobjectAdjustment, 2> Adjustments;
76 const Expr *Temp = MTE->GetTemporaryExpr();
77 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
78 Adjustments);
79 // Keep any cv-qualifiers from the reference if we generated a temporary
80 // for it.
81 if (Inner != Temp)
82 return Inner->getType();
83 }
84
85 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000086 }
87
Richard Smithd62306a2011-11-10 06:34:14 +000088 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000089 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000090 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000091 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000092 APValue::BaseOrMemberType Value;
93 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000094 return Value;
95 }
96
97 /// Get an LValue path entry, which is known to not be an array index, as a
98 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +000099 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000100 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000101 }
102 /// Get an LValue path entry, which is known to not be an array index, as a
103 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000104 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000105 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000106 }
107 /// Determine whether this LValue path entry for a base class names a virtual
108 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000109 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000110 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000111 }
112
Richard Smitha8105bc2012-01-06 16:39:00 +0000113 /// Find the path length and type of the most-derived subobject in the given
114 /// path, and find the size of the containing array, if any.
115 static
116 unsigned findMostDerivedSubobject(ASTContext &Ctx, QualType Base,
117 ArrayRef<APValue::LValuePathEntry> Path,
George Burgess IVa51c4072015-10-16 01:49:01 +0000118 uint64_t &ArraySize, QualType &Type,
119 bool &IsArray) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000120 unsigned MostDerivedLength = 0;
121 Type = Base;
Richard Smith80815602011-11-07 05:07:52 +0000122 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000123 if (Type->isArrayType()) {
124 const ConstantArrayType *CAT =
125 cast<ConstantArrayType>(Ctx.getAsArrayType(Type));
126 Type = CAT->getElementType();
127 ArraySize = CAT->getSize().getZExtValue();
128 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000129 IsArray = true;
Richard Smith66c96992012-02-18 22:04:06 +0000130 } else if (Type->isAnyComplexType()) {
131 const ComplexType *CT = Type->castAs<ComplexType>();
132 Type = CT->getElementType();
133 ArraySize = 2;
134 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000135 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000136 } else if (const FieldDecl *FD = getAsField(Path[I])) {
137 Type = FD->getType();
138 ArraySize = 0;
139 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000140 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000141 } else {
Richard Smith80815602011-11-07 05:07:52 +0000142 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000143 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000144 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000145 }
Richard Smith80815602011-11-07 05:07:52 +0000146 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000147 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000148 }
149
Richard Smitha8105bc2012-01-06 16:39:00 +0000150 // The order of this enum is important for diagnostics.
151 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000152 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000153 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000154 };
155
Richard Smith96e0c102011-11-04 02:25:55 +0000156 /// A path from a glvalue to a subobject of that glvalue.
157 struct SubobjectDesignator {
158 /// True if the subobject was named in a manner not supported by C++11. Such
159 /// lvalues can still be folded, but they are not core constant expressions
160 /// and we cannot perform lvalue-to-rvalue conversions on them.
161 bool Invalid : 1;
162
Richard Smitha8105bc2012-01-06 16:39:00 +0000163 /// Is this a pointer one past the end of an object?
164 bool IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000165
George Burgess IVa51c4072015-10-16 01:49:01 +0000166 /// Indicator of whether the most-derived object is an array element.
167 bool MostDerivedIsArrayElement : 1;
168
Richard Smitha8105bc2012-01-06 16:39:00 +0000169 /// The length of the path to the most-derived object of which this is a
170 /// subobject.
George Burgess IVa51c4072015-10-16 01:49:01 +0000171 unsigned MostDerivedPathLength : 29;
Richard Smitha8105bc2012-01-06 16:39:00 +0000172
George Burgess IVa51c4072015-10-16 01:49:01 +0000173 /// The size of the array of which the most-derived object is an element.
174 /// This will always be 0 if the most-derived object is not an array
175 /// element. 0 is not an indicator of whether or not the most-derived object
176 /// is an array, however, because 0-length arrays are allowed.
Richard Smitha8105bc2012-01-06 16:39:00 +0000177 uint64_t MostDerivedArraySize;
178
179 /// The type of the most derived object referred to by this address.
180 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000181
Richard Smith80815602011-11-07 05:07:52 +0000182 typedef APValue::LValuePathEntry PathEntry;
183
Richard Smith96e0c102011-11-04 02:25:55 +0000184 /// The entries on the path from the glvalue to the designated subobject.
185 SmallVector<PathEntry, 8> Entries;
186
Richard Smitha8105bc2012-01-06 16:39:00 +0000187 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000188
Richard Smitha8105bc2012-01-06 16:39:00 +0000189 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000190 : Invalid(false), IsOnePastTheEnd(false),
191 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
192 MostDerivedArraySize(0), MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000193
194 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000195 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
196 MostDerivedIsArrayElement(false), MostDerivedPathLength(0),
197 MostDerivedArraySize(0) {
Richard Smith80815602011-11-07 05:07:52 +0000198 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000199 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000200 ArrayRef<PathEntry> VEntries = V.getLValuePath();
201 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
George Burgess IVa51c4072015-10-16 01:49:01 +0000202 if (V.getLValueBase()) {
203 bool IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000204 MostDerivedPathLength =
205 findMostDerivedSubobject(Ctx, getType(V.getLValueBase()),
206 V.getLValuePath(), MostDerivedArraySize,
George Burgess IVa51c4072015-10-16 01:49:01 +0000207 MostDerivedType, IsArray);
208 MostDerivedIsArrayElement = IsArray;
209 }
Richard Smith80815602011-11-07 05:07:52 +0000210 }
211 }
212
Richard Smith96e0c102011-11-04 02:25:55 +0000213 void setInvalid() {
214 Invalid = true;
215 Entries.clear();
216 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000217
218 /// Determine whether this is a one-past-the-end pointer.
219 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000220 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000221 if (IsOnePastTheEnd)
222 return true;
George Burgess IVa51c4072015-10-16 01:49:01 +0000223 if (MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000224 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
225 return true;
226 return false;
227 }
228
229 /// Check that this refers to a valid subobject.
230 bool isValidSubobject() const {
231 if (Invalid)
232 return false;
233 return !isOnePastTheEnd();
234 }
235 /// Check that this refers to a valid subobject, and if not, produce a
236 /// relevant diagnostic and set the designator as invalid.
237 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
238
239 /// Update this designator to refer to the first element within this array.
240 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000241 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000242 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000243 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000244
245 // This is a most-derived object.
246 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000247 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000248 MostDerivedArraySize = CAT->getSize().getZExtValue();
249 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000250 }
251 /// Update this designator to refer to the given base or member of this
252 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000253 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000254 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000255 APValue::BaseOrMemberType Value(D, Virtual);
256 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000257 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000258
259 // If this isn't a base class, it's a new most-derived object.
260 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
261 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000262 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000263 MostDerivedArraySize = 0;
264 MostDerivedPathLength = Entries.size();
265 }
Richard Smith96e0c102011-11-04 02:25:55 +0000266 }
Richard Smith66c96992012-02-18 22:04:06 +0000267 /// Update this designator to refer to the given complex component.
268 void addComplexUnchecked(QualType EltTy, bool Imag) {
269 PathEntry Entry;
270 Entry.ArrayIndex = Imag;
271 Entries.push_back(Entry);
272
273 // This is technically a most-derived object, though in practice this
274 // is unlikely to matter.
275 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000276 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000277 MostDerivedArraySize = 2;
278 MostDerivedPathLength = Entries.size();
279 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000280 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E, uint64_t N);
Richard Smith96e0c102011-11-04 02:25:55 +0000281 /// Add N to the address of this subobject.
Richard Smitha8105bc2012-01-06 16:39:00 +0000282 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith96e0c102011-11-04 02:25:55 +0000283 if (Invalid) return;
George Burgess IVa51c4072015-10-16 01:49:01 +0000284 if (MostDerivedPathLength == Entries.size() &&
285 MostDerivedIsArrayElement) {
Richard Smith80815602011-11-07 05:07:52 +0000286 Entries.back().ArrayIndex += N;
Richard Smitha8105bc2012-01-06 16:39:00 +0000287 if (Entries.back().ArrayIndex > MostDerivedArraySize) {
288 diagnosePointerArithmetic(Info, E, Entries.back().ArrayIndex);
289 setInvalid();
290 }
Richard Smith96e0c102011-11-04 02:25:55 +0000291 return;
292 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000293 // [expr.add]p4: For the purposes of these operators, a pointer to a
294 // nonarray object behaves the same as a pointer to the first element of
295 // an array of length one with the type of the object as its element type.
296 if (IsOnePastTheEnd && N == (uint64_t)-1)
297 IsOnePastTheEnd = false;
298 else if (!IsOnePastTheEnd && N == 1)
299 IsOnePastTheEnd = true;
300 else if (N != 0) {
301 diagnosePointerArithmetic(Info, E, uint64_t(IsOnePastTheEnd) + N);
Richard Smith96e0c102011-11-04 02:25:55 +0000302 setInvalid();
Richard Smitha8105bc2012-01-06 16:39:00 +0000303 }
Richard Smith96e0c102011-11-04 02:25:55 +0000304 }
305 };
306
Richard Smith254a73d2011-10-28 22:34:42 +0000307 /// A stack frame in the constexpr call stack.
308 struct CallStackFrame {
309 EvalInfo &Info;
310
311 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000312 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000313
Richard Smithf6f003a2011-12-16 19:06:07 +0000314 /// CallLoc - The location of the call expression for this call.
315 SourceLocation CallLoc;
316
317 /// Callee - The function which was called.
318 const FunctionDecl *Callee;
319
Richard Smithb228a862012-02-15 02:18:13 +0000320 /// Index - The call index of this call.
321 unsigned Index;
322
Richard Smithd62306a2011-11-10 06:34:14 +0000323 /// This - The binding for the this pointer in this call, if any.
324 const LValue *This;
325
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000326 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000327 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000328 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000329
Eli Friedman4830ec82012-06-25 21:21:08 +0000330 // Note that we intentionally use std::map here so that references to
331 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000332 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000333 typedef MapTy::const_iterator temp_iterator;
334 /// Temporaries - Temporary lvalues materialized within this stack frame.
335 MapTy Temporaries;
336
Richard Smithf6f003a2011-12-16 19:06:07 +0000337 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
338 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000339 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000340 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000341
342 APValue *getTemporary(const void *Key) {
343 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000344 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000345 }
346 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000347 };
348
Richard Smith852c9db2013-04-20 22:23:05 +0000349 /// Temporarily override 'this'.
350 class ThisOverrideRAII {
351 public:
352 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
353 : Frame(Frame), OldThis(Frame.This) {
354 if (Enable)
355 Frame.This = NewThis;
356 }
357 ~ThisOverrideRAII() {
358 Frame.This = OldThis;
359 }
360 private:
361 CallStackFrame &Frame;
362 const LValue *OldThis;
363 };
364
Richard Smith92b1ce02011-12-12 09:28:41 +0000365 /// A partial diagnostic which we might know in advance that we are not going
366 /// to emit.
367 class OptionalDiagnostic {
368 PartialDiagnostic *Diag;
369
370 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000371 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
372 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000373
374 template<typename T>
375 OptionalDiagnostic &operator<<(const T &v) {
376 if (Diag)
377 *Diag << v;
378 return *this;
379 }
Richard Smithfe800032012-01-31 04:08:20 +0000380
381 OptionalDiagnostic &operator<<(const APSInt &I) {
382 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000383 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000384 I.toString(Buffer);
385 *Diag << StringRef(Buffer.data(), Buffer.size());
386 }
387 return *this;
388 }
389
390 OptionalDiagnostic &operator<<(const APFloat &F) {
391 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000392 // FIXME: Force the precision of the source value down so we don't
393 // print digits which are usually useless (we don't really care here if
394 // we truncate a digit by accident in edge cases). Ideally,
395 // APFloat::toString would automatically print the shortest
396 // representation which rounds to the correct value, but it's a bit
397 // tricky to implement.
398 unsigned precision =
399 llvm::APFloat::semanticsPrecision(F.getSemantics());
400 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000401 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000402 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000403 *Diag << StringRef(Buffer.data(), Buffer.size());
404 }
405 return *this;
406 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000407 };
408
Richard Smith08d6a2c2013-07-24 07:11:57 +0000409 /// A cleanup, and a flag indicating whether it is lifetime-extended.
410 class Cleanup {
411 llvm::PointerIntPair<APValue*, 1, bool> Value;
412
413 public:
414 Cleanup(APValue *Val, bool IsLifetimeExtended)
415 : Value(Val, IsLifetimeExtended) {}
416
417 bool isLifetimeExtended() const { return Value.getInt(); }
418 void endLifetime() {
419 *Value.getPointer() = APValue();
420 }
421 };
422
Richard Smithb228a862012-02-15 02:18:13 +0000423 /// EvalInfo - This is a private struct used by the evaluator to capture
424 /// information about a subexpression as it is folded. It retains information
425 /// about the AST context, but also maintains information about the folded
426 /// expression.
427 ///
428 /// If an expression could be evaluated, it is still possible it is not a C
429 /// "integer constant expression" or constant expression. If not, this struct
430 /// captures information about how and why not.
431 ///
432 /// One bit of information passed *into* the request for constant folding
433 /// indicates whether the subexpression is "evaluated" or not according to C
434 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
435 /// evaluate the expression regardless of what the RHS is, but C only allows
436 /// certain things in certain situations.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000437 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000438 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000439
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000440 /// EvalStatus - Contains information about the evaluation.
441 Expr::EvalStatus &EvalStatus;
442
443 /// CurrentCall - The top of the constexpr call stack.
444 CallStackFrame *CurrentCall;
445
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000446 /// CallStackDepth - The number of calls in the call stack right now.
447 unsigned CallStackDepth;
448
Richard Smithb228a862012-02-15 02:18:13 +0000449 /// NextCallIndex - The next call index to assign.
450 unsigned NextCallIndex;
451
Richard Smitha3d3bd22013-05-08 02:12:03 +0000452 /// StepsLeft - The remaining number of evaluation steps we're permitted
453 /// to perform. This is essentially a limit for the number of statements
454 /// we will evaluate.
455 unsigned StepsLeft;
456
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000457 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000458 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000459 CallStackFrame BottomFrame;
460
Richard Smith08d6a2c2013-07-24 07:11:57 +0000461 /// A stack of values whose lifetimes end at the end of some surrounding
462 /// evaluation frame.
463 llvm::SmallVector<Cleanup, 16> CleanupStack;
464
Richard Smithd62306a2011-11-10 06:34:14 +0000465 /// EvaluatingDecl - This is the declaration whose initializer is being
466 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000467 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000468
469 /// EvaluatingDeclValue - This is the value being constructed for the
470 /// declaration whose initializer is being evaluated, if any.
471 APValue *EvaluatingDeclValue;
472
Richard Smith357362d2011-12-13 06:39:58 +0000473 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
474 /// notes attached to it will also be stored, otherwise they will not be.
475 bool HasActiveDiagnostic;
476
Richard Smith0c6124b2015-12-03 01:36:22 +0000477 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
478 /// fold (not just why it's not strictly a constant expression)?
479 bool HasFoldFailureDiagnostic;
480
George Burgess IV8c892b52016-05-25 22:31:54 +0000481 /// \brief Whether or not we're currently speculatively evaluating.
482 bool IsSpeculativelyEvaluating;
483
Richard Smith6d4c6582013-11-05 22:18:15 +0000484 enum EvaluationMode {
485 /// Evaluate as a constant expression. Stop if we find that the expression
486 /// is not a constant expression.
487 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000488
Richard Smith6d4c6582013-11-05 22:18:15 +0000489 /// Evaluate as a potential constant expression. Keep going if we hit a
490 /// construct that we can't evaluate yet (because we don't yet know the
491 /// value of something) but stop if we hit something that could never be
492 /// a constant expression.
493 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000494
Richard Smith6d4c6582013-11-05 22:18:15 +0000495 /// Fold the expression to a constant. Stop if we hit a side-effect that
496 /// we can't model.
497 EM_ConstantFold,
498
499 /// Evaluate the expression looking for integer overflow and similar
500 /// issues. Don't worry about side-effects, and try to visit all
501 /// subexpressions.
502 EM_EvaluateForOverflow,
503
504 /// Evaluate in any way we know how. Don't worry about side-effects that
505 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000506 EM_IgnoreSideEffects,
507
508 /// Evaluate as a constant expression. Stop if we find that the expression
509 /// is not a constant expression. Some expressions can be retried in the
510 /// optimizer if we don't constant fold them here, but in an unevaluated
511 /// context we try to fold them immediately since the optimizer never
512 /// gets a chance to look at it.
513 EM_ConstantExpressionUnevaluated,
514
515 /// Evaluate as a potential constant expression. Keep going if we hit a
516 /// construct that we can't evaluate yet (because we don't yet know the
517 /// value of something) but stop if we hit something that could never be
518 /// a constant expression. Some expressions can be retried in the
519 /// optimizer if we don't constant fold them here, but in an unevaluated
520 /// context we try to fold them immediately since the optimizer never
521 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000522 EM_PotentialConstantExpressionUnevaluated,
523
524 /// Evaluate as a constant expression. Continue evaluating if we find a
525 /// MemberExpr with a base that can't be evaluated.
526 EM_DesignatorFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000527 } EvalMode;
528
529 /// Are we checking whether the expression is a potential constant
530 /// expression?
531 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000532 return EvalMode == EM_PotentialConstantExpression ||
533 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000534 }
535
536 /// Are we checking an expression for overflow?
537 // FIXME: We should check for any kind of undefined or suspicious behavior
538 // in such constructs, not just overflow.
539 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
540
541 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000542 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000543 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000544 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000545 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
546 EvaluatingDecl((const ValueDecl *)nullptr),
547 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000548 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
549 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000550
Richard Smith7525ff62013-05-09 07:14:00 +0000551 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
552 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000553 EvaluatingDeclValue = &Value;
554 }
555
David Blaikiebbafb8a2012-03-11 07:00:24 +0000556 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000557
Richard Smith357362d2011-12-13 06:39:58 +0000558 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000559 // Don't perform any constexpr calls (other than the call we're checking)
560 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000561 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000562 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000563 if (NextCallIndex == 0) {
564 // NextCallIndex has wrapped around.
565 Diag(Loc, diag::note_constexpr_call_limit_exceeded);
566 return false;
567 }
Richard Smith357362d2011-12-13 06:39:58 +0000568 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
569 return true;
570 Diag(Loc, diag::note_constexpr_depth_limit_exceeded)
571 << getLangOpts().ConstexprCallDepth;
572 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000573 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000574
Richard Smithb228a862012-02-15 02:18:13 +0000575 CallStackFrame *getCallFrame(unsigned CallIndex) {
576 assert(CallIndex && "no call index in getCallFrame");
577 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
578 // be null in this loop.
579 CallStackFrame *Frame = CurrentCall;
580 while (Frame->Index > CallIndex)
581 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000582 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000583 }
584
Richard Smitha3d3bd22013-05-08 02:12:03 +0000585 bool nextStep(const Stmt *S) {
586 if (!StepsLeft) {
587 Diag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
588 return false;
589 }
590 --StepsLeft;
591 return true;
592 }
593
Richard Smith357362d2011-12-13 06:39:58 +0000594 private:
595 /// Add a diagnostic to the diagnostics list.
596 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
597 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
598 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
599 return EvalStatus.Diag->back().second;
600 }
601
Richard Smithf6f003a2011-12-16 19:06:07 +0000602 /// Add notes containing a call stack to the current point of evaluation.
603 void addCallStack(unsigned Limit);
604
Richard Smith357362d2011-12-13 06:39:58 +0000605 public:
Richard Smithf57d8cb2011-12-09 22:58:01 +0000606 /// Diagnose that the evaluation cannot be folded.
Richard Smithf2b681b2011-12-21 05:04:46 +0000607 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId
608 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith0c6124b2015-12-03 01:36:22 +0000609 unsigned ExtraNotes = 0, bool IsCCEDiag = false) {
Richard Smith92b1ce02011-12-12 09:28:41 +0000610 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000611 // If we have a prior diagnostic, it will be noting that the expression
612 // isn't a constant expression. This diagnostic is more important,
613 // unless we require this evaluation to produce a constant expression.
614 //
615 // FIXME: We might want to show both diagnostics to the user in
616 // EM_ConstantFold mode.
617 if (!EvalStatus.Diag->empty()) {
618 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000619 case EM_ConstantFold:
620 case EM_IgnoreSideEffects:
621 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000622 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000623 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000624 // We've already failed to fold something. Keep that diagnostic.
Richard Smith6d4c6582013-11-05 22:18:15 +0000625 case EM_ConstantExpression:
626 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000627 case EM_ConstantExpressionUnevaluated:
628 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000629 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000630 HasActiveDiagnostic = false;
631 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000632 }
633 }
634
Richard Smithf6f003a2011-12-16 19:06:07 +0000635 unsigned CallStackNotes = CallStackDepth - 1;
636 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
637 if (Limit)
638 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000639 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000640 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000641
Richard Smith357362d2011-12-13 06:39:58 +0000642 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000643 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000644 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000645 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
646 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000647 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000648 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000649 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000650 }
Richard Smith357362d2011-12-13 06:39:58 +0000651 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000652 return OptionalDiagnostic();
653 }
654
Richard Smithce1ec5e2012-03-15 04:53:45 +0000655 OptionalDiagnostic Diag(const Expr *E, diag::kind DiagId
656 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith0c6124b2015-12-03 01:36:22 +0000657 unsigned ExtraNotes = 0, bool IsCCEDiag = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000658 if (EvalStatus.Diag)
Richard Smith0c6124b2015-12-03 01:36:22 +0000659 return Diag(E->getExprLoc(), DiagId, ExtraNotes, IsCCEDiag);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000660 HasActiveDiagnostic = false;
661 return OptionalDiagnostic();
662 }
663
Richard Smith92b1ce02011-12-12 09:28:41 +0000664 /// Diagnose that the evaluation does not produce a C++11 core constant
665 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000666 ///
667 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
668 /// EM_PotentialConstantExpression mode and we produce one of these.
Richard Smithce1ec5e2012-03-15 04:53:45 +0000669 template<typename LocArg>
670 OptionalDiagnostic CCEDiag(LocArg Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000671 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000672 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000673 // Don't override a previous diagnostic. Don't bother collecting
674 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000675 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000676 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000677 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000678 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000679 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000680 }
681
682 /// Add a note to a prior diagnostic.
683 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
684 if (!HasActiveDiagnostic)
685 return OptionalDiagnostic();
686 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000687 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000688
689 /// Add a stack of notes to a prior diagnostic.
690 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
691 if (HasActiveDiagnostic) {
692 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
693 Diags.begin(), Diags.end());
694 }
695 }
Richard Smith253c2a32012-01-27 01:14:48 +0000696
Richard Smith6d4c6582013-11-05 22:18:15 +0000697 /// Should we continue evaluation after encountering a side-effect that we
698 /// couldn't model?
699 bool keepEvaluatingAfterSideEffect() {
700 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000701 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000702 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000703 case EM_EvaluateForOverflow:
704 case EM_IgnoreSideEffects:
705 return true;
706
Richard Smith6d4c6582013-11-05 22:18:15 +0000707 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:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000710 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000711 return false;
712 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000713 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000714 }
715
716 /// Note that we have had a side-effect, and determine whether we should
717 /// keep evaluating.
718 bool noteSideEffect() {
719 EvalStatus.HasSideEffects = true;
720 return keepEvaluatingAfterSideEffect();
721 }
722
Richard Smithce8eca52015-12-08 03:21:47 +0000723 /// Should we continue evaluation after encountering undefined behavior?
724 bool keepEvaluatingAfterUndefinedBehavior() {
725 switch (EvalMode) {
726 case EM_EvaluateForOverflow:
727 case EM_IgnoreSideEffects:
728 case EM_ConstantFold:
729 case EM_DesignatorFold:
730 return true;
731
732 case EM_PotentialConstantExpression:
733 case EM_PotentialConstantExpressionUnevaluated:
734 case EM_ConstantExpression:
735 case EM_ConstantExpressionUnevaluated:
736 return false;
737 }
738 llvm_unreachable("Missed EvalMode case");
739 }
740
741 /// Note that we hit something that was technically undefined behavior, but
742 /// that we can evaluate past it (such as signed overflow or floating-point
743 /// division by zero.)
744 bool noteUndefinedBehavior() {
745 EvalStatus.HasUndefinedBehavior = true;
746 return keepEvaluatingAfterUndefinedBehavior();
747 }
748
Richard Smith253c2a32012-01-27 01:14:48 +0000749 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000750 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000751 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000752 if (!StepsLeft)
753 return false;
754
755 switch (EvalMode) {
756 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000757 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000758 case EM_EvaluateForOverflow:
759 return true;
760
761 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000762 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000763 case EM_ConstantFold:
764 case EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +0000765 case EM_DesignatorFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000766 return false;
767 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000768 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000769 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000770
George Burgess IV8c892b52016-05-25 22:31:54 +0000771 /// Notes that we failed to evaluate an expression that other expressions
772 /// directly depend on, and determine if we should keep evaluating. This
773 /// should only be called if we actually intend to keep evaluating.
774 ///
775 /// Call noteSideEffect() instead if we may be able to ignore the value that
776 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
777 ///
778 /// (Foo(), 1) // use noteSideEffect
779 /// (Foo() || true) // use noteSideEffect
780 /// Foo() + 1 // use noteFailure
781 LLVM_ATTRIBUTE_UNUSED_RESULT bool noteFailure() {
782 // Failure when evaluating some expression often means there is some
783 // subexpression whose evaluation was skipped. Therefore, (because we
784 // don't track whether we skipped an expression when unwinding after an
785 // evaluation failure) every evaluation failure that bubbles up from a
786 // subexpression implies that a side-effect has potentially happened. We
787 // skip setting the HasSideEffects flag to true until we decide to
788 // continue evaluating after that point, which happens here.
789 bool KeepGoing = keepEvaluatingAfterFailure();
790 EvalStatus.HasSideEffects |= KeepGoing;
791 return KeepGoing;
792 }
793
George Burgess IV3a03fab2015-09-04 21:28:13 +0000794 bool allowInvalidBaseExpr() const {
795 return EvalMode == EM_DesignatorFold;
796 }
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000797 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000798
799 /// Object used to treat all foldable expressions as constant expressions.
800 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000801 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000802 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000803 bool HadNoPriorDiags;
804 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000805
Richard Smith6d4c6582013-11-05 22:18:15 +0000806 explicit FoldConstant(EvalInfo &Info, bool Enabled)
807 : Info(Info),
808 Enabled(Enabled),
809 HadNoPriorDiags(Info.EvalStatus.Diag &&
810 Info.EvalStatus.Diag->empty() &&
811 !Info.EvalStatus.HasSideEffects),
812 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000813 if (Enabled &&
814 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
815 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +0000816 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000817 }
Richard Smith6d4c6582013-11-05 22:18:15 +0000818 void keepDiagnostics() { Enabled = false; }
819 ~FoldConstant() {
820 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +0000821 !Info.EvalStatus.HasSideEffects)
822 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +0000823 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000824 }
825 };
Richard Smith17100ba2012-02-16 02:46:34 +0000826
George Burgess IV3a03fab2015-09-04 21:28:13 +0000827 /// RAII object used to treat the current evaluation as the correct pointer
828 /// offset fold for the current EvalMode
829 struct FoldOffsetRAII {
830 EvalInfo &Info;
831 EvalInfo::EvaluationMode OldMode;
832 explicit FoldOffsetRAII(EvalInfo &Info, bool Subobject)
833 : Info(Info), OldMode(Info.EvalMode) {
834 if (!Info.checkingPotentialConstantExpression())
835 Info.EvalMode = Subobject ? EvalInfo::EM_DesignatorFold
836 : EvalInfo::EM_ConstantFold;
837 }
838
839 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
840 };
841
George Burgess IV8c892b52016-05-25 22:31:54 +0000842 /// RAII object used to optionally suppress diagnostics and side-effects from
843 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +0000844 class SpeculativeEvaluationRAII {
George Burgess IV8c892b52016-05-25 22:31:54 +0000845 /// Pair of EvalInfo, and a bit that stores whether or not we were
846 /// speculatively evaluating when we created this RAII.
847 llvm::PointerIntPair<EvalInfo *, 1, bool> InfoAndOldSpecEval;
Richard Smith17100ba2012-02-16 02:46:34 +0000848 Expr::EvalStatus Old;
849
George Burgess IV8c892b52016-05-25 22:31:54 +0000850 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
851 InfoAndOldSpecEval = Other.InfoAndOldSpecEval;
852 Old = Other.Old;
853 Other.InfoAndOldSpecEval.setPointer(nullptr);
854 }
855
856 void maybeRestoreState() {
857 EvalInfo *Info = InfoAndOldSpecEval.getPointer();
858 if (!Info)
859 return;
860
861 Info->EvalStatus = Old;
862 Info->IsSpeculativelyEvaluating = InfoAndOldSpecEval.getInt();
863 }
864
Richard Smith17100ba2012-02-16 02:46:34 +0000865 public:
George Burgess IV8c892b52016-05-25 22:31:54 +0000866 SpeculativeEvaluationRAII() = default;
867
868 SpeculativeEvaluationRAII(
869 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
870 : InfoAndOldSpecEval(&Info, Info.IsSpeculativelyEvaluating),
871 Old(Info.EvalStatus) {
Richard Smith17100ba2012-02-16 02:46:34 +0000872 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +0000873 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +0000874 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000875
876 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
877 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
878 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +0000879 }
George Burgess IV8c892b52016-05-25 22:31:54 +0000880
881 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
882 maybeRestoreState();
883 moveFromAndCancel(std::move(Other));
884 return *this;
885 }
886
887 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +0000888 };
Richard Smith08d6a2c2013-07-24 07:11:57 +0000889
890 /// RAII object wrapping a full-expression or block scope, and handling
891 /// the ending of the lifetime of temporaries created within it.
892 template<bool IsFullExpression>
893 class ScopeRAII {
894 EvalInfo &Info;
895 unsigned OldStackSize;
896 public:
897 ScopeRAII(EvalInfo &Info)
898 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
899 ~ScopeRAII() {
900 // Body moved to a static method to encourage the compiler to inline away
901 // instances of this class.
902 cleanup(Info, OldStackSize);
903 }
904 private:
905 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
906 unsigned NewEnd = OldStackSize;
907 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
908 I != N; ++I) {
909 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
910 // Full-expression cleanup of a lifetime-extended temporary: nothing
911 // to do, just move this cleanup to the right place in the stack.
912 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
913 ++NewEnd;
914 } else {
915 // End the lifetime of the object.
916 Info.CleanupStack[I].endLifetime();
917 }
918 }
919 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
920 Info.CleanupStack.end());
921 }
922 };
923 typedef ScopeRAII<false> BlockScopeRAII;
924 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +0000925}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000926
Richard Smitha8105bc2012-01-06 16:39:00 +0000927bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
928 CheckSubobjectKind CSK) {
929 if (Invalid)
930 return false;
931 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000932 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +0000933 << CSK;
934 setInvalid();
935 return false;
936 }
937 return true;
938}
939
940void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
941 const Expr *E, uint64_t N) {
George Burgess IVa51c4072015-10-16 01:49:01 +0000942 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +0000943 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000944 << static_cast<int>(N) << /*array*/ 0
945 << static_cast<unsigned>(MostDerivedArraySize);
946 else
Richard Smithce1ec5e2012-03-15 04:53:45 +0000947 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smitha8105bc2012-01-06 16:39:00 +0000948 << static_cast<int>(N) << /*non-array*/ 1;
949 setInvalid();
950}
951
Richard Smithf6f003a2011-12-16 19:06:07 +0000952CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
953 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000954 APValue *Arguments)
Richard Smithf6f003a2011-12-16 19:06:07 +0000955 : Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Richard Smithb228a862012-02-15 02:18:13 +0000956 Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Richard Smithf6f003a2011-12-16 19:06:07 +0000957 Info.CurrentCall = this;
958 ++Info.CallStackDepth;
959}
960
961CallStackFrame::~CallStackFrame() {
962 assert(Info.CurrentCall == this && "calls retired out of order");
963 --Info.CallStackDepth;
964 Info.CurrentCall = Caller;
965}
966
Richard Smith08d6a2c2013-07-24 07:11:57 +0000967APValue &CallStackFrame::createTemporary(const void *Key,
968 bool IsLifetimeExtended) {
969 APValue &Result = Temporaries[Key];
970 assert(Result.isUninit() && "temporary created multiple times");
971 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
972 return Result;
973}
974
Richard Smith84401042013-06-03 05:03:02 +0000975static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +0000976
977void EvalInfo::addCallStack(unsigned Limit) {
978 // Determine which calls to skip, if any.
979 unsigned ActiveCalls = CallStackDepth - 1;
980 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
981 if (Limit && Limit < ActiveCalls) {
982 SkipStart = Limit / 2 + Limit % 2;
983 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000984 }
985
Richard Smithf6f003a2011-12-16 19:06:07 +0000986 // Walk the call stack and add the diagnostics.
987 unsigned CallIdx = 0;
988 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
989 Frame = Frame->Caller, ++CallIdx) {
990 // Skip this call?
991 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
992 if (CallIdx == SkipStart) {
993 // Note that we're skipping calls.
994 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
995 << unsigned(ActiveCalls - Limit);
996 }
997 continue;
998 }
999
Richard Smith5179eb72016-06-28 19:03:57 +00001000 // Use a different note for an inheriting constructor, because from the
1001 // user's perspective it's not really a function at all.
1002 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1003 if (CD->isInheritingConstructor()) {
1004 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1005 << CD->getParent();
1006 continue;
1007 }
1008 }
1009
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001010 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001011 llvm::raw_svector_ostream Out(Buffer);
1012 describeCall(Frame, Out);
1013 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1014 }
1015}
1016
1017namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001018 struct ComplexValue {
1019 private:
1020 bool IsInt;
1021
1022 public:
1023 APSInt IntReal, IntImag;
1024 APFloat FloatReal, FloatImag;
1025
1026 ComplexValue() : FloatReal(APFloat::Bogus), FloatImag(APFloat::Bogus) {}
1027
1028 void makeComplexFloat() { IsInt = false; }
1029 bool isComplexFloat() const { return !IsInt; }
1030 APFloat &getComplexFloatReal() { return FloatReal; }
1031 APFloat &getComplexFloatImag() { return FloatImag; }
1032
1033 void makeComplexInt() { IsInt = true; }
1034 bool isComplexInt() const { return IsInt; }
1035 APSInt &getComplexIntReal() { return IntReal; }
1036 APSInt &getComplexIntImag() { return IntImag; }
1037
Richard Smith2e312c82012-03-03 22:46:17 +00001038 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001039 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001040 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001041 else
Richard Smith2e312c82012-03-03 22:46:17 +00001042 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001043 }
Richard Smith2e312c82012-03-03 22:46:17 +00001044 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001045 assert(v.isComplexFloat() || v.isComplexInt());
1046 if (v.isComplexFloat()) {
1047 makeComplexFloat();
1048 FloatReal = v.getComplexFloatReal();
1049 FloatImag = v.getComplexFloatImag();
1050 } else {
1051 makeComplexInt();
1052 IntReal = v.getComplexIntReal();
1053 IntImag = v.getComplexIntImag();
1054 }
1055 }
John McCall93d91dc2010-05-07 17:22:02 +00001056 };
John McCall45d55e42010-05-07 21:00:08 +00001057
1058 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001059 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001060 CharUnits Offset;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001061 bool InvalidBase : 1;
1062 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001063 SubobjectDesignator Designator;
John McCall45d55e42010-05-07 21:00:08 +00001064
Richard Smithce40ad62011-11-12 22:28:03 +00001065 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001066 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001067 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001068 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001069 SubobjectDesignator &getLValueDesignator() { return Designator; }
1070 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
John McCall45d55e42010-05-07 21:00:08 +00001071
Richard Smith2e312c82012-03-03 22:46:17 +00001072 void moveInto(APValue &V) const {
1073 if (Designator.Invalid)
1074 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex);
1075 else
1076 V = APValue(Base, Offset, Designator.Entries,
1077 Designator.IsOnePastTheEnd, CallIndex);
John McCall45d55e42010-05-07 21:00:08 +00001078 }
Richard Smith2e312c82012-03-03 22:46:17 +00001079 void setFrom(ASTContext &Ctx, const APValue &V) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00001080 assert(V.isLValue());
1081 Base = V.getLValueBase();
1082 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001083 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001084 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001085 Designator = SubobjectDesignator(Ctx, V);
Richard Smith96e0c102011-11-04 02:25:55 +00001086 }
1087
George Burgess IV3a03fab2015-09-04 21:28:13 +00001088 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
Richard Smithce40ad62011-11-12 22:28:03 +00001089 Base = B;
Richard Smith96e0c102011-11-04 02:25:55 +00001090 Offset = CharUnits::Zero();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001091 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001092 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001093 Designator = SubobjectDesignator(getType(B));
1094 }
1095
George Burgess IV3a03fab2015-09-04 21:28:13 +00001096 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1097 set(B, I, true);
1098 }
1099
Richard Smitha8105bc2012-01-06 16:39:00 +00001100 // Check that this LValue is not based on a null pointer. If it is, produce
1101 // a diagnostic and mark the designator as invalid.
1102 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1103 CheckSubobjectKind CSK) {
1104 if (Designator.Invalid)
1105 return false;
1106 if (!Base) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001107 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001108 << CSK;
1109 Designator.setInvalid();
1110 return false;
1111 }
1112 return true;
1113 }
1114
1115 // Check this LValue refers to an object. If not, set the designator to be
1116 // invalid and emit a diagnostic.
1117 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001118 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001119 Designator.checkSubobject(Info, E, CSK);
1120 }
1121
1122 void addDecl(EvalInfo &Info, const Expr *E,
1123 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001124 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1125 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001126 }
1127 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001128 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1129 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001130 }
Richard Smith66c96992012-02-18 22:04:06 +00001131 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001132 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1133 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001134 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001135 void adjustIndex(EvalInfo &Info, const Expr *E, uint64_t N) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001136 if (N && checkNullPointer(Info, E, CSK_ArrayIndex))
Richard Smithce1ec5e2012-03-15 04:53:45 +00001137 Designator.adjustIndex(Info, E, N);
John McCallc07a0c72011-02-17 10:25:35 +00001138 }
John McCall45d55e42010-05-07 21:00:08 +00001139 };
Richard Smith027bf112011-11-17 22:56:20 +00001140
1141 struct MemberPtr {
1142 MemberPtr() {}
1143 explicit MemberPtr(const ValueDecl *Decl) :
1144 DeclAndIsDerivedMember(Decl, false), Path() {}
1145
1146 /// The member or (direct or indirect) field referred to by this member
1147 /// pointer, or 0 if this is a null member pointer.
1148 const ValueDecl *getDecl() const {
1149 return DeclAndIsDerivedMember.getPointer();
1150 }
1151 /// Is this actually a member of some type derived from the relevant class?
1152 bool isDerivedMember() const {
1153 return DeclAndIsDerivedMember.getInt();
1154 }
1155 /// Get the class which the declaration actually lives in.
1156 const CXXRecordDecl *getContainingRecord() const {
1157 return cast<CXXRecordDecl>(
1158 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1159 }
1160
Richard Smith2e312c82012-03-03 22:46:17 +00001161 void moveInto(APValue &V) const {
1162 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001163 }
Richard Smith2e312c82012-03-03 22:46:17 +00001164 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001165 assert(V.isMemberPointer());
1166 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1167 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1168 Path.clear();
1169 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1170 Path.insert(Path.end(), P.begin(), P.end());
1171 }
1172
1173 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1174 /// whether the member is a member of some class derived from the class type
1175 /// of the member pointer.
1176 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1177 /// Path - The path of base/derived classes from the member declaration's
1178 /// class (exclusive) to the class type of the member pointer (inclusive).
1179 SmallVector<const CXXRecordDecl*, 4> Path;
1180
1181 /// Perform a cast towards the class of the Decl (either up or down the
1182 /// hierarchy).
1183 bool castBack(const CXXRecordDecl *Class) {
1184 assert(!Path.empty());
1185 const CXXRecordDecl *Expected;
1186 if (Path.size() >= 2)
1187 Expected = Path[Path.size() - 2];
1188 else
1189 Expected = getContainingRecord();
1190 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1191 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1192 // if B does not contain the original member and is not a base or
1193 // derived class of the class containing the original member, the result
1194 // of the cast is undefined.
1195 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1196 // (D::*). We consider that to be a language defect.
1197 return false;
1198 }
1199 Path.pop_back();
1200 return true;
1201 }
1202 /// Perform a base-to-derived member pointer cast.
1203 bool castToDerived(const CXXRecordDecl *Derived) {
1204 if (!getDecl())
1205 return true;
1206 if (!isDerivedMember()) {
1207 Path.push_back(Derived);
1208 return true;
1209 }
1210 if (!castBack(Derived))
1211 return false;
1212 if (Path.empty())
1213 DeclAndIsDerivedMember.setInt(false);
1214 return true;
1215 }
1216 /// Perform a derived-to-base member pointer cast.
1217 bool castToBase(const CXXRecordDecl *Base) {
1218 if (!getDecl())
1219 return true;
1220 if (Path.empty())
1221 DeclAndIsDerivedMember.setInt(true);
1222 if (isDerivedMember()) {
1223 Path.push_back(Base);
1224 return true;
1225 }
1226 return castBack(Base);
1227 }
1228 };
Richard Smith357362d2011-12-13 06:39:58 +00001229
Richard Smith7bb00672012-02-01 01:42:44 +00001230 /// Compare two member pointers, which are assumed to be of the same type.
1231 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1232 if (!LHS.getDecl() || !RHS.getDecl())
1233 return !LHS.getDecl() && !RHS.getDecl();
1234 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1235 return false;
1236 return LHS.Path == RHS.Path;
1237 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001238}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001239
Richard Smith2e312c82012-03-03 22:46:17 +00001240static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001241static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1242 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001243 bool AllowNonLiteralTypes = false);
John McCall45d55e42010-05-07 21:00:08 +00001244static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info);
1245static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info);
Richard Smith027bf112011-11-17 22:56:20 +00001246static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1247 EvalInfo &Info);
1248static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001249static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001250static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001251 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001252static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001253static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smitha23ab512013-05-23 00:30:41 +00001254static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001255static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001256
1257//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001258// Misc utilities
1259//===----------------------------------------------------------------------===//
1260
Richard Smith84401042013-06-03 05:03:02 +00001261/// Produce a string describing the given constexpr call.
1262static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1263 unsigned ArgIndex = 0;
1264 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1265 !isa<CXXConstructorDecl>(Frame->Callee) &&
1266 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1267
1268 if (!IsMemberCall)
1269 Out << *Frame->Callee << '(';
1270
1271 if (Frame->This && IsMemberCall) {
1272 APValue Val;
1273 Frame->This->moveInto(Val);
1274 Val.printPretty(Out, Frame->Info.Ctx,
1275 Frame->This->Designator.MostDerivedType);
1276 // FIXME: Add parens around Val if needed.
1277 Out << "->" << *Frame->Callee << '(';
1278 IsMemberCall = false;
1279 }
1280
1281 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1282 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1283 if (ArgIndex > (unsigned)IsMemberCall)
1284 Out << ", ";
1285
1286 const ParmVarDecl *Param = *I;
1287 const APValue &Arg = Frame->Arguments[ArgIndex];
1288 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1289
1290 if (ArgIndex == 0 && IsMemberCall)
1291 Out << "->" << *Frame->Callee << '(';
1292 }
1293
1294 Out << ')';
1295}
1296
Richard Smithd9f663b2013-04-22 15:31:51 +00001297/// Evaluate an expression to see if it had side-effects, and discard its
1298/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001299/// \return \c true if the caller should keep evaluating.
1300static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001301 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001302 if (!Evaluate(Scratch, Info, E))
1303 // We don't need the value, but we might have skipped a side effect here.
1304 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001305 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001306}
1307
Richard Smith861b5b52013-05-07 23:34:45 +00001308/// Sign- or zero-extend a value to 64 bits. If it's already 64 bits, just
1309/// return its existing value.
1310static int64_t getExtValue(const APSInt &Value) {
1311 return Value.isSigned() ? Value.getSExtValue()
1312 : static_cast<int64_t>(Value.getZExtValue());
1313}
1314
Richard Smithd62306a2011-11-10 06:34:14 +00001315/// Should this call expression be treated as a string literal?
1316static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001317 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001318 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1319 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1320}
1321
Richard Smithce40ad62011-11-12 22:28:03 +00001322static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001323 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1324 // constant expression of pointer type that evaluates to...
1325
1326 // ... a null pointer value, or a prvalue core constant expression of type
1327 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001328 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001329
Richard Smithce40ad62011-11-12 22:28:03 +00001330 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1331 // ... the address of an object with static storage duration,
1332 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1333 return VD->hasGlobalStorage();
1334 // ... the address of a function,
1335 return isa<FunctionDecl>(D);
1336 }
1337
1338 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001339 switch (E->getStmtClass()) {
1340 default:
1341 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001342 case Expr::CompoundLiteralExprClass: {
1343 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1344 return CLE->isFileScope() && CLE->isLValue();
1345 }
Richard Smithe6c01442013-06-05 00:46:14 +00001346 case Expr::MaterializeTemporaryExprClass:
1347 // A materialized temporary might have been lifetime-extended to static
1348 // storage duration.
1349 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001350 // A string literal has static storage duration.
1351 case Expr::StringLiteralClass:
1352 case Expr::PredefinedExprClass:
1353 case Expr::ObjCStringLiteralClass:
1354 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001355 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001356 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001357 return true;
1358 case Expr::CallExprClass:
1359 return IsStringLiteralCall(cast<CallExpr>(E));
1360 // For GCC compatibility, &&label has static storage duration.
1361 case Expr::AddrLabelExprClass:
1362 return true;
1363 // A Block literal expression may be used as the initialization value for
1364 // Block variables at global or local static scope.
1365 case Expr::BlockExprClass:
1366 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001367 case Expr::ImplicitValueInitExprClass:
1368 // FIXME:
1369 // We can never form an lvalue with an implicit value initialization as its
1370 // base through expression evaluation, so these only appear in one case: the
1371 // implicit variable declaration we invent when checking whether a constexpr
1372 // constructor can produce a constant expression. We must assume that such
1373 // an expression might be a global lvalue.
1374 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001375 }
John McCall95007602010-05-10 23:27:23 +00001376}
1377
Richard Smithb228a862012-02-15 02:18:13 +00001378static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1379 assert(Base && "no location for a null lvalue");
1380 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1381 if (VD)
1382 Info.Note(VD->getLocation(), diag::note_declared_at);
1383 else
Ted Kremenek28831752012-08-23 20:46:57 +00001384 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001385 diag::note_constexpr_temporary_here);
1386}
1387
Richard Smith80815602011-11-07 05:07:52 +00001388/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001389/// value for an address or reference constant expression. Return true if we
1390/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001391static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1392 QualType Type, const LValue &LVal) {
1393 bool IsReferenceType = Type->isReferenceType();
1394
Richard Smith357362d2011-12-13 06:39:58 +00001395 APValue::LValueBase Base = LVal.getLValueBase();
1396 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1397
Richard Smith0dea49e2012-02-18 04:58:18 +00001398 // Check that the object is a global. Note that the fake 'this' object we
1399 // manufacture when checking potential constant expressions is conservatively
1400 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001401 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001402 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001403 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001404 Info.Diag(Loc, diag::note_constexpr_non_global, 1)
1405 << IsReferenceType << !Designator.Entries.empty()
1406 << !!VD << VD;
1407 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001408 } else {
Richard Smithb228a862012-02-15 02:18:13 +00001409 Info.Diag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001410 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001411 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001412 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001413 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001414 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001415 LVal.getLValueCallIndex() == 0) &&
1416 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001417
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001418 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1419 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001420 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001421 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001422 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001423
Hans Wennborg82dd8772014-06-25 22:19:48 +00001424 // A dllimport variable never acts like a constant.
1425 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001426 return false;
1427 }
1428 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1429 // __declspec(dllimport) must be handled very carefully:
1430 // We must never initialize an expression with the thunk in C++.
1431 // Doing otherwise would allow the same id-expression to yield
1432 // different addresses for the same function in different translation
1433 // units. However, this means that we must dynamically initialize the
1434 // expression with the contents of the import address table at runtime.
1435 //
1436 // The C language has no notion of ODR; furthermore, it has no notion of
1437 // dynamic initialization. This means that we are permitted to
1438 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001439 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001440 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001441 }
1442 }
1443
Richard Smitha8105bc2012-01-06 16:39:00 +00001444 // Allow address constant expressions to be past-the-end pointers. This is
1445 // an extension: the standard requires them to point to an object.
1446 if (!IsReferenceType)
1447 return true;
1448
1449 // A reference constant expression must refer to an object.
1450 if (!Base) {
1451 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001452 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001453 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001454 }
1455
Richard Smith357362d2011-12-13 06:39:58 +00001456 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001457 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001458 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Richard Smithb228a862012-02-15 02:18:13 +00001459 Info.Diag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001460 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001461 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001462 }
1463
Richard Smith80815602011-11-07 05:07:52 +00001464 return true;
1465}
1466
Richard Smithfddd3842011-12-30 21:15:51 +00001467/// Check that this core constant expression is of literal type, and if not,
1468/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001469static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001470 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001471 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001472 return true;
1473
Richard Smith7525ff62013-05-09 07:14:00 +00001474 // C++1y: A constant initializer for an object o [...] may also invoke
1475 // constexpr constructors for o and its subobjects even if those objects
1476 // are of non-literal class types.
Aaron Ballmandd69ef32014-08-19 15:55:55 +00001477 if (Info.getLangOpts().CPlusPlus14 && This &&
Richard Smith37dc92e2013-05-16 05:04:51 +00001478 Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001479 return true;
1480
Richard Smithfddd3842011-12-30 21:15:51 +00001481 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001482 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001483 Info.Diag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001484 << E->getType();
1485 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001486 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001487 return false;
1488}
1489
Richard Smith0b0a0b62011-10-29 20:57:55 +00001490/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001491/// constant expression. If not, report an appropriate diagnostic. Does not
1492/// check that the expression is of literal type.
1493static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1494 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001495 if (Value.isUninit()) {
Richard Smith51f03172013-06-20 03:00:05 +00001496 Info.Diag(DiagLoc, diag::note_constexpr_uninitialized)
1497 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001498 return false;
1499 }
1500
Richard Smith77be48a2014-07-31 06:31:19 +00001501 // We allow _Atomic(T) to be initialized from anything that T can be
1502 // initialized from.
1503 if (const AtomicType *AT = Type->getAs<AtomicType>())
1504 Type = AT->getValueType();
1505
Richard Smithb228a862012-02-15 02:18:13 +00001506 // Core issue 1454: For a literal constant expression of array or class type,
1507 // each subobject of its value shall have been initialized by a constant
1508 // expression.
1509 if (Value.isArray()) {
1510 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1511 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1512 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1513 Value.getArrayInitializedElt(I)))
1514 return false;
1515 }
1516 if (!Value.hasArrayFiller())
1517 return true;
1518 return CheckConstantExpression(Info, DiagLoc, EltTy,
1519 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001520 }
Richard Smithb228a862012-02-15 02:18:13 +00001521 if (Value.isUnion() && Value.getUnionField()) {
1522 return CheckConstantExpression(Info, DiagLoc,
1523 Value.getUnionField()->getType(),
1524 Value.getUnionValue());
1525 }
1526 if (Value.isStruct()) {
1527 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1528 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1529 unsigned BaseIndex = 0;
1530 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1531 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1532 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1533 Value.getStructBase(BaseIndex)))
1534 return false;
1535 }
1536 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001537 for (const auto *I : RD->fields()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00001538 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1539 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001540 return false;
1541 }
1542 }
1543
1544 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001545 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001546 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001547 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1548 }
1549
1550 // Everything else is fine.
1551 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001552}
1553
Benjamin Kramer8407df72015-03-09 16:47:52 +00001554static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001555 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001556}
1557
1558static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001559 if (Value.CallIndex)
1560 return false;
1561 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1562 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001563}
1564
Richard Smithcecf1842011-11-01 21:06:14 +00001565static bool IsWeakLValue(const LValue &Value) {
1566 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001567 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001568}
1569
David Majnemerb5116032014-12-09 23:32:34 +00001570static bool isZeroSized(const LValue &Value) {
1571 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001572 if (Decl && isa<VarDecl>(Decl)) {
1573 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001574 if (Ty->isArrayType())
1575 return Ty->isIncompleteType() ||
1576 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001577 }
1578 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001579}
1580
Richard Smith2e312c82012-03-03 22:46:17 +00001581static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001582 // A null base expression indicates a null pointer. These are always
1583 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001584 if (!Value.getLValueBase()) {
1585 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001586 return true;
1587 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001588
Richard Smith027bf112011-11-17 22:56:20 +00001589 // We have a non-null base. These are generally known to be true, but if it's
1590 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001591 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001592 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001593 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001594}
1595
Richard Smith2e312c82012-03-03 22:46:17 +00001596static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001597 switch (Val.getKind()) {
1598 case APValue::Uninitialized:
1599 return false;
1600 case APValue::Int:
1601 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001602 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001603 case APValue::Float:
1604 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001605 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001606 case APValue::ComplexInt:
1607 Result = Val.getComplexIntReal().getBoolValue() ||
1608 Val.getComplexIntImag().getBoolValue();
1609 return true;
1610 case APValue::ComplexFloat:
1611 Result = !Val.getComplexFloatReal().isZero() ||
1612 !Val.getComplexFloatImag().isZero();
1613 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001614 case APValue::LValue:
1615 return EvalPointerValueAsBool(Val, Result);
1616 case APValue::MemberPointer:
1617 Result = Val.getMemberPointerDecl();
1618 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001619 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001620 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001621 case APValue::Struct:
1622 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001623 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001624 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001625 }
1626
Richard Smith11562c52011-10-28 17:51:58 +00001627 llvm_unreachable("unknown APValue kind");
1628}
1629
1630static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1631 EvalInfo &Info) {
1632 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001633 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001634 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001635 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001636 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001637}
1638
Richard Smith357362d2011-12-13 06:39:58 +00001639template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001640static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001641 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001642 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001643 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001644 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001645}
1646
1647static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1648 QualType SrcType, const APFloat &Value,
1649 QualType DestType, APSInt &Result) {
1650 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001651 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001652 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001653
Richard Smith357362d2011-12-13 06:39:58 +00001654 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001655 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001656 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1657 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001658 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001659 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001660}
1661
Richard Smith357362d2011-12-13 06:39:58 +00001662static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1663 QualType SrcType, QualType DestType,
1664 APFloat &Result) {
1665 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001666 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001667 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1668 APFloat::rmNearestTiesToEven, &ignored)
1669 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001670 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001671 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001672}
1673
Richard Smith911e1422012-01-30 22:27:01 +00001674static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1675 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001676 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001677 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001678 APSInt Result = Value;
1679 // Figure out if this is a truncate, extend or noop cast.
1680 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001681 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001682 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001683 return Result;
1684}
1685
Richard Smith357362d2011-12-13 06:39:58 +00001686static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1687 QualType SrcType, const APSInt &Value,
1688 QualType DestType, APFloat &Result) {
1689 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1690 if (Result.convertFromAPInt(Value, Value.isSigned(),
1691 APFloat::rmNearestTiesToEven)
1692 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001693 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001694 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001695}
1696
Richard Smith49ca8aa2013-08-06 07:09:20 +00001697static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1698 APValue &Value, const FieldDecl *FD) {
1699 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1700
1701 if (!Value.isInt()) {
1702 // Trying to store a pointer-cast-to-integer into a bitfield.
1703 // FIXME: In this case, we should provide the diagnostic for casting
1704 // a pointer to an integer.
1705 assert(Value.isLValue() && "integral value neither int nor lvalue?");
1706 Info.Diag(E);
1707 return false;
1708 }
1709
1710 APSInt &Int = Value.getInt();
1711 unsigned OldBitWidth = Int.getBitWidth();
1712 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
1713 if (NewBitWidth < OldBitWidth)
1714 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
1715 return true;
1716}
1717
Eli Friedman803acb32011-12-22 03:51:45 +00001718static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
1719 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00001720 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00001721 if (!Evaluate(SVal, Info, E))
1722 return false;
1723 if (SVal.isInt()) {
1724 Res = SVal.getInt();
1725 return true;
1726 }
1727 if (SVal.isFloat()) {
1728 Res = SVal.getFloat().bitcastToAPInt();
1729 return true;
1730 }
1731 if (SVal.isVector()) {
1732 QualType VecTy = E->getType();
1733 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
1734 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
1735 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
1736 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
1737 Res = llvm::APInt::getNullValue(VecSize);
1738 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
1739 APValue &Elt = SVal.getVectorElt(i);
1740 llvm::APInt EltAsInt;
1741 if (Elt.isInt()) {
1742 EltAsInt = Elt.getInt();
1743 } else if (Elt.isFloat()) {
1744 EltAsInt = Elt.getFloat().bitcastToAPInt();
1745 } else {
1746 // Don't try to handle vectors of anything other than int or float
1747 // (not sure if it's possible to hit this case).
Richard Smithce1ec5e2012-03-15 04:53:45 +00001748 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001749 return false;
1750 }
1751 unsigned BaseEltSize = EltAsInt.getBitWidth();
1752 if (BigEndian)
1753 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
1754 else
1755 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
1756 }
1757 return true;
1758 }
1759 // Give up if the input isn't an int, float, or vector. For example, we
1760 // reject "(v4i16)(intptr_t)&a".
Richard Smithce1ec5e2012-03-15 04:53:45 +00001761 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00001762 return false;
1763}
1764
Richard Smith43e77732013-05-07 04:50:00 +00001765/// Perform the given integer operation, which is known to need at most BitWidth
1766/// bits, and check for overflow in the original type (if that type was not an
1767/// unsigned type).
1768template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00001769static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
1770 const APSInt &LHS, const APSInt &RHS,
1771 unsigned BitWidth, Operation Op,
1772 APSInt &Result) {
1773 if (LHS.isUnsigned()) {
1774 Result = Op(LHS, RHS);
1775 return true;
1776 }
Richard Smith43e77732013-05-07 04:50:00 +00001777
1778 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00001779 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00001780 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00001781 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00001782 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00001783 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00001784 << Result.toString(10) << E->getType();
1785 else
Richard Smith0c6124b2015-12-03 01:36:22 +00001786 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001787 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001788 return true;
Richard Smith43e77732013-05-07 04:50:00 +00001789}
1790
1791/// Perform the given binary integer operation.
1792static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
1793 BinaryOperatorKind Opcode, APSInt RHS,
1794 APSInt &Result) {
1795 switch (Opcode) {
1796 default:
1797 Info.Diag(E);
1798 return false;
1799 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00001800 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
1801 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001802 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00001803 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1804 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001805 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00001806 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
1807 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00001808 case BO_And: Result = LHS & RHS; return true;
1809 case BO_Xor: Result = LHS ^ RHS; return true;
1810 case BO_Or: Result = LHS | RHS; return true;
1811 case BO_Div:
1812 case BO_Rem:
1813 if (RHS == 0) {
1814 Info.Diag(E, diag::note_expr_divide_by_zero);
1815 return false;
1816 }
Richard Smith0c6124b2015-12-03 01:36:22 +00001817 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
1818 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
1819 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00001820 if (RHS.isNegative() && RHS.isAllOnesValue() &&
1821 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00001822 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
1823 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00001824 return true;
1825 case BO_Shl: {
1826 if (Info.getLangOpts().OpenCL)
1827 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1828 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1829 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1830 RHS.isUnsigned());
1831 else if (RHS.isSigned() && RHS.isNegative()) {
1832 // During constant-folding, a negative shift is an opposite shift. Such
1833 // a shift is not a constant expression.
1834 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1835 RHS = -RHS;
1836 goto shift_right;
1837 }
1838 shift_left:
1839 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
1840 // the shifted type.
1841 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1842 if (SA != RHS) {
1843 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1844 << RHS << E->getType() << LHS.getBitWidth();
1845 } else if (LHS.isSigned()) {
1846 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
1847 // operand, and must not overflow the corresponding unsigned type.
1848 if (LHS.isNegative())
1849 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
1850 else if (LHS.countLeadingZeros() < SA)
1851 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
1852 }
1853 Result = LHS << SA;
1854 return true;
1855 }
1856 case BO_Shr: {
1857 if (Info.getLangOpts().OpenCL)
1858 // OpenCL 6.3j: shift values are effectively % word size of LHS.
1859 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
1860 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
1861 RHS.isUnsigned());
1862 else if (RHS.isSigned() && RHS.isNegative()) {
1863 // During constant-folding, a negative shift is an opposite shift. Such a
1864 // shift is not a constant expression.
1865 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
1866 RHS = -RHS;
1867 goto shift_left;
1868 }
1869 shift_right:
1870 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
1871 // shifted type.
1872 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
1873 if (SA != RHS)
1874 Info.CCEDiag(E, diag::note_constexpr_large_shift)
1875 << RHS << E->getType() << LHS.getBitWidth();
1876 Result = LHS >> SA;
1877 return true;
1878 }
1879
1880 case BO_LT: Result = LHS < RHS; return true;
1881 case BO_GT: Result = LHS > RHS; return true;
1882 case BO_LE: Result = LHS <= RHS; return true;
1883 case BO_GE: Result = LHS >= RHS; return true;
1884 case BO_EQ: Result = LHS == RHS; return true;
1885 case BO_NE: Result = LHS != RHS; return true;
1886 }
1887}
1888
Richard Smith861b5b52013-05-07 23:34:45 +00001889/// Perform the given binary floating-point operation, in-place, on LHS.
1890static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
1891 APFloat &LHS, BinaryOperatorKind Opcode,
1892 const APFloat &RHS) {
1893 switch (Opcode) {
1894 default:
1895 Info.Diag(E);
1896 return false;
1897 case BO_Mul:
1898 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
1899 break;
1900 case BO_Add:
1901 LHS.add(RHS, APFloat::rmNearestTiesToEven);
1902 break;
1903 case BO_Sub:
1904 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
1905 break;
1906 case BO_Div:
1907 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
1908 break;
1909 }
1910
Richard Smith0c6124b2015-12-03 01:36:22 +00001911 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00001912 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00001913 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00001914 }
Richard Smith861b5b52013-05-07 23:34:45 +00001915 return true;
1916}
1917
Richard Smitha8105bc2012-01-06 16:39:00 +00001918/// Cast an lvalue referring to a base subobject to a derived class, by
1919/// truncating the lvalue's path to the given length.
1920static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
1921 const RecordDecl *TruncatedType,
1922 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00001923 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00001924
1925 // Check we actually point to a derived class object.
1926 if (TruncatedElements == D.Entries.size())
1927 return true;
1928 assert(TruncatedElements >= D.MostDerivedPathLength &&
1929 "not casting to a derived class");
1930 if (!Result.checkSubobject(Info, E, CSK_Derived))
1931 return false;
1932
1933 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00001934 const RecordDecl *RD = TruncatedType;
1935 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00001936 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001937 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
1938 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00001939 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00001940 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00001941 else
Richard Smithd62306a2011-11-10 06:34:14 +00001942 Result.Offset -= Layout.getBaseClassOffset(Base);
1943 RD = Base;
1944 }
Richard Smith027bf112011-11-17 22:56:20 +00001945 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00001946 return true;
1947}
1948
John McCalld7bca762012-05-01 00:38:49 +00001949static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001950 const CXXRecordDecl *Derived,
1951 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00001952 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00001953 if (!RL) {
1954 if (Derived->isInvalidDecl()) return false;
1955 RL = &Info.Ctx.getASTRecordLayout(Derived);
1956 }
1957
Richard Smithd62306a2011-11-10 06:34:14 +00001958 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00001959 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00001960 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001961}
1962
Richard Smitha8105bc2012-01-06 16:39:00 +00001963static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00001964 const CXXRecordDecl *DerivedDecl,
1965 const CXXBaseSpecifier *Base) {
1966 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
1967
John McCalld7bca762012-05-01 00:38:49 +00001968 if (!Base->isVirtual())
1969 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00001970
Richard Smitha8105bc2012-01-06 16:39:00 +00001971 SubobjectDesignator &D = Obj.Designator;
1972 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00001973 return false;
1974
Richard Smitha8105bc2012-01-06 16:39:00 +00001975 // Extract most-derived object and corresponding type.
1976 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
1977 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
1978 return false;
1979
1980 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00001981 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00001982 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
1983 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00001984 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00001985 return true;
1986}
1987
Richard Smith84401042013-06-03 05:03:02 +00001988static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
1989 QualType Type, LValue &Result) {
1990 for (CastExpr::path_const_iterator PathI = E->path_begin(),
1991 PathE = E->path_end();
1992 PathI != PathE; ++PathI) {
1993 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
1994 *PathI))
1995 return false;
1996 Type = (*PathI)->getType();
1997 }
1998 return true;
1999}
2000
Richard Smithd62306a2011-11-10 06:34:14 +00002001/// Update LVal to refer to the given field, which must be a member of the type
2002/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002003static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002004 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002005 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002006 if (!RL) {
2007 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002008 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002009 }
Richard Smithd62306a2011-11-10 06:34:14 +00002010
2011 unsigned I = FD->getFieldIndex();
2012 LVal.Offset += Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I));
Richard Smitha8105bc2012-01-06 16:39:00 +00002013 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002014 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002015}
2016
Richard Smith1b78b3d2012-01-25 22:15:11 +00002017/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002018static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002019 LValue &LVal,
2020 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002021 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002022 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002023 return false;
2024 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002025}
2026
Richard Smithd62306a2011-11-10 06:34:14 +00002027/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002028static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2029 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002030 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2031 // extension.
2032 if (Type->isVoidType() || Type->isFunctionType()) {
2033 Size = CharUnits::One();
2034 return true;
2035 }
2036
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002037 if (Type->isDependentType()) {
2038 Info.Diag(Loc);
2039 return false;
2040 }
2041
Richard Smithd62306a2011-11-10 06:34:14 +00002042 if (!Type->isConstantSizeType()) {
2043 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002044 // FIXME: Better diagnostic.
2045 Info.Diag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002046 return false;
2047 }
2048
2049 Size = Info.Ctx.getTypeSizeInChars(Type);
2050 return true;
2051}
2052
2053/// Update a pointer value to model pointer arithmetic.
2054/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002055/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002056/// \param LVal - The pointer value to be updated.
2057/// \param EltTy - The pointee type represented by LVal.
2058/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002059static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2060 LValue &LVal, QualType EltTy,
2061 int64_t Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002062 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002063 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002064 return false;
2065
2066 // Compute the new offset in the appropriate width.
2067 LVal.Offset += Adjustment * SizeOfPointee;
Richard Smitha8105bc2012-01-06 16:39:00 +00002068 LVal.adjustIndex(Info, E, Adjustment);
Richard Smithd62306a2011-11-10 06:34:14 +00002069 return true;
2070}
2071
Richard Smith66c96992012-02-18 22:04:06 +00002072/// Update an lvalue to refer to a component of a complex number.
2073/// \param Info - Information about the ongoing evaluation.
2074/// \param LVal - The lvalue to be updated.
2075/// \param EltTy - The complex number's component type.
2076/// \param Imag - False for the real component, true for the imaginary.
2077static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2078 LValue &LVal, QualType EltTy,
2079 bool Imag) {
2080 if (Imag) {
2081 CharUnits SizeOfComponent;
2082 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2083 return false;
2084 LVal.Offset += SizeOfComponent;
2085 }
2086 LVal.addComplex(Info, E, EltTy, Imag);
2087 return true;
2088}
2089
Richard Smith27908702011-10-24 17:54:18 +00002090/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002091///
2092/// \param Info Information about the ongoing evaluation.
2093/// \param E An expression to be used when printing diagnostics.
2094/// \param VD The variable whose initializer should be obtained.
2095/// \param Frame The frame in which the variable was created. Must be null
2096/// if this variable is not local to the evaluation.
2097/// \param Result Filled in with a pointer to the value of the variable.
2098static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2099 const VarDecl *VD, CallStackFrame *Frame,
2100 APValue *&Result) {
Richard Smith254a73d2011-10-28 22:34:42 +00002101 // If this is a parameter to an active constexpr function call, perform
2102 // argument substitution.
2103 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002104 // Assume arguments of a potential constant expression are unknown
2105 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002106 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002107 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002108 if (!Frame || !Frame->Arguments) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002109 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002110 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002111 }
Richard Smith3229b742013-05-05 21:17:10 +00002112 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002113 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002114 }
Richard Smith27908702011-10-24 17:54:18 +00002115
Richard Smithd9f663b2013-04-22 15:31:51 +00002116 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002117 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002118 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002119 if (!Result) {
2120 // Assume variables referenced within a lambda's call operator that were
2121 // not declared within the call operator are captures and during checking
2122 // of a potential constant expression, assume they are unknown constant
2123 // expressions.
2124 assert(isLambdaCallOperator(Frame->Callee) &&
2125 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2126 "missing value for local variable");
2127 if (Info.checkingPotentialConstantExpression())
2128 return false;
2129 // FIXME: implement capture evaluation during constant expr evaluation.
2130 Info.Diag(E->getLocStart(),
2131 diag::note_unimplemented_constexpr_lambda_feature_ast)
2132 << "captures not currently allowed";
2133 return false;
2134 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002135 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002136 }
2137
Richard Smithd0b4dd62011-12-19 06:19:21 +00002138 // Dig out the initializer, and use the declaration which it's attached to.
2139 const Expr *Init = VD->getAnyInitializer(VD);
2140 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002141 // If we're checking a potential constant expression, the variable could be
2142 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002143 if (!Info.checkingPotentialConstantExpression())
Richard Smithce1ec5e2012-03-15 04:53:45 +00002144 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002145 return false;
2146 }
2147
Richard Smithd62306a2011-11-10 06:34:14 +00002148 // If we're currently evaluating the initializer of this declaration, use that
2149 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002150 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002151 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002152 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002153 }
2154
Richard Smithcecf1842011-11-01 21:06:14 +00002155 // Never evaluate the initializer of a weak variable. We can't be sure that
2156 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002157 if (VD->isWeak()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002158 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002159 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002160 }
Richard Smithcecf1842011-11-01 21:06:14 +00002161
Richard Smithd0b4dd62011-12-19 06:19:21 +00002162 // Check that we can fold the initializer. In C++, we will have already done
2163 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002164 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002165 if (!VD->evaluateValue(Notes)) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002166 Info.Diag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002167 Notes.size() + 1) << VD;
2168 Info.Note(VD->getLocation(), diag::note_declared_at);
2169 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002170 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002171 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002172 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002173 Notes.size() + 1) << VD;
2174 Info.Note(VD->getLocation(), diag::note_declared_at);
2175 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002176 }
Richard Smith27908702011-10-24 17:54:18 +00002177
Richard Smith3229b742013-05-05 21:17:10 +00002178 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002179 return true;
Richard Smith27908702011-10-24 17:54:18 +00002180}
2181
Richard Smith11562c52011-10-28 17:51:58 +00002182static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002183 Qualifiers Quals = T.getQualifiers();
2184 return Quals.hasConst() && !Quals.hasVolatile();
2185}
2186
Richard Smithe97cbd72011-11-11 04:05:33 +00002187/// Get the base index of the given base class within an APValue representing
2188/// the given derived class.
2189static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2190 const CXXRecordDecl *Base) {
2191 Base = Base->getCanonicalDecl();
2192 unsigned Index = 0;
2193 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2194 E = Derived->bases_end(); I != E; ++I, ++Index) {
2195 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2196 return Index;
2197 }
2198
2199 llvm_unreachable("base class missing from derived class's bases list");
2200}
2201
Richard Smith3da88fa2013-04-26 14:36:30 +00002202/// Extract the value of a character from a string literal.
2203static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2204 uint64_t Index) {
Alexey Bataevec474782014-10-09 08:45:04 +00002205 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
2206 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2207 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002208 const StringLiteral *S = cast<StringLiteral>(Lit);
2209 const ConstantArrayType *CAT =
2210 Info.Ctx.getAsConstantArrayType(S->getType());
2211 assert(CAT && "string literal isn't an array");
2212 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002213 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002214
2215 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002216 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002217 if (Index < S->getLength())
2218 Value = S->getCodeUnit(Index);
2219 return Value;
2220}
2221
Richard Smith3da88fa2013-04-26 14:36:30 +00002222// Expand a string literal into an array of characters.
2223static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2224 APValue &Result) {
2225 const StringLiteral *S = cast<StringLiteral>(Lit);
2226 const ConstantArrayType *CAT =
2227 Info.Ctx.getAsConstantArrayType(S->getType());
2228 assert(CAT && "string literal isn't an array");
2229 QualType CharType = CAT->getElementType();
2230 assert(CharType->isIntegerType() && "unexpected character type");
2231
2232 unsigned Elts = CAT->getSize().getZExtValue();
2233 Result = APValue(APValue::UninitArray(),
2234 std::min(S->getLength(), Elts), Elts);
2235 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2236 CharType->isUnsignedIntegerType());
2237 if (Result.hasArrayFiller())
2238 Result.getArrayFiller() = APValue(Value);
2239 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2240 Value = S->getCodeUnit(I);
2241 Result.getArrayInitializedElt(I) = APValue(Value);
2242 }
2243}
2244
2245// Expand an array so that it has more than Index filled elements.
2246static void expandArray(APValue &Array, unsigned Index) {
2247 unsigned Size = Array.getArraySize();
2248 assert(Index < Size);
2249
2250 // Always at least double the number of elements for which we store a value.
2251 unsigned OldElts = Array.getArrayInitializedElts();
2252 unsigned NewElts = std::max(Index+1, OldElts * 2);
2253 NewElts = std::min(Size, std::max(NewElts, 8u));
2254
2255 // Copy the data across.
2256 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2257 for (unsigned I = 0; I != OldElts; ++I)
2258 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2259 for (unsigned I = OldElts; I != NewElts; ++I)
2260 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2261 if (NewValue.hasArrayFiller())
2262 NewValue.getArrayFiller() = Array.getArrayFiller();
2263 Array.swap(NewValue);
2264}
2265
Richard Smithb01fe402014-09-16 01:24:02 +00002266/// Determine whether a type would actually be read by an lvalue-to-rvalue
2267/// conversion. If it's of class type, we may assume that the copy operation
2268/// is trivial. Note that this is never true for a union type with fields
2269/// (because the copy always "reads" the active member) and always true for
2270/// a non-class type.
2271static bool isReadByLvalueToRvalueConversion(QualType T) {
2272 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2273 if (!RD || (RD->isUnion() && !RD->field_empty()))
2274 return true;
2275 if (RD->isEmpty())
2276 return false;
2277
2278 for (auto *Field : RD->fields())
2279 if (isReadByLvalueToRvalueConversion(Field->getType()))
2280 return true;
2281
2282 for (auto &BaseSpec : RD->bases())
2283 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2284 return true;
2285
2286 return false;
2287}
2288
2289/// Diagnose an attempt to read from any unreadable field within the specified
2290/// type, which might be a class type.
2291static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2292 QualType T) {
2293 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2294 if (!RD)
2295 return false;
2296
2297 if (!RD->hasMutableFields())
2298 return false;
2299
2300 for (auto *Field : RD->fields()) {
2301 // If we're actually going to read this field in some way, then it can't
2302 // be mutable. If we're in a union, then assigning to a mutable field
2303 // (even an empty one) can change the active member, so that's not OK.
2304 // FIXME: Add core issue number for the union case.
2305 if (Field->isMutable() &&
2306 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
2307 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
2308 Info.Note(Field->getLocation(), diag::note_declared_at);
2309 return true;
2310 }
2311
2312 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2313 return true;
2314 }
2315
2316 for (auto &BaseSpec : RD->bases())
2317 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2318 return true;
2319
2320 // All mutable fields were empty, and thus not actually read.
2321 return false;
2322}
2323
Richard Smith861b5b52013-05-07 23:34:45 +00002324/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002325enum AccessKinds {
2326 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002327 AK_Assign,
2328 AK_Increment,
2329 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002330};
2331
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002332namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002333/// A handle to a complete object (an object that is not a subobject of
2334/// another object).
2335struct CompleteObject {
2336 /// The value of the complete object.
2337 APValue *Value;
2338 /// The type of the complete object.
2339 QualType Type;
2340
Craig Topper36250ad2014-05-12 05:36:57 +00002341 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002342 CompleteObject(APValue *Value, QualType Type)
2343 : Value(Value), Type(Type) {
2344 assert(Value && "missing value for complete object");
2345 }
2346
Aaron Ballman67347662015-02-15 22:00:28 +00002347 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002348};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002349} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002350
Richard Smith3da88fa2013-04-26 14:36:30 +00002351/// Find the designated sub-object of an rvalue.
2352template<typename SubobjectHandler>
2353typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002354findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002355 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002356 if (Sub.Invalid)
2357 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002358 return handler.failed();
Richard Smitha8105bc2012-01-06 16:39:00 +00002359 if (Sub.isOnePastTheEnd()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002360 if (Info.getLangOpts().CPlusPlus11)
2361 Info.Diag(E, diag::note_constexpr_access_past_end)
2362 << handler.AccessKind;
2363 else
2364 Info.Diag(E);
2365 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002366 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002367
Richard Smith3229b742013-05-05 21:17:10 +00002368 APValue *O = Obj.Value;
2369 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002370 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002371
Richard Smithd62306a2011-11-10 06:34:14 +00002372 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002373 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2374 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002375 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00002376 Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
2377 return handler.failed();
2378 }
2379
Richard Smith49ca8aa2013-08-06 07:09:20 +00002380 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002381 // If we are reading an object of class type, there may still be more
2382 // things we need to check: if there are any mutable subobjects, we
2383 // cannot perform this read. (This only happens when performing a trivial
2384 // copy or assignment.)
2385 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2386 diagnoseUnreadableFields(Info, E, ObjType))
2387 return handler.failed();
2388
Richard Smith49ca8aa2013-08-06 07:09:20 +00002389 if (!handler.found(*O, ObjType))
2390 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002391
Richard Smith49ca8aa2013-08-06 07:09:20 +00002392 // If we modified a bit-field, truncate it to the right width.
2393 if (handler.AccessKind != AK_Read &&
2394 LastField && LastField->isBitField() &&
2395 !truncateBitfieldValue(Info, E, *O, LastField))
2396 return false;
2397
2398 return true;
2399 }
2400
Craig Topper36250ad2014-05-12 05:36:57 +00002401 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002402 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002403 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002404 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002405 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002406 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002407 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002408 // Note, it should not be possible to form a pointer with a valid
2409 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002410 if (Info.getLangOpts().CPlusPlus11)
2411 Info.Diag(E, diag::note_constexpr_access_past_end)
2412 << handler.AccessKind;
2413 else
2414 Info.Diag(E);
2415 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002416 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002417
2418 ObjType = CAT->getElementType();
2419
Richard Smith14a94132012-02-17 03:35:37 +00002420 // An array object is represented as either an Array APValue or as an
2421 // LValue which refers to a string literal.
2422 if (O->isLValue()) {
2423 assert(I == N - 1 && "extracting subobject of character?");
2424 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002425 if (handler.AccessKind != AK_Read)
2426 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2427 *O);
2428 else
2429 return handler.foundString(*O, ObjType, Index);
2430 }
2431
2432 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002433 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002434 else if (handler.AccessKind != AK_Read) {
2435 expandArray(*O, Index);
2436 O = &O->getArrayInitializedElt(Index);
2437 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002438 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002439 } else if (ObjType->isAnyComplexType()) {
2440 // Next subobject is a complex number.
2441 uint64_t Index = Sub.Entries[I].ArrayIndex;
2442 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002443 if (Info.getLangOpts().CPlusPlus11)
2444 Info.Diag(E, diag::note_constexpr_access_past_end)
2445 << handler.AccessKind;
2446 else
2447 Info.Diag(E);
2448 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002449 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002450
2451 bool WasConstQualified = ObjType.isConstQualified();
2452 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2453 if (WasConstQualified)
2454 ObjType.addConst();
2455
Richard Smith66c96992012-02-18 22:04:06 +00002456 assert(I == N - 1 && "extracting subobject of scalar?");
2457 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002458 return handler.found(Index ? O->getComplexIntImag()
2459 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002460 } else {
2461 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002462 return handler.found(Index ? O->getComplexFloatImag()
2463 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002464 }
Richard Smithd62306a2011-11-10 06:34:14 +00002465 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002466 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002467 Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002468 << Field;
2469 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002470 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002471 }
2472
Richard Smithd62306a2011-11-10 06:34:14 +00002473 // Next subobject is a class, struct or union field.
2474 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2475 if (RD->isUnion()) {
2476 const FieldDecl *UnionField = O->getUnionField();
2477 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002478 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002479 Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
2480 << handler.AccessKind << Field << !UnionField << UnionField;
2481 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002482 }
Richard Smithd62306a2011-11-10 06:34:14 +00002483 O = &O->getUnionValue();
2484 } else
2485 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002486
2487 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002488 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002489 if (WasConstQualified && !Field->isMutable())
2490 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002491
2492 if (ObjType.isVolatileQualified()) {
2493 if (Info.getLangOpts().CPlusPlus) {
2494 // FIXME: Include a description of the path to the volatile subobject.
Richard Smith3da88fa2013-04-26 14:36:30 +00002495 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2496 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002497 Info.Note(Field->getLocation(), diag::note_declared_at);
2498 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002499 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002500 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002501 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002502 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002503
2504 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002505 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002506 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002507 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2508 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2509 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002510
2511 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002512 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002513 if (WasConstQualified)
2514 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002515 }
2516 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002517}
2518
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002519namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002520struct ExtractSubobjectHandler {
2521 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002522 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002523
2524 static const AccessKinds AccessKind = AK_Read;
2525
2526 typedef bool result_type;
2527 bool failed() { return false; }
2528 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002529 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002530 return true;
2531 }
2532 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002533 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002534 return true;
2535 }
2536 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002537 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002538 return true;
2539 }
2540 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002541 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002542 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2543 return true;
2544 }
2545};
Richard Smith3229b742013-05-05 21:17:10 +00002546} // end anonymous namespace
2547
Richard Smith3da88fa2013-04-26 14:36:30 +00002548const AccessKinds ExtractSubobjectHandler::AccessKind;
2549
2550/// Extract the designated sub-object of an rvalue.
2551static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002552 const CompleteObject &Obj,
2553 const SubobjectDesignator &Sub,
2554 APValue &Result) {
2555 ExtractSubobjectHandler Handler = { Info, Result };
2556 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002557}
2558
Richard Smith3229b742013-05-05 21:17:10 +00002559namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002560struct ModifySubobjectHandler {
2561 EvalInfo &Info;
2562 APValue &NewVal;
2563 const Expr *E;
2564
2565 typedef bool result_type;
2566 static const AccessKinds AccessKind = AK_Assign;
2567
2568 bool checkConst(QualType QT) {
2569 // Assigning to a const object has undefined behavior.
2570 if (QT.isConstQualified()) {
2571 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2572 return false;
2573 }
2574 return true;
2575 }
2576
2577 bool failed() { return false; }
2578 bool found(APValue &Subobj, QualType SubobjType) {
2579 if (!checkConst(SubobjType))
2580 return false;
2581 // We've been given ownership of NewVal, so just swap it in.
2582 Subobj.swap(NewVal);
2583 return true;
2584 }
2585 bool found(APSInt &Value, QualType SubobjType) {
2586 if (!checkConst(SubobjType))
2587 return false;
2588 if (!NewVal.isInt()) {
2589 // Maybe trying to write a cast pointer value into a complex?
2590 Info.Diag(E);
2591 return false;
2592 }
2593 Value = NewVal.getInt();
2594 return true;
2595 }
2596 bool found(APFloat &Value, QualType SubobjType) {
2597 if (!checkConst(SubobjType))
2598 return false;
2599 Value = NewVal.getFloat();
2600 return true;
2601 }
2602 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2603 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2604 }
2605};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002606} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002607
Richard Smith3229b742013-05-05 21:17:10 +00002608const AccessKinds ModifySubobjectHandler::AccessKind;
2609
Richard Smith3da88fa2013-04-26 14:36:30 +00002610/// Update the designated sub-object of an rvalue to the given value.
2611static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002612 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002613 const SubobjectDesignator &Sub,
2614 APValue &NewVal) {
2615 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002616 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002617}
2618
Richard Smith84f6dcf2012-02-02 01:16:57 +00002619/// Find the position where two subobject designators diverge, or equivalently
2620/// the length of the common initial subsequence.
2621static unsigned FindDesignatorMismatch(QualType ObjType,
2622 const SubobjectDesignator &A,
2623 const SubobjectDesignator &B,
2624 bool &WasArrayIndex) {
2625 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2626 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002627 if (!ObjType.isNull() &&
2628 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002629 // Next subobject is an array element.
2630 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2631 WasArrayIndex = true;
2632 return I;
2633 }
Richard Smith66c96992012-02-18 22:04:06 +00002634 if (ObjType->isAnyComplexType())
2635 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2636 else
2637 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002638 } else {
2639 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2640 WasArrayIndex = false;
2641 return I;
2642 }
2643 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2644 // Next subobject is a field.
2645 ObjType = FD->getType();
2646 else
2647 // Next subobject is a base class.
2648 ObjType = QualType();
2649 }
2650 }
2651 WasArrayIndex = false;
2652 return I;
2653}
2654
2655/// Determine whether the given subobject designators refer to elements of the
2656/// same array object.
2657static bool AreElementsOfSameArray(QualType ObjType,
2658 const SubobjectDesignator &A,
2659 const SubobjectDesignator &B) {
2660 if (A.Entries.size() != B.Entries.size())
2661 return false;
2662
George Burgess IVa51c4072015-10-16 01:49:01 +00002663 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002664 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2665 // A is a subobject of the array element.
2666 return false;
2667
2668 // If A (and B) designates an array element, the last entry will be the array
2669 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2670 // of length 1' case, and the entire path must match.
2671 bool WasArrayIndex;
2672 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2673 return CommonLength >= A.Entries.size() - IsArray;
2674}
2675
Richard Smith3229b742013-05-05 21:17:10 +00002676/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002677static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2678 AccessKinds AK, const LValue &LVal,
2679 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002680 if (!LVal.Base) {
2681 Info.Diag(E, diag::note_constexpr_access_null) << AK;
2682 return CompleteObject();
2683 }
2684
Craig Topper36250ad2014-05-12 05:36:57 +00002685 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002686 if (LVal.CallIndex) {
2687 Frame = Info.getCallFrame(LVal.CallIndex);
2688 if (!Frame) {
2689 Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
2690 << AK << LVal.Base.is<const ValueDecl*>();
2691 NoteLValueLocation(Info, LVal.Base);
2692 return CompleteObject();
2693 }
Richard Smith3229b742013-05-05 21:17:10 +00002694 }
2695
2696 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
2697 // is not a constant expression (even if the object is non-volatile). We also
2698 // apply this rule to C++98, in order to conform to the expected 'volatile'
2699 // semantics.
2700 if (LValType.isVolatileQualified()) {
2701 if (Info.getLangOpts().CPlusPlus)
2702 Info.Diag(E, diag::note_constexpr_access_volatile_type)
2703 << AK << LValType;
2704 else
2705 Info.Diag(E);
2706 return CompleteObject();
2707 }
2708
2709 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00002710 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00002711 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00002712
2713 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
2714 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
2715 // In C++11, constexpr, non-volatile variables initialized with constant
2716 // expressions are constant expressions too. Inside constexpr functions,
2717 // parameters are constant expressions even if they're non-const.
2718 // In C++1y, objects local to a constant expression (those with a Frame) are
2719 // both readable and writable inside constant expressions.
2720 // In C, such things can also be folded, although they are not ICEs.
2721 const VarDecl *VD = dyn_cast<VarDecl>(D);
2722 if (VD) {
2723 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
2724 VD = VDef;
2725 }
2726 if (!VD || VD->isInvalidDecl()) {
2727 Info.Diag(E);
2728 return CompleteObject();
2729 }
2730
2731 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00002732 if (BaseType.isVolatileQualified()) {
2733 if (Info.getLangOpts().CPlusPlus) {
2734 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2735 << AK << 1 << VD;
2736 Info.Note(VD->getLocation(), diag::note_declared_at);
2737 } else {
2738 Info.Diag(E);
2739 }
2740 return CompleteObject();
2741 }
2742
2743 // Unless we're looking at a local variable or argument in a constexpr call,
2744 // the variable we're reading must be const.
2745 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002746 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00002747 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
2748 // OK, we can read and modify an object if we're in the process of
2749 // evaluating its initializer, because its lifetime began in this
2750 // evaluation.
2751 } else if (AK != AK_Read) {
2752 // All the remaining cases only permit reading.
2753 Info.Diag(E, diag::note_constexpr_modify_global);
2754 return CompleteObject();
2755 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00002756 // OK, we can read this variable.
2757 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00002758 // In OpenCL if a variable is in constant address space it is a const value.
2759 if (!(BaseType.isConstQualified() ||
2760 (Info.getLangOpts().OpenCL &&
2761 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00002762 if (Info.getLangOpts().CPlusPlus) {
2763 Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
2764 Info.Note(VD->getLocation(), diag::note_declared_at);
2765 } else {
2766 Info.Diag(E);
2767 }
2768 return CompleteObject();
2769 }
2770 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
2771 // We support folding of const floating-point types, in order to make
2772 // static const data members of such types (supported as an extension)
2773 // more useful.
2774 if (Info.getLangOpts().CPlusPlus11) {
2775 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2776 Info.Note(VD->getLocation(), diag::note_declared_at);
2777 } else {
2778 Info.CCEDiag(E);
2779 }
2780 } else {
2781 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00002782 if (Info.checkingPotentialConstantExpression() &&
2783 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
2784 // The definition of this variable could be constexpr. We can't
2785 // access it right now, but may be able to in future.
2786 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smith3229b742013-05-05 21:17:10 +00002787 Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
2788 Info.Note(VD->getLocation(), diag::note_declared_at);
2789 } else {
2790 Info.Diag(E);
2791 }
2792 return CompleteObject();
2793 }
2794 }
2795
2796 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
2797 return CompleteObject();
2798 } else {
2799 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
2800
2801 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00002802 if (const MaterializeTemporaryExpr *MTE =
2803 dyn_cast<MaterializeTemporaryExpr>(Base)) {
2804 assert(MTE->getStorageDuration() == SD_Static &&
2805 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00002806
Richard Smithe6c01442013-06-05 00:46:14 +00002807 // Per C++1y [expr.const]p2:
2808 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
2809 // - a [...] glvalue of integral or enumeration type that refers to
2810 // a non-volatile const object [...]
2811 // [...]
2812 // - a [...] glvalue of literal type that refers to a non-volatile
2813 // object whose lifetime began within the evaluation of e.
2814 //
2815 // C++11 misses the 'began within the evaluation of e' check and
2816 // instead allows all temporaries, including things like:
2817 // int &&r = 1;
2818 // int x = ++r;
2819 // constexpr int k = r;
2820 // Therefore we use the C++1y rules in C++11 too.
2821 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
2822 const ValueDecl *ED = MTE->getExtendingDecl();
2823 if (!(BaseType.isConstQualified() &&
2824 BaseType->isIntegralOrEnumerationType()) &&
2825 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
2826 Info.Diag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
2827 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
2828 return CompleteObject();
2829 }
2830
2831 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
2832 assert(BaseVal && "got reference to unevaluated temporary");
2833 } else {
2834 Info.Diag(E);
2835 return CompleteObject();
2836 }
2837 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002838 BaseVal = Frame->getTemporary(Base);
2839 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00002840 }
Richard Smith3229b742013-05-05 21:17:10 +00002841
2842 // Volatile temporary objects cannot be accessed in constant expressions.
2843 if (BaseType.isVolatileQualified()) {
2844 if (Info.getLangOpts().CPlusPlus) {
2845 Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
2846 << AK << 0;
2847 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
2848 } else {
2849 Info.Diag(E);
2850 }
2851 return CompleteObject();
2852 }
2853 }
2854
Richard Smith7525ff62013-05-09 07:14:00 +00002855 // During the construction of an object, it is not yet 'const'.
2856 // FIXME: We don't set up EvaluatingDecl for local variables or temporaries,
2857 // and this doesn't do quite the right thing for const subobjects of the
2858 // object under construction.
2859 if (LVal.getLValueBase() == Info.EvaluatingDecl) {
2860 BaseType = Info.Ctx.getCanonicalType(BaseType);
2861 BaseType.removeLocalConst();
2862 }
2863
Richard Smith6d4c6582013-11-05 22:18:15 +00002864 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00002865 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00002866 //
2867 // FIXME: Not all local state is mutable. Allow local constant subobjects
2868 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00002869 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
2870 Info.EvalStatus.HasSideEffects) ||
2871 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00002872 return CompleteObject();
2873
2874 return CompleteObject(BaseVal, BaseType);
2875}
2876
Richard Smith243ef902013-05-05 23:31:59 +00002877/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
2878/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
2879/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00002880///
2881/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002882/// \param Conv - The expression for which we are performing the conversion.
2883/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002884/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
2885/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00002886/// \param LVal - The glvalue on which we are attempting to perform this action.
2887/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00002888static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00002889 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00002890 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002891 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00002892 return false;
2893
Richard Smith3229b742013-05-05 21:17:10 +00002894 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00002895 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00002896 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00002897 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
2898 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
2899 // initializer until now for such expressions. Such an expression can't be
2900 // an ICE in C, so this only matters for fold.
2901 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
2902 if (Type.isVolatileQualified()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002903 Info.Diag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00002904 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002905 }
Richard Smith3229b742013-05-05 21:17:10 +00002906 APValue Lit;
2907 if (!Evaluate(Lit, Info, CLE->getInitializer()))
2908 return false;
2909 CompleteObject LitObj(&Lit, Base->getType());
2910 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00002911 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00002912 // We represent a string literal array as an lvalue pointing at the
2913 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00002914 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00002915 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
2916 CompleteObject StrObj(&Str, Base->getType());
2917 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00002918 }
Richard Smith11562c52011-10-28 17:51:58 +00002919 }
2920
Richard Smith3229b742013-05-05 21:17:10 +00002921 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
2922 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00002923}
2924
2925/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00002926static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00002927 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002928 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00002929 return false;
2930
Aaron Ballmandd69ef32014-08-19 15:55:55 +00002931 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith3229b742013-05-05 21:17:10 +00002932 Info.Diag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002933 return false;
2934 }
2935
Richard Smith3229b742013-05-05 21:17:10 +00002936 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
2937 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00002938}
2939
Richard Smith243ef902013-05-05 23:31:59 +00002940static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
2941 return T->isSignedIntegerType() &&
2942 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
2943}
2944
2945namespace {
Richard Smith43e77732013-05-07 04:50:00 +00002946struct CompoundAssignSubobjectHandler {
2947 EvalInfo &Info;
2948 const Expr *E;
2949 QualType PromotedLHSType;
2950 BinaryOperatorKind Opcode;
2951 const APValue &RHS;
2952
2953 static const AccessKinds AccessKind = AK_Assign;
2954
2955 typedef bool result_type;
2956
2957 bool checkConst(QualType QT) {
2958 // Assigning to a const object has undefined behavior.
2959 if (QT.isConstQualified()) {
2960 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
2961 return false;
2962 }
2963 return true;
2964 }
2965
2966 bool failed() { return false; }
2967 bool found(APValue &Subobj, QualType SubobjType) {
2968 switch (Subobj.getKind()) {
2969 case APValue::Int:
2970 return found(Subobj.getInt(), SubobjType);
2971 case APValue::Float:
2972 return found(Subobj.getFloat(), SubobjType);
2973 case APValue::ComplexInt:
2974 case APValue::ComplexFloat:
2975 // FIXME: Implement complex compound assignment.
2976 Info.Diag(E);
2977 return false;
2978 case APValue::LValue:
2979 return foundPointer(Subobj, SubobjType);
2980 default:
2981 // FIXME: can this happen?
2982 Info.Diag(E);
2983 return false;
2984 }
2985 }
2986 bool found(APSInt &Value, QualType SubobjType) {
2987 if (!checkConst(SubobjType))
2988 return false;
2989
2990 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
2991 // We don't support compound assignment on integer-cast-to-pointer
2992 // values.
2993 Info.Diag(E);
2994 return false;
2995 }
2996
2997 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
2998 SubobjType, Value);
2999 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3000 return false;
3001 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3002 return true;
3003 }
3004 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003005 return checkConst(SubobjType) &&
3006 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3007 Value) &&
3008 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3009 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003010 }
3011 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3012 if (!checkConst(SubobjType))
3013 return false;
3014
3015 QualType PointeeType;
3016 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3017 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003018
3019 if (PointeeType.isNull() || !RHS.isInt() ||
3020 (Opcode != BO_Add && Opcode != BO_Sub)) {
Richard Smith43e77732013-05-07 04:50:00 +00003021 Info.Diag(E);
3022 return false;
3023 }
3024
Richard Smith861b5b52013-05-07 23:34:45 +00003025 int64_t Offset = getExtValue(RHS.getInt());
3026 if (Opcode == BO_Sub)
3027 Offset = -Offset;
3028
3029 LValue LVal;
3030 LVal.setFrom(Info.Ctx, Subobj);
3031 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3032 return false;
3033 LVal.moveInto(Subobj);
3034 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003035 }
3036 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3037 llvm_unreachable("shouldn't encounter string elements here");
3038 }
3039};
3040} // end anonymous namespace
3041
3042const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3043
3044/// Perform a compound assignment of LVal <op>= RVal.
3045static bool handleCompoundAssignment(
3046 EvalInfo &Info, const Expr *E,
3047 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3048 BinaryOperatorKind Opcode, const APValue &RVal) {
3049 if (LVal.Designator.Invalid)
3050 return false;
3051
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003052 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith43e77732013-05-07 04:50:00 +00003053 Info.Diag(E);
3054 return false;
3055 }
3056
3057 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3058 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3059 RVal };
3060 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3061}
3062
3063namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003064struct IncDecSubobjectHandler {
3065 EvalInfo &Info;
3066 const Expr *E;
3067 AccessKinds AccessKind;
3068 APValue *Old;
3069
3070 typedef bool result_type;
3071
3072 bool checkConst(QualType QT) {
3073 // Assigning to a const object has undefined behavior.
3074 if (QT.isConstQualified()) {
3075 Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
3076 return false;
3077 }
3078 return true;
3079 }
3080
3081 bool failed() { return false; }
3082 bool found(APValue &Subobj, QualType SubobjType) {
3083 // Stash the old value. Also clear Old, so we don't clobber it later
3084 // if we're post-incrementing a complex.
3085 if (Old) {
3086 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003087 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003088 }
3089
3090 switch (Subobj.getKind()) {
3091 case APValue::Int:
3092 return found(Subobj.getInt(), SubobjType);
3093 case APValue::Float:
3094 return found(Subobj.getFloat(), SubobjType);
3095 case APValue::ComplexInt:
3096 return found(Subobj.getComplexIntReal(),
3097 SubobjType->castAs<ComplexType>()->getElementType()
3098 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3099 case APValue::ComplexFloat:
3100 return found(Subobj.getComplexFloatReal(),
3101 SubobjType->castAs<ComplexType>()->getElementType()
3102 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3103 case APValue::LValue:
3104 return foundPointer(Subobj, SubobjType);
3105 default:
3106 // FIXME: can this happen?
3107 Info.Diag(E);
3108 return false;
3109 }
3110 }
3111 bool found(APSInt &Value, QualType SubobjType) {
3112 if (!checkConst(SubobjType))
3113 return false;
3114
3115 if (!SubobjType->isIntegerType()) {
3116 // We don't support increment / decrement on integer-cast-to-pointer
3117 // values.
3118 Info.Diag(E);
3119 return false;
3120 }
3121
3122 if (Old) *Old = APValue(Value);
3123
3124 // bool arithmetic promotes to int, and the conversion back to bool
3125 // doesn't reduce mod 2^n, so special-case it.
3126 if (SubobjType->isBooleanType()) {
3127 if (AccessKind == AK_Increment)
3128 Value = 1;
3129 else
3130 Value = !Value;
3131 return true;
3132 }
3133
3134 bool WasNegative = Value.isNegative();
3135 if (AccessKind == AK_Increment) {
3136 ++Value;
3137
3138 if (!WasNegative && Value.isNegative() &&
3139 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3140 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003141 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003142 }
3143 } else {
3144 --Value;
3145
3146 if (WasNegative && !Value.isNegative() &&
3147 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3148 unsigned BitWidth = Value.getBitWidth();
3149 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3150 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003151 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003152 }
3153 }
3154 return true;
3155 }
3156 bool found(APFloat &Value, QualType SubobjType) {
3157 if (!checkConst(SubobjType))
3158 return false;
3159
3160 if (Old) *Old = APValue(Value);
3161
3162 APFloat One(Value.getSemantics(), 1);
3163 if (AccessKind == AK_Increment)
3164 Value.add(One, APFloat::rmNearestTiesToEven);
3165 else
3166 Value.subtract(One, APFloat::rmNearestTiesToEven);
3167 return true;
3168 }
3169 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3170 if (!checkConst(SubobjType))
3171 return false;
3172
3173 QualType PointeeType;
3174 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3175 PointeeType = PT->getPointeeType();
3176 else {
3177 Info.Diag(E);
3178 return false;
3179 }
3180
3181 LValue LVal;
3182 LVal.setFrom(Info.Ctx, Subobj);
3183 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3184 AccessKind == AK_Increment ? 1 : -1))
3185 return false;
3186 LVal.moveInto(Subobj);
3187 return true;
3188 }
3189 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3190 llvm_unreachable("shouldn't encounter string elements here");
3191 }
3192};
3193} // end anonymous namespace
3194
3195/// Perform an increment or decrement on LVal.
3196static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3197 QualType LValType, bool IsIncrement, APValue *Old) {
3198 if (LVal.Designator.Invalid)
3199 return false;
3200
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003201 if (!Info.getLangOpts().CPlusPlus14) {
Richard Smith243ef902013-05-05 23:31:59 +00003202 Info.Diag(E);
3203 return false;
3204 }
3205
3206 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3207 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3208 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3209 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3210}
3211
Richard Smithe97cbd72011-11-11 04:05:33 +00003212/// Build an lvalue for the object argument of a member function call.
3213static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3214 LValue &This) {
3215 if (Object->getType()->isPointerType())
3216 return EvaluatePointer(Object, This, Info);
3217
3218 if (Object->isGLValue())
3219 return EvaluateLValue(Object, This, Info);
3220
Richard Smithd9f663b2013-04-22 15:31:51 +00003221 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003222 return EvaluateTemporary(Object, This, Info);
3223
Richard Smith3e79a572014-06-11 19:53:12 +00003224 Info.Diag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003225 return false;
3226}
3227
3228/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3229/// lvalue referring to the result.
3230///
3231/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003232/// \param LV - An lvalue referring to the base of the member pointer.
3233/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003234/// \param IncludeMember - Specifies whether the member itself is included in
3235/// the resulting LValue subobject designator. This is not possible when
3236/// creating a bound member function.
3237/// \return The field or method declaration to which the member pointer refers,
3238/// or 0 if evaluation fails.
3239static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003240 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003241 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003242 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003243 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003244 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003245 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003246 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003247
3248 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3249 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003250 if (!MemPtr.getDecl()) {
3251 // FIXME: Specific diagnostic.
3252 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003253 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003254 }
Richard Smith253c2a32012-01-27 01:14:48 +00003255
Richard Smith027bf112011-11-17 22:56:20 +00003256 if (MemPtr.isDerivedMember()) {
3257 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003258 // The end of the derived-to-base path for the base object must match the
3259 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003260 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003261 LV.Designator.Entries.size()) {
3262 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003263 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003264 }
Richard Smith027bf112011-11-17 22:56:20 +00003265 unsigned PathLengthToMember =
3266 LV.Designator.Entries.size() - MemPtr.Path.size();
3267 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3268 const CXXRecordDecl *LVDecl = getAsBaseClass(
3269 LV.Designator.Entries[PathLengthToMember + I]);
3270 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003271 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
3272 Info.Diag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003273 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003274 }
Richard Smith027bf112011-11-17 22:56:20 +00003275 }
3276
3277 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003278 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003279 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003280 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003281 } else if (!MemPtr.Path.empty()) {
3282 // Extend the LValue path with the member pointer's path.
3283 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3284 MemPtr.Path.size() + IncludeMember);
3285
3286 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003287 if (const PointerType *PT = LVType->getAs<PointerType>())
3288 LVType = PT->getPointeeType();
3289 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3290 assert(RD && "member pointer access on non-class-type expression");
3291 // The first class in the path is that of the lvalue.
3292 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3293 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003294 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003295 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003296 RD = Base;
3297 }
3298 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003299 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3300 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003301 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003302 }
3303
3304 // Add the member. Note that we cannot build bound member functions here.
3305 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003306 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003307 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003308 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003309 } else if (const IndirectFieldDecl *IFD =
3310 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003311 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003312 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003313 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003314 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003315 }
Richard Smith027bf112011-11-17 22:56:20 +00003316 }
3317
3318 return MemPtr.getDecl();
3319}
3320
Richard Smith84401042013-06-03 05:03:02 +00003321static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3322 const BinaryOperator *BO,
3323 LValue &LV,
3324 bool IncludeMember = true) {
3325 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3326
3327 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003328 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003329 MemberPtr MemPtr;
3330 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3331 }
Craig Topper36250ad2014-05-12 05:36:57 +00003332 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003333 }
3334
3335 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3336 BO->getRHS(), IncludeMember);
3337}
3338
Richard Smith027bf112011-11-17 22:56:20 +00003339/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3340/// the provided lvalue, which currently refers to the base object.
3341static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3342 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003343 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003344 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003345 return false;
3346
Richard Smitha8105bc2012-01-06 16:39:00 +00003347 QualType TargetQT = E->getType();
3348 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3349 TargetQT = PT->getPointeeType();
3350
3351 // Check this cast lands within the final derived-to-base subobject path.
3352 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003353 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003354 << D.MostDerivedType << TargetQT;
3355 return false;
3356 }
3357
Richard Smith027bf112011-11-17 22:56:20 +00003358 // Check the type of the final cast. We don't need to check the path,
3359 // since a cast can only be formed if the path is unique.
3360 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003361 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3362 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003363 if (NewEntriesSize == D.MostDerivedPathLength)
3364 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3365 else
Richard Smith027bf112011-11-17 22:56:20 +00003366 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003367 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003368 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003369 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003370 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003371 }
Richard Smith027bf112011-11-17 22:56:20 +00003372
3373 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003374 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003375}
3376
Mike Stump876387b2009-10-27 22:09:17 +00003377namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003378enum EvalStmtResult {
3379 /// Evaluation failed.
3380 ESR_Failed,
3381 /// Hit a 'return' statement.
3382 ESR_Returned,
3383 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003384 ESR_Succeeded,
3385 /// Hit a 'continue' statement.
3386 ESR_Continue,
3387 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003388 ESR_Break,
3389 /// Still scanning for 'case' or 'default' statement.
3390 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003391};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003392}
Richard Smith254a73d2011-10-28 22:34:42 +00003393
Richard Smithd9f663b2013-04-22 15:31:51 +00003394static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3395 if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
3396 // We don't need to evaluate the initializer for a static local.
3397 if (!VD->hasLocalStorage())
3398 return true;
3399
3400 LValue Result;
3401 Result.set(VD, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003402 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003403
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003404 const Expr *InitE = VD->getInit();
3405 if (!InitE) {
Richard Smith51f03172013-06-20 03:00:05 +00003406 Info.Diag(D->getLocStart(), diag::note_constexpr_uninitialized)
3407 << false << VD->getType();
3408 Val = APValue();
3409 return false;
3410 }
3411
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003412 if (InitE->isValueDependent())
3413 return false;
3414
3415 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003416 // Wipe out any partially-computed value, to allow tracking that this
3417 // evaluation failed.
3418 Val = APValue();
3419 return false;
3420 }
3421 }
3422
3423 return true;
3424}
3425
Richard Smith4e18ca52013-05-06 05:56:11 +00003426/// Evaluate a condition (either a variable declaration or an expression).
3427static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3428 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003429 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003430 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3431 return false;
3432 return EvaluateAsBooleanCondition(Cond, Result, Info);
3433}
3434
Richard Smith89210072016-04-04 23:29:43 +00003435namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003436/// \brief A location where the result (returned value) of evaluating a
3437/// statement should be stored.
3438struct StmtResult {
3439 /// The APValue that should be filled in with the returned value.
3440 APValue &Value;
3441 /// The location containing the result, if any (used to support RVO).
3442 const LValue *Slot;
3443};
Richard Smith89210072016-04-04 23:29:43 +00003444}
Richard Smith52a980a2015-08-28 02:43:42 +00003445
3446static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003447 const Stmt *S,
3448 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003449
3450/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003451static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003452 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003453 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003454 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003455 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003456 case ESR_Break:
3457 return ESR_Succeeded;
3458 case ESR_Succeeded:
3459 case ESR_Continue:
3460 return ESR_Continue;
3461 case ESR_Failed:
3462 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003463 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003464 return ESR;
3465 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003466 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003467}
3468
Richard Smith496ddcf2013-05-12 17:32:42 +00003469/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003470static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003471 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003472 BlockScopeRAII Scope(Info);
3473
Richard Smith496ddcf2013-05-12 17:32:42 +00003474 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003475 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003476 {
3477 FullExpressionRAII Scope(Info);
3478 if (SS->getConditionVariable() &&
3479 !EvaluateDecl(Info, SS->getConditionVariable()))
3480 return ESR_Failed;
3481 if (!EvaluateInteger(SS->getCond(), Value, Info))
3482 return ESR_Failed;
3483 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003484
3485 // Find the switch case corresponding to the value of the condition.
3486 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003487 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003488 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3489 SC = SC->getNextSwitchCase()) {
3490 if (isa<DefaultStmt>(SC)) {
3491 Found = SC;
3492 continue;
3493 }
3494
3495 const CaseStmt *CS = cast<CaseStmt>(SC);
3496 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3497 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3498 : LHS;
3499 if (LHS <= Value && Value <= RHS) {
3500 Found = SC;
3501 break;
3502 }
3503 }
3504
3505 if (!Found)
3506 return ESR_Succeeded;
3507
3508 // Search the switch body for the switch case and evaluate it from there.
3509 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3510 case ESR_Break:
3511 return ESR_Succeeded;
3512 case ESR_Succeeded:
3513 case ESR_Continue:
3514 case ESR_Failed:
3515 case ESR_Returned:
3516 return ESR;
3517 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003518 // This can only happen if the switch case is nested within a statement
3519 // expression. We have no intention of supporting that.
3520 Info.Diag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
3521 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003522 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003523 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003524}
3525
Richard Smith254a73d2011-10-28 22:34:42 +00003526// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003527static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003528 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003529 if (!Info.nextStep(S))
3530 return ESR_Failed;
3531
Richard Smith496ddcf2013-05-12 17:32:42 +00003532 // If we're hunting down a 'case' or 'default' label, recurse through
3533 // substatements until we hit the label.
3534 if (Case) {
3535 // FIXME: We don't start the lifetime of objects whose initialization we
3536 // jump over. However, such objects must be of class type with a trivial
3537 // default constructor that initialize all subobjects, so must be empty,
3538 // so this almost never matters.
3539 switch (S->getStmtClass()) {
3540 case Stmt::CompoundStmtClass:
3541 // FIXME: Precompute which substatement of a compound statement we
3542 // would jump to, and go straight there rather than performing a
3543 // linear scan each time.
3544 case Stmt::LabelStmtClass:
3545 case Stmt::AttributedStmtClass:
3546 case Stmt::DoStmtClass:
3547 break;
3548
3549 case Stmt::CaseStmtClass:
3550 case Stmt::DefaultStmtClass:
3551 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003552 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003553 break;
3554
3555 case Stmt::IfStmtClass: {
3556 // FIXME: Precompute which side of an 'if' we would jump to, and go
3557 // straight there rather than scanning both sides.
3558 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003559
3560 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3561 // preceded by our switch label.
3562 BlockScopeRAII Scope(Info);
3563
Richard Smith496ddcf2013-05-12 17:32:42 +00003564 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3565 if (ESR != ESR_CaseNotFound || !IS->getElse())
3566 return ESR;
3567 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3568 }
3569
3570 case Stmt::WhileStmtClass: {
3571 EvalStmtResult ESR =
3572 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3573 if (ESR != ESR_Continue)
3574 return ESR;
3575 break;
3576 }
3577
3578 case Stmt::ForStmtClass: {
3579 const ForStmt *FS = cast<ForStmt>(S);
3580 EvalStmtResult ESR =
3581 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3582 if (ESR != ESR_Continue)
3583 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003584 if (FS->getInc()) {
3585 FullExpressionRAII IncScope(Info);
3586 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3587 return ESR_Failed;
3588 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003589 break;
3590 }
3591
3592 case Stmt::DeclStmtClass:
3593 // FIXME: If the variable has initialization that can't be jumped over,
3594 // bail out of any immediately-surrounding compound-statement too.
3595 default:
3596 return ESR_CaseNotFound;
3597 }
3598 }
3599
Richard Smith254a73d2011-10-28 22:34:42 +00003600 switch (S->getStmtClass()) {
3601 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003602 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003603 // Don't bother evaluating beyond an expression-statement which couldn't
3604 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003605 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003606 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003607 return ESR_Failed;
3608 return ESR_Succeeded;
3609 }
3610
3611 Info.Diag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003612 return ESR_Failed;
3613
3614 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003615 return ESR_Succeeded;
3616
Richard Smithd9f663b2013-04-22 15:31:51 +00003617 case Stmt::DeclStmtClass: {
3618 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003619 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003620 // Each declaration initialization is its own full-expression.
3621 // FIXME: This isn't quite right; if we're performing aggregate
3622 // initialization, each braced subexpression is its own full-expression.
3623 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003624 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003625 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003626 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003627 return ESR_Succeeded;
3628 }
3629
Richard Smith357362d2011-12-13 06:39:58 +00003630 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003631 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003632 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003633 if (RetExpr &&
3634 !(Result.Slot
3635 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3636 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003637 return ESR_Failed;
3638 return ESR_Returned;
3639 }
Richard Smith254a73d2011-10-28 22:34:42 +00003640
3641 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003642 BlockScopeRAII Scope(Info);
3643
Richard Smith254a73d2011-10-28 22:34:42 +00003644 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003645 for (const auto *BI : CS->body()) {
3646 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003647 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003648 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003649 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003650 return ESR;
3651 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003652 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003653 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003654
3655 case Stmt::IfStmtClass: {
3656 const IfStmt *IS = cast<IfStmt>(S);
3657
3658 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003659 BlockScopeRAII Scope(Info);
Richard Smithd9f663b2013-04-22 15:31:51 +00003660 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003661 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003662 return ESR_Failed;
3663
3664 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3665 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3666 if (ESR != ESR_Succeeded)
3667 return ESR;
3668 }
3669 return ESR_Succeeded;
3670 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003671
3672 case Stmt::WhileStmtClass: {
3673 const WhileStmt *WS = cast<WhileStmt>(S);
3674 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003675 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003676 bool Continue;
3677 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
3678 Continue))
3679 return ESR_Failed;
3680 if (!Continue)
3681 break;
3682
3683 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
3684 if (ESR != ESR_Continue)
3685 return ESR;
3686 }
3687 return ESR_Succeeded;
3688 }
3689
3690 case Stmt::DoStmtClass: {
3691 const DoStmt *DS = cast<DoStmt>(S);
3692 bool Continue;
3693 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00003694 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00003695 if (ESR != ESR_Continue)
3696 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00003697 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00003698
Richard Smith08d6a2c2013-07-24 07:11:57 +00003699 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003700 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
3701 return ESR_Failed;
3702 } while (Continue);
3703 return ESR_Succeeded;
3704 }
3705
3706 case Stmt::ForStmtClass: {
3707 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003708 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003709 if (FS->getInit()) {
3710 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
3711 if (ESR != ESR_Succeeded)
3712 return ESR;
3713 }
3714 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003715 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003716 bool Continue = true;
3717 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
3718 FS->getCond(), Continue))
3719 return ESR_Failed;
3720 if (!Continue)
3721 break;
3722
3723 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3724 if (ESR != ESR_Continue)
3725 return ESR;
3726
Richard Smith08d6a2c2013-07-24 07:11:57 +00003727 if (FS->getInc()) {
3728 FullExpressionRAII IncScope(Info);
3729 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3730 return ESR_Failed;
3731 }
Richard Smith4e18ca52013-05-06 05:56:11 +00003732 }
3733 return ESR_Succeeded;
3734 }
3735
Richard Smith896e0d72013-05-06 06:51:17 +00003736 case Stmt::CXXForRangeStmtClass: {
3737 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003738 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003739
3740 // Initialize the __range variable.
3741 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
3742 if (ESR != ESR_Succeeded)
3743 return ESR;
3744
3745 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00003746 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
3747 if (ESR != ESR_Succeeded)
3748 return ESR;
3749 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00003750 if (ESR != ESR_Succeeded)
3751 return ESR;
3752
3753 while (true) {
3754 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003755 {
3756 bool Continue = true;
3757 FullExpressionRAII CondExpr(Info);
3758 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
3759 return ESR_Failed;
3760 if (!Continue)
3761 break;
3762 }
Richard Smith896e0d72013-05-06 06:51:17 +00003763
3764 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003765 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00003766 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
3767 if (ESR != ESR_Succeeded)
3768 return ESR;
3769
3770 // Loop body.
3771 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
3772 if (ESR != ESR_Continue)
3773 return ESR;
3774
3775 // Increment: ++__begin
3776 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3777 return ESR_Failed;
3778 }
3779
3780 return ESR_Succeeded;
3781 }
3782
Richard Smith496ddcf2013-05-12 17:32:42 +00003783 case Stmt::SwitchStmtClass:
3784 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
3785
Richard Smith4e18ca52013-05-06 05:56:11 +00003786 case Stmt::ContinueStmtClass:
3787 return ESR_Continue;
3788
3789 case Stmt::BreakStmtClass:
3790 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00003791
3792 case Stmt::LabelStmtClass:
3793 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
3794
3795 case Stmt::AttributedStmtClass:
3796 // As a general principle, C++11 attributes can be ignored without
3797 // any semantic impact.
3798 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
3799 Case);
3800
3801 case Stmt::CaseStmtClass:
3802 case Stmt::DefaultStmtClass:
3803 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00003804 }
3805}
3806
Richard Smithcc36f692011-12-22 02:22:31 +00003807/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
3808/// default constructor. If so, we'll fold it whether or not it's marked as
3809/// constexpr. If it is marked as constexpr, we will never implicitly define it,
3810/// so we need special handling.
3811static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00003812 const CXXConstructorDecl *CD,
3813 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00003814 if (!CD->isTrivial() || !CD->isDefaultConstructor())
3815 return false;
3816
Richard Smith66e05fe2012-01-18 05:21:49 +00003817 // Value-initialization does not call a trivial default constructor, so such a
3818 // call is a core constant expression whether or not the constructor is
3819 // constexpr.
3820 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003821 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00003822 // FIXME: If DiagDecl is an implicitly-declared special member function,
3823 // we should be much more explicit about why it's not constexpr.
3824 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
3825 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
3826 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00003827 } else {
3828 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
3829 }
3830 }
3831 return true;
3832}
3833
Richard Smith357362d2011-12-13 06:39:58 +00003834/// CheckConstexprFunction - Check that a function can be called in a constant
3835/// expression.
3836static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
3837 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003838 const FunctionDecl *Definition,
3839 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00003840 // Potential constant expressions can contain calls to declared, but not yet
3841 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00003842 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00003843 Declaration->isConstexpr())
3844 return false;
3845
Richard Smith0838f3a2013-05-14 05:18:44 +00003846 // Bail out with no diagnostic if the function declaration itself is invalid.
3847 // We will have produced a relevant diagnostic while parsing it.
3848 if (Declaration->isInvalidDecl())
3849 return false;
3850
Richard Smith357362d2011-12-13 06:39:58 +00003851 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00003852 if (Definition && Definition->isConstexpr() &&
3853 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00003854 return true;
3855
Richard Smith2bf7fdb2013-01-02 11:42:31 +00003856 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00003857 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Richard Smith5179eb72016-06-28 19:03:57 +00003858
3859 // If this function is not constexpr because it is an inherited
3860 // non-constexpr constructor, diagnose that directly.
3861 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
3862 if (CD && CD->isInheritingConstructor()) {
3863 auto *Inherited = CD->getInheritedConstructor().getConstructor();
3864 if (!Inherited->isConstexpr())
3865 DiagDecl = CD = Inherited;
3866 }
3867
3868 // FIXME: If DiagDecl is an implicitly-declared special member function
3869 // or an inheriting constructor, we should be much more explicit about why
3870 // it's not constexpr.
3871 if (CD && CD->isInheritingConstructor())
3872 Info.Diag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
3873 << CD->getInheritedConstructor().getConstructor()->getParent();
3874 else
3875 Info.Diag(CallLoc, diag::note_constexpr_invalid_function, 1)
3876 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00003877 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
3878 } else {
3879 Info.Diag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
3880 }
3881 return false;
3882}
3883
Richard Smithbe6dd812014-11-19 21:27:17 +00003884/// Determine if a class has any fields that might need to be copied by a
3885/// trivial copy or move operation.
3886static bool hasFields(const CXXRecordDecl *RD) {
3887 if (!RD || RD->isEmpty())
3888 return false;
3889 for (auto *FD : RD->fields()) {
3890 if (FD->isUnnamedBitfield())
3891 continue;
3892 return true;
3893 }
3894 for (auto &Base : RD->bases())
3895 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
3896 return true;
3897 return false;
3898}
3899
Richard Smithd62306a2011-11-10 06:34:14 +00003900namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00003901typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00003902}
3903
3904/// EvaluateArgs - Evaluate the arguments to a function call.
3905static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
3906 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00003907 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00003908 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00003909 I != E; ++I) {
3910 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
3911 // If we're checking for a potential constant expression, evaluate all
3912 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00003913 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00003914 return false;
3915 Success = false;
3916 }
3917 }
3918 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00003919}
3920
Richard Smith254a73d2011-10-28 22:34:42 +00003921/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00003922static bool HandleFunctionCall(SourceLocation CallLoc,
3923 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003924 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00003925 EvalInfo &Info, APValue &Result,
3926 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00003927 ArgVector ArgValues(Args.size());
3928 if (!EvaluateArgs(Args, ArgValues, Info))
3929 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00003930
Richard Smith253c2a32012-01-27 01:14:48 +00003931 if (!Info.CheckCallLimit(CallLoc))
3932 return false;
3933
3934 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00003935
3936 // For a trivial copy or move assignment, perform an APValue copy. This is
3937 // essential for unions, where the operations performed by the assignment
3938 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00003939 //
3940 // Skip this for non-union classes with no fields; in that case, the defaulted
3941 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00003942 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00003943 if (MD && MD->isDefaulted() &&
3944 (MD->getParent()->isUnion() ||
3945 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00003946 assert(This &&
3947 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
3948 LValue RHS;
3949 RHS.setFrom(Info.Ctx, ArgValues[0]);
3950 APValue RHSValue;
3951 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
3952 RHS, RHSValue))
3953 return false;
3954 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
3955 RHSValue))
3956 return false;
3957 This->moveInto(Result);
3958 return true;
3959 }
3960
Richard Smith52a980a2015-08-28 02:43:42 +00003961 StmtResult Ret = {Result, ResultSlot};
3962 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00003963 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00003964 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00003965 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003966 Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00003967 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003968 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00003969}
3970
Richard Smithd62306a2011-11-10 06:34:14 +00003971/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00003972static bool HandleConstructorCall(const Expr *E, const LValue &This,
3973 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00003974 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00003975 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00003976 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00003977 if (!Info.CheckCallLimit(CallLoc))
3978 return false;
3979
Richard Smith3607ffe2012-02-13 03:54:03 +00003980 const CXXRecordDecl *RD = Definition->getParent();
3981 if (RD->getNumVBases()) {
3982 Info.Diag(CallLoc, diag::note_constexpr_virtual_base) << RD;
3983 return false;
3984 }
3985
Richard Smith5179eb72016-06-28 19:03:57 +00003986 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00003987
Richard Smith52a980a2015-08-28 02:43:42 +00003988 // FIXME: Creating an APValue just to hold a nonexistent return value is
3989 // wasteful.
3990 APValue RetVal;
3991 StmtResult Ret = {RetVal, nullptr};
3992
Richard Smith5179eb72016-06-28 19:03:57 +00003993 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00003994 if (Definition->isDelegatingConstructor()) {
3995 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00003996 {
3997 FullExpressionRAII InitScope(Info);
3998 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
3999 return false;
4000 }
Richard Smith52a980a2015-08-28 02:43:42 +00004001 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004002 }
4003
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004004 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004005 // essential for unions (or classes with anonymous union members), where the
4006 // operations performed by the constructor cannot be represented by
4007 // ctor-initializers.
4008 //
4009 // Skip this for empty non-union classes; we should not perform an
4010 // lvalue-to-rvalue conversion on them because their copy constructor does not
4011 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004012 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004013 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004014 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004015 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004016 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004017 return handleLValueToRValueConversion(
4018 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4019 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004020 }
4021
4022 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004023 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004024 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004025 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004026
John McCalld7bca762012-05-01 00:38:49 +00004027 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004028 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4029
Richard Smith08d6a2c2013-07-24 07:11:57 +00004030 // A scope for temporaries lifetime-extended by reference members.
4031 BlockScopeRAII LifetimeExtendedScope(Info);
4032
Richard Smith253c2a32012-01-27 01:14:48 +00004033 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004034 unsigned BasesSeen = 0;
4035#ifndef NDEBUG
4036 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4037#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004038 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004039 LValue Subobject = This;
4040 APValue *Value = &Result;
4041
4042 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004043 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004044 if (I->isBaseInitializer()) {
4045 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004046#ifndef NDEBUG
4047 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004048 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004049 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4050 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4051 "base class initializers not in expected order");
4052 ++BaseIt;
4053#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004054 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004055 BaseType->getAsCXXRecordDecl(), &Layout))
4056 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004057 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004058 } else if ((FD = I->getMember())) {
4059 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004060 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004061 if (RD->isUnion()) {
4062 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004063 Value = &Result.getUnionValue();
4064 } else {
4065 Value = &Result.getStructField(FD->getFieldIndex());
4066 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004067 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004068 // Walk the indirect field decl's chain to find the object to initialize,
4069 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004070 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004071 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004072 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4073 // Switch the union field if it differs. This happens if we had
4074 // preceding zero-initialization, and we're now initializing a union
4075 // subobject other than the first.
4076 // FIXME: In this case, the values of the other subobjects are
4077 // specified, since zero-initialization sets all padding bits to zero.
4078 if (Value->isUninit() ||
4079 (Value->isUnion() && Value->getUnionField() != FD)) {
4080 if (CD->isUnion())
4081 *Value = APValue(FD);
4082 else
4083 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004084 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004085 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004086 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004087 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004088 if (CD->isUnion())
4089 Value = &Value->getUnionValue();
4090 else
4091 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004092 }
Richard Smithd62306a2011-11-10 06:34:14 +00004093 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004094 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004095 }
Richard Smith253c2a32012-01-27 01:14:48 +00004096
Richard Smith08d6a2c2013-07-24 07:11:57 +00004097 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004098 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4099 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004100 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004101 // If we're checking for a potential constant expression, evaluate all
4102 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004103 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004104 return false;
4105 Success = false;
4106 }
Richard Smithd62306a2011-11-10 06:34:14 +00004107 }
4108
Richard Smithd9f663b2013-04-22 15:31:51 +00004109 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004110 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004111}
4112
Richard Smith5179eb72016-06-28 19:03:57 +00004113static bool HandleConstructorCall(const Expr *E, const LValue &This,
4114 ArrayRef<const Expr*> Args,
4115 const CXXConstructorDecl *Definition,
4116 EvalInfo &Info, APValue &Result) {
4117 ArgVector ArgValues(Args.size());
4118 if (!EvaluateArgs(Args, ArgValues, Info))
4119 return false;
4120
4121 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4122 Info, Result);
4123}
4124
Eli Friedman9a156e52008-11-12 09:44:48 +00004125//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004126// Generic Evaluation
4127//===----------------------------------------------------------------------===//
4128namespace {
4129
Aaron Ballman68af21c2014-01-03 19:26:43 +00004130template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004131class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004132 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004133private:
Richard Smith52a980a2015-08-28 02:43:42 +00004134 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004135 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004136 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004137 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004138 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004139 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004140 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004141
Richard Smith17100ba2012-02-16 02:46:34 +00004142 // Check whether a conditional operator with a non-constant condition is a
4143 // potential constant expression. If neither arm is a potential constant
4144 // expression, then the conditional operator is not either.
4145 template<typename ConditionalOperator>
4146 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004147 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004148
4149 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004150 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004151 {
Richard Smith17100ba2012-02-16 02:46:34 +00004152 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004153 StmtVisitorTy::Visit(E->getFalseExpr());
4154 if (Diag.empty())
4155 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004156 }
Richard Smith17100ba2012-02-16 02:46:34 +00004157
George Burgess IV8c892b52016-05-25 22:31:54 +00004158 {
4159 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004160 Diag.clear();
4161 StmtVisitorTy::Visit(E->getTrueExpr());
4162 if (Diag.empty())
4163 return;
4164 }
4165
4166 Error(E, diag::note_constexpr_conditional_never_const);
4167 }
4168
4169
4170 template<typename ConditionalOperator>
4171 bool HandleConditionalOperator(const ConditionalOperator *E) {
4172 bool BoolResult;
4173 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
George Burgess IV8c892b52016-05-25 22:31:54 +00004174 if (Info.checkingPotentialConstantExpression() && Info.noteFailure())
Richard Smith17100ba2012-02-16 02:46:34 +00004175 CheckPotentialConstantConditional(E);
4176 return false;
4177 }
4178
4179 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4180 return StmtVisitorTy::Visit(EvalExpr);
4181 }
4182
Peter Collingbournee9200682011-05-13 03:29:01 +00004183protected:
4184 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004185 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004186 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4187
Richard Smith92b1ce02011-12-12 09:28:41 +00004188 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004189 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004190 }
4191
Aaron Ballman68af21c2014-01-03 19:26:43 +00004192 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004193
4194public:
4195 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4196
4197 EvalInfo &getEvalInfo() { return Info; }
4198
Richard Smithf57d8cb2011-12-09 22:58:01 +00004199 /// Report an evaluation error. This should only be called when an error is
4200 /// first discovered. When propagating an error, just return false.
4201 bool Error(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004202 Info.Diag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004203 return false;
4204 }
4205 bool Error(const Expr *E) {
4206 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4207 }
4208
Aaron Ballman68af21c2014-01-03 19:26:43 +00004209 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004210 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004211 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004212 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004213 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004214 }
4215
Aaron Ballman68af21c2014-01-03 19:26:43 +00004216 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004217 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004218 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004219 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004220 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004221 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004222 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004223 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004224 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004225 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004226 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004227 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004228 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004229 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004230 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004231 // The initializer may not have been parsed yet, or might be erroneous.
4232 if (!E->getExpr())
4233 return Error(E);
4234 return StmtVisitorTy::Visit(E->getExpr());
4235 }
Richard Smith5894a912011-12-19 22:12:41 +00004236 // We cannot create any objects for which cleanups are required, so there is
4237 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004238 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004239 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004240
Aaron Ballman68af21c2014-01-03 19:26:43 +00004241 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004242 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4243 return static_cast<Derived*>(this)->VisitCastExpr(E);
4244 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004245 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004246 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4247 return static_cast<Derived*>(this)->VisitCastExpr(E);
4248 }
4249
Aaron Ballman68af21c2014-01-03 19:26:43 +00004250 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004251 switch (E->getOpcode()) {
4252 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004253 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004254
4255 case BO_Comma:
4256 VisitIgnoredValue(E->getLHS());
4257 return StmtVisitorTy::Visit(E->getRHS());
4258
4259 case BO_PtrMemD:
4260 case BO_PtrMemI: {
4261 LValue Obj;
4262 if (!HandleMemberPointerAccess(Info, E, Obj))
4263 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004264 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004265 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004266 return false;
4267 return DerivedSuccess(Result, E);
4268 }
4269 }
4270 }
4271
Aaron Ballman68af21c2014-01-03 19:26:43 +00004272 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004273 // Evaluate and cache the common expression. We treat it as a temporary,
4274 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004275 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004276 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004277 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004278
Richard Smith17100ba2012-02-16 02:46:34 +00004279 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004280 }
4281
Aaron Ballman68af21c2014-01-03 19:26:43 +00004282 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004283 bool IsBcpCall = false;
4284 // If the condition (ignoring parens) is a __builtin_constant_p call,
4285 // the result is a constant expression if it can be folded without
4286 // side-effects. This is an important GNU extension. See GCC PR38377
4287 // for discussion.
4288 if (const CallExpr *CallCE =
4289 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004290 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004291 IsBcpCall = true;
4292
4293 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4294 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004295 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004296 return false;
4297
Richard Smith6d4c6582013-11-05 22:18:15 +00004298 FoldConstant Fold(Info, IsBcpCall);
4299 if (!HandleConditionalOperator(E)) {
4300 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004301 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004302 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004303
4304 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004305 }
4306
Aaron Ballman68af21c2014-01-03 19:26:43 +00004307 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004308 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4309 return DerivedSuccess(*Value, E);
4310
4311 const Expr *Source = E->getSourceExpr();
4312 if (!Source)
4313 return Error(E);
4314 if (Source == E) { // sanity checking.
4315 assert(0 && "OpaqueValueExpr recursively refers to itself");
4316 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004317 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004318 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004319 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004320
Aaron Ballman68af21c2014-01-03 19:26:43 +00004321 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004322 APValue Result;
4323 if (!handleCallExpr(E, Result, nullptr))
4324 return false;
4325 return DerivedSuccess(Result, E);
4326 }
4327
4328 bool handleCallExpr(const CallExpr *E, APValue &Result,
4329 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004330 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004331 QualType CalleeType = Callee->getType();
4332
Craig Topper36250ad2014-05-12 05:36:57 +00004333 const FunctionDecl *FD = nullptr;
4334 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004335 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004336 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004337
Richard Smithe97cbd72011-11-11 04:05:33 +00004338 // Extract function decl and 'this' pointer from the callee.
4339 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004340 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004341 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4342 // Explicit bound member calls, such as x.f() or p->g();
4343 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004344 return false;
4345 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004346 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004347 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004348 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4349 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004350 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4351 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004352 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004353 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004354 return Error(Callee);
4355
4356 FD = dyn_cast<FunctionDecl>(Member);
4357 if (!FD)
4358 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004359 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004360 LValue Call;
4361 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004362 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004363
Richard Smitha8105bc2012-01-06 16:39:00 +00004364 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004365 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004366 FD = dyn_cast_or_null<FunctionDecl>(
4367 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004368 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004369 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004370
4371 // Overloaded operator calls to member functions are represented as normal
4372 // calls with '*this' as the first argument.
4373 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4374 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004375 // FIXME: When selecting an implicit conversion for an overloaded
4376 // operator delete, we sometimes try to evaluate calls to conversion
4377 // operators without a 'this' parameter!
4378 if (Args.empty())
4379 return Error(E);
4380
Richard Smithe97cbd72011-11-11 04:05:33 +00004381 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
4382 return false;
4383 This = &ThisVal;
4384 Args = Args.slice(1);
4385 }
4386
4387 // Don't call function pointers which have been cast to some other type.
4388 if (!Info.Ctx.hasSameType(CalleeType->getPointeeType(), FD->getType()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004389 return Error(E);
Richard Smithe97cbd72011-11-11 04:05:33 +00004390 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004391 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004392
Richard Smith47b34932012-02-01 02:39:43 +00004393 if (This && !This->checkSubobject(Info, E, CSK_This))
4394 return false;
4395
Richard Smith3607ffe2012-02-13 03:54:03 +00004396 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4397 // calls to such functions in constant expressions.
4398 if (This && !HasQualifier &&
4399 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4400 return Error(E, diag::note_constexpr_virtual_call);
4401
Craig Topper36250ad2014-05-12 05:36:57 +00004402 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004403 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004404
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004405 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
Richard Smith52a980a2015-08-28 02:43:42 +00004406 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
4407 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004408 return false;
4409
Richard Smith52a980a2015-08-28 02:43:42 +00004410 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004411 }
4412
Aaron Ballman68af21c2014-01-03 19:26:43 +00004413 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004414 return StmtVisitorTy::Visit(E->getInitializer());
4415 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004416 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004417 if (E->getNumInits() == 0)
4418 return DerivedZeroInitialization(E);
4419 if (E->getNumInits() == 1)
4420 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004421 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004422 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004423 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004424 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004425 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004426 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004427 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004428 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004429 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004430 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004431 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004432
Richard Smithd62306a2011-11-10 06:34:14 +00004433 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004434 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004435 assert(!E->isArrow() && "missing call to bound member function?");
4436
Richard Smith2e312c82012-03-03 22:46:17 +00004437 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004438 if (!Evaluate(Val, Info, E->getBase()))
4439 return false;
4440
4441 QualType BaseTy = E->getBase()->getType();
4442
4443 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004444 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004445 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004446 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004447 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4448
Richard Smith3229b742013-05-05 21:17:10 +00004449 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004450 SubobjectDesignator Designator(BaseTy);
4451 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004452
Richard Smith3229b742013-05-05 21:17:10 +00004453 APValue Result;
4454 return extractSubobject(Info, E, Obj, Designator, Result) &&
4455 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004456 }
4457
Aaron Ballman68af21c2014-01-03 19:26:43 +00004458 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004459 switch (E->getCastKind()) {
4460 default:
4461 break;
4462
Richard Smitha23ab512013-05-23 00:30:41 +00004463 case CK_AtomicToNonAtomic: {
4464 APValue AtomicVal;
4465 if (!EvaluateAtomic(E->getSubExpr(), AtomicVal, Info))
4466 return false;
4467 return DerivedSuccess(AtomicVal, E);
4468 }
4469
Richard Smith11562c52011-10-28 17:51:58 +00004470 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004471 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004472 return StmtVisitorTy::Visit(E->getSubExpr());
4473
4474 case CK_LValueToRValue: {
4475 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004476 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4477 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004478 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004479 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004480 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004481 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004482 return false;
4483 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004484 }
4485 }
4486
Richard Smithf57d8cb2011-12-09 22:58:01 +00004487 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004488 }
4489
Aaron Ballman68af21c2014-01-03 19:26:43 +00004490 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004491 return VisitUnaryPostIncDec(UO);
4492 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004493 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004494 return VisitUnaryPostIncDec(UO);
4495 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004496 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004497 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004498 return Error(UO);
4499
4500 LValue LVal;
4501 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4502 return false;
4503 APValue RVal;
4504 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4505 UO->isIncrementOp(), &RVal))
4506 return false;
4507 return DerivedSuccess(RVal, UO);
4508 }
4509
Aaron Ballman68af21c2014-01-03 19:26:43 +00004510 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004511 // We will have checked the full-expressions inside the statement expression
4512 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004513 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004514 return Error(E);
4515
Richard Smith08d6a2c2013-07-24 07:11:57 +00004516 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004517 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004518 if (CS->body_empty())
4519 return true;
4520
Richard Smith51f03172013-06-20 03:00:05 +00004521 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4522 BE = CS->body_end();
4523 /**/; ++BI) {
4524 if (BI + 1 == BE) {
4525 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4526 if (!FinalExpr) {
4527 Info.Diag((*BI)->getLocStart(),
4528 diag::note_constexpr_stmt_expr_unsupported);
4529 return false;
4530 }
4531 return this->Visit(FinalExpr);
4532 }
4533
4534 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004535 StmtResult Result = { ReturnValue, nullptr };
4536 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004537 if (ESR != ESR_Succeeded) {
4538 // FIXME: If the statement-expression terminated due to 'return',
4539 // 'break', or 'continue', it would be nice to propagate that to
4540 // the outer statement evaluation rather than bailing out.
4541 if (ESR != ESR_Failed)
4542 Info.Diag((*BI)->getLocStart(),
4543 diag::note_constexpr_stmt_expr_unsupported);
4544 return false;
4545 }
4546 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004547
4548 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004549 }
4550
Richard Smith4a678122011-10-24 18:44:57 +00004551 /// Visit a value which is evaluated, but whose value is ignored.
4552 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004553 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004554 }
David Majnemere9807b22016-02-26 04:23:19 +00004555
4556 /// Potentially visit a MemberExpr's base expression.
4557 void VisitIgnoredBaseExpression(const Expr *E) {
4558 // While MSVC doesn't evaluate the base expression, it does diagnose the
4559 // presence of side-effecting behavior.
4560 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4561 return;
4562 VisitIgnoredValue(E);
4563 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004564};
4565
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004566}
Peter Collingbournee9200682011-05-13 03:29:01 +00004567
4568//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004569// Common base class for lvalue and temporary evaluation.
4570//===----------------------------------------------------------------------===//
4571namespace {
4572template<class Derived>
4573class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004574 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004575protected:
4576 LValue &Result;
4577 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004578 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004579
4580 bool Success(APValue::LValueBase B) {
4581 Result.set(B);
4582 return true;
4583 }
4584
4585public:
4586 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result) :
4587 ExprEvaluatorBaseTy(Info), Result(Result) {}
4588
Richard Smith2e312c82012-03-03 22:46:17 +00004589 bool Success(const APValue &V, const Expr *E) {
4590 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004591 return true;
4592 }
Richard Smith027bf112011-11-17 22:56:20 +00004593
Richard Smith027bf112011-11-17 22:56:20 +00004594 bool VisitMemberExpr(const MemberExpr *E) {
4595 // Handle non-static data members.
4596 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004597 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004598 if (E->isArrow()) {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004599 EvalOK = EvaluatePointer(E->getBase(), Result, this->Info);
Ted Kremenek28831752012-08-23 20:46:57 +00004600 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004601 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004602 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004603 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004604 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004605 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004606 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004607 BaseTy = E->getBase()->getType();
4608 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00004609 if (!EvalOK) {
4610 if (!this->Info.allowInvalidBaseExpr())
4611 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00004612 Result.setInvalid(E);
4613 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004614 }
Richard Smith027bf112011-11-17 22:56:20 +00004615
Richard Smith1b78b3d2012-01-25 22:15:11 +00004616 const ValueDecl *MD = E->getMemberDecl();
4617 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
4618 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
4619 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4620 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00004621 if (!HandleLValueMember(this->Info, E, Result, FD))
4622 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004623 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00004624 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
4625 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004626 } else
4627 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004628
Richard Smith1b78b3d2012-01-25 22:15:11 +00004629 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00004630 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00004631 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00004632 RefValue))
4633 return false;
4634 return Success(RefValue, E);
4635 }
4636 return true;
4637 }
4638
4639 bool VisitBinaryOperator(const BinaryOperator *E) {
4640 switch (E->getOpcode()) {
4641 default:
4642 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
4643
4644 case BO_PtrMemD:
4645 case BO_PtrMemI:
4646 return HandleMemberPointerAccess(this->Info, E, Result);
4647 }
4648 }
4649
4650 bool VisitCastExpr(const CastExpr *E) {
4651 switch (E->getCastKind()) {
4652 default:
4653 return ExprEvaluatorBaseTy::VisitCastExpr(E);
4654
4655 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00004656 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00004657 if (!this->Visit(E->getSubExpr()))
4658 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004659
4660 // Now figure out the necessary offset to add to the base LV to get from
4661 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00004662 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
4663 Result);
Richard Smith027bf112011-11-17 22:56:20 +00004664 }
4665 }
4666};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004667}
Richard Smith027bf112011-11-17 22:56:20 +00004668
4669//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00004670// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00004671//
4672// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
4673// function designators (in C), decl references to void objects (in C), and
4674// temporaries (if building with -Wno-address-of-temporary).
4675//
4676// LValue evaluation produces values comprising a base expression of one of the
4677// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00004678// - Declarations
4679// * VarDecl
4680// * FunctionDecl
4681// - Literals
Richard Smith11562c52011-10-28 17:51:58 +00004682// * CompoundLiteralExpr in C
4683// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00004684// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00004685// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00004686// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00004687// * ObjCEncodeExpr
4688// * AddrLabelExpr
4689// * BlockExpr
4690// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00004691// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00004692// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00004693// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00004694// was evaluated, for cases where the MaterializeTemporaryExpr is missing
4695// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00004696// * A MaterializeTemporaryExpr that has static storage duration, with no
4697// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00004698// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00004699//===----------------------------------------------------------------------===//
4700namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00004701class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00004702 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00004703public:
Richard Smith027bf112011-11-17 22:56:20 +00004704 LValueExprEvaluator(EvalInfo &Info, LValue &Result) :
4705 LValueExprEvaluatorBaseTy(Info, Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00004706
Richard Smith11562c52011-10-28 17:51:58 +00004707 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00004708 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00004709
Peter Collingbournee9200682011-05-13 03:29:01 +00004710 bool VisitDeclRefExpr(const DeclRefExpr *E);
4711 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004712 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004713 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
4714 bool VisitMemberExpr(const MemberExpr *E);
4715 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
4716 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00004717 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00004718 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004719 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
4720 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00004721 bool VisitUnaryReal(const UnaryOperator *E);
4722 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00004723 bool VisitUnaryPreInc(const UnaryOperator *UO) {
4724 return VisitUnaryPreIncDec(UO);
4725 }
4726 bool VisitUnaryPreDec(const UnaryOperator *UO) {
4727 return VisitUnaryPreIncDec(UO);
4728 }
Richard Smith3229b742013-05-05 21:17:10 +00004729 bool VisitBinAssign(const BinaryOperator *BO);
4730 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00004731
Peter Collingbournee9200682011-05-13 03:29:01 +00004732 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00004733 switch (E->getCastKind()) {
4734 default:
Richard Smith027bf112011-11-17 22:56:20 +00004735 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00004736
Eli Friedmance3e02a2011-10-11 00:13:24 +00004737 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00004738 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00004739 if (!Visit(E->getSubExpr()))
4740 return false;
4741 Result.Designator.setInvalid();
4742 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00004743
Richard Smith027bf112011-11-17 22:56:20 +00004744 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00004745 if (!Visit(E->getSubExpr()))
4746 return false;
Richard Smith027bf112011-11-17 22:56:20 +00004747 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00004748 }
4749 }
Eli Friedman9a156e52008-11-12 09:44:48 +00004750};
4751} // end anonymous namespace
4752
Richard Smith11562c52011-10-28 17:51:58 +00004753/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00004754/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00004755/// * function designators in C, and
4756/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00004757/// * @selector() expressions in Objective-C
Richard Smith9f8400e2013-05-01 19:00:39 +00004758static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
4759 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00004760 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
Peter Collingbournee9200682011-05-13 03:29:01 +00004761 return LValueExprEvaluator(Info, Result).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004762}
4763
Peter Collingbournee9200682011-05-13 03:29:01 +00004764bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00004765 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00004766 return Success(FD);
4767 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00004768 return VisitVarDecl(E, VD);
4769 return Error(E);
4770}
Richard Smith733237d2011-10-24 23:14:33 +00004771
Richard Smith11562c52011-10-28 17:51:58 +00004772bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Craig Topper36250ad2014-05-12 05:36:57 +00004773 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00004774 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
4775 Frame = Info.CurrentCall;
4776
Richard Smithfec09922011-11-01 16:57:24 +00004777 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00004778 if (Frame) {
4779 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00004780 return true;
4781 }
Richard Smithce40ad62011-11-12 22:28:03 +00004782 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00004783 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00004784
Richard Smith3229b742013-05-05 21:17:10 +00004785 APValue *V;
4786 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004787 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00004788 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004789 if (!Info.checkingPotentialConstantExpression())
Richard Smith08d6a2c2013-07-24 07:11:57 +00004790 Info.Diag(E, diag::note_constexpr_use_uninit_reference);
4791 return false;
4792 }
Richard Smith3229b742013-05-05 21:17:10 +00004793 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00004794}
4795
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004796bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
4797 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00004798 // Walk through the expression to find the materialized temporary itself.
4799 SmallVector<const Expr *, 2> CommaLHSs;
4800 SmallVector<SubobjectAdjustment, 2> Adjustments;
4801 const Expr *Inner = E->GetTemporaryExpr()->
4802 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00004803
Richard Smith84401042013-06-03 05:03:02 +00004804 // If we passed any comma operators, evaluate their LHSs.
4805 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
4806 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
4807 return false;
4808
Richard Smithe6c01442013-06-05 00:46:14 +00004809 // A materialized temporary with static storage duration can appear within the
4810 // result of a constant expression evaluation, so we need to preserve its
4811 // value for use outside this evaluation.
4812 APValue *Value;
4813 if (E->getStorageDuration() == SD_Static) {
4814 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00004815 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00004816 Result.set(E);
4817 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004818 Value = &Info.CurrentCall->
4819 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00004820 Result.set(E, Info.CurrentCall->Index);
4821 }
4822
Richard Smithea4ad5d2013-06-06 08:19:16 +00004823 QualType Type = Inner->getType();
4824
Richard Smith84401042013-06-03 05:03:02 +00004825 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00004826 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
4827 (E->getStorageDuration() == SD_Static &&
4828 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
4829 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00004830 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00004831 }
Richard Smith84401042013-06-03 05:03:02 +00004832
4833 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00004834 for (unsigned I = Adjustments.size(); I != 0; /**/) {
4835 --I;
4836 switch (Adjustments[I].Kind) {
4837 case SubobjectAdjustment::DerivedToBaseAdjustment:
4838 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
4839 Type, Result))
4840 return false;
4841 Type = Adjustments[I].DerivedToBase.BasePath->getType();
4842 break;
4843
4844 case SubobjectAdjustment::FieldAdjustment:
4845 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
4846 return false;
4847 Type = Adjustments[I].Field->getType();
4848 break;
4849
4850 case SubobjectAdjustment::MemberPointerAdjustment:
4851 if (!HandleMemberPointerAccess(this->Info, Type, Result,
4852 Adjustments[I].Ptr.RHS))
4853 return false;
4854 Type = Adjustments[I].Ptr.MPT->getPointeeType();
4855 break;
4856 }
4857 }
4858
4859 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00004860}
4861
Peter Collingbournee9200682011-05-13 03:29:01 +00004862bool
4863LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004864 assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
4865 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
4866 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00004867 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004868}
4869
Richard Smith6e525142011-12-27 12:18:28 +00004870bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00004871 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00004872 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00004873
4874 Info.Diag(E, diag::note_constexpr_typeid_polymorphic)
4875 << E->getExprOperand()->getType()
4876 << E->getExprOperand()->getSourceRange();
4877 return false;
Richard Smith6e525142011-12-27 12:18:28 +00004878}
4879
Francois Pichet0066db92012-04-16 04:08:35 +00004880bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
4881 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00004882}
Francois Pichet0066db92012-04-16 04:08:35 +00004883
Peter Collingbournee9200682011-05-13 03:29:01 +00004884bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004885 // Handle static data members.
4886 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00004887 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00004888 return VisitVarDecl(E, VD);
4889 }
4890
Richard Smith254a73d2011-10-28 22:34:42 +00004891 // Handle static member functions.
4892 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
4893 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00004894 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00004895 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00004896 }
4897 }
4898
Richard Smithd62306a2011-11-10 06:34:14 +00004899 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00004900 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00004901}
4902
Peter Collingbournee9200682011-05-13 03:29:01 +00004903bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004904 // FIXME: Deal with vectors as array subscript bases.
4905 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004906 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004907
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004908 if (!EvaluatePointer(E->getBase(), Result, Info))
John McCall45d55e42010-05-07 21:00:08 +00004909 return false;
Mike Stump11289f42009-09-09 15:08:12 +00004910
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004911 APSInt Index;
4912 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00004913 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004914
Richard Smith861b5b52013-05-07 23:34:45 +00004915 return HandleLValueArrayAdjustment(Info, E, Result, E->getType(),
4916 getExtValue(Index));
Anders Carlsson9f9e4242008-11-16 19:01:22 +00004917}
Eli Friedman9a156e52008-11-12 09:44:48 +00004918
Peter Collingbournee9200682011-05-13 03:29:01 +00004919bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
John McCall45d55e42010-05-07 21:00:08 +00004920 return EvaluatePointer(E->getSubExpr(), Result, Info);
Eli Friedman0b8337c2009-02-20 01:57:15 +00004921}
4922
Richard Smith66c96992012-02-18 22:04:06 +00004923bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
4924 if (!Visit(E->getSubExpr()))
4925 return false;
4926 // __real is a no-op on scalar lvalues.
4927 if (E->getSubExpr()->getType()->isAnyComplexType())
4928 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
4929 return true;
4930}
4931
4932bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
4933 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
4934 "lvalue __imag__ on scalar?");
4935 if (!Visit(E->getSubExpr()))
4936 return false;
4937 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
4938 return true;
4939}
4940
Richard Smith243ef902013-05-05 23:31:59 +00004941bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004942 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004943 return Error(UO);
4944
4945 if (!this->Visit(UO->getSubExpr()))
4946 return false;
4947
Richard Smith243ef902013-05-05 23:31:59 +00004948 return handleIncDec(
4949 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00004950 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00004951}
4952
4953bool LValueExprEvaluator::VisitCompoundAssignOperator(
4954 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004955 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00004956 return Error(CAO);
4957
Richard Smith3229b742013-05-05 21:17:10 +00004958 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00004959
4960 // The overall lvalue result is the result of evaluating the LHS.
4961 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00004962 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004963 Evaluate(RHS, this->Info, CAO->getRHS());
4964 return false;
4965 }
4966
Richard Smith3229b742013-05-05 21:17:10 +00004967 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
4968 return false;
4969
Richard Smith43e77732013-05-07 04:50:00 +00004970 return handleCompoundAssignment(
4971 this->Info, CAO,
4972 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
4973 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00004974}
4975
4976bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004977 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004978 return Error(E);
4979
Richard Smith3229b742013-05-05 21:17:10 +00004980 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00004981
4982 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00004983 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004984 Evaluate(NewVal, this->Info, E->getRHS());
4985 return false;
4986 }
4987
Richard Smith3229b742013-05-05 21:17:10 +00004988 if (!Evaluate(NewVal, this->Info, E->getRHS()))
4989 return false;
Richard Smith243ef902013-05-05 23:31:59 +00004990
4991 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00004992 NewVal);
4993}
4994
Eli Friedman9a156e52008-11-12 09:44:48 +00004995//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00004996// Pointer Evaluation
4997//===----------------------------------------------------------------------===//
4998
Anders Carlsson0a1707c2008-07-08 05:13:58 +00004999namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005000class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005001 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005002 LValue &Result;
5003
Peter Collingbournee9200682011-05-13 03:29:01 +00005004 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005005 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005006 return true;
5007 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005008public:
Mike Stump11289f42009-09-09 15:08:12 +00005009
John McCall45d55e42010-05-07 21:00:08 +00005010 PointerExprEvaluator(EvalInfo &info, LValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00005011 : ExprEvaluatorBaseTy(info), Result(Result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005012
Richard Smith2e312c82012-03-03 22:46:17 +00005013 bool Success(const APValue &V, const Expr *E) {
5014 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005015 return true;
5016 }
Richard Smithfddd3842011-12-30 21:15:51 +00005017 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005018 return Success((Expr*)nullptr);
Richard Smith4ce706a2011-10-11 21:43:33 +00005019 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005020
John McCall45d55e42010-05-07 21:00:08 +00005021 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005022 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005023 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005024 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005025 { return Success(E); }
Patrick Beard0caa3942012-04-19 00:25:12 +00005026 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005027 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005028 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005029 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005030 bool VisitCallExpr(const CallExpr *E);
5031 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005032 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005033 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005034 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005035 }
Richard Smithd62306a2011-11-10 06:34:14 +00005036 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005037 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005038 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005039 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005040 if (!Info.CurrentCall->This) {
5041 if (Info.getLangOpts().CPlusPlus11)
5042 Info.Diag(E, diag::note_constexpr_this) << E->isImplicit();
5043 else
5044 Info.Diag(E);
5045 return false;
5046 }
Richard Smithd62306a2011-11-10 06:34:14 +00005047 Result = *Info.CurrentCall->This;
5048 return true;
5049 }
John McCallc07a0c72011-02-17 10:25:35 +00005050
Eli Friedman449fe542009-03-23 04:56:01 +00005051 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005052};
Chris Lattner05706e882008-07-11 18:11:29 +00005053} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005054
John McCall45d55e42010-05-07 21:00:08 +00005055static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005056 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
Peter Collingbournee9200682011-05-13 03:29:01 +00005057 return PointerExprEvaluator(Info, Result).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005058}
5059
John McCall45d55e42010-05-07 21:00:08 +00005060bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005061 if (E->getOpcode() != BO_Add &&
5062 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005063 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005064
Chris Lattner05706e882008-07-11 18:11:29 +00005065 const Expr *PExp = E->getLHS();
5066 const Expr *IExp = E->getRHS();
5067 if (IExp->getType()->isPointerType())
5068 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005069
Richard Smith253c2a32012-01-27 01:14:48 +00005070 bool EvalPtrOK = EvaluatePointer(PExp, Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00005071 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005072 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005073
John McCall45d55e42010-05-07 21:00:08 +00005074 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005075 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005076 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005077
5078 int64_t AdditionalOffset = getExtValue(Offset);
Richard Smith96e0c102011-11-04 02:25:55 +00005079 if (E->getOpcode() == BO_Sub)
5080 AdditionalOffset = -AdditionalOffset;
Chris Lattner05706e882008-07-11 18:11:29 +00005081
Ted Kremenek28831752012-08-23 20:46:57 +00005082 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smitha8105bc2012-01-06 16:39:00 +00005083 return HandleLValueArrayAdjustment(Info, E, Result, Pointee,
5084 AdditionalOffset);
Chris Lattner05706e882008-07-11 18:11:29 +00005085}
Eli Friedman9a156e52008-11-12 09:44:48 +00005086
John McCall45d55e42010-05-07 21:00:08 +00005087bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5088 return EvaluateLValue(E->getSubExpr(), Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005089}
Mike Stump11289f42009-09-09 15:08:12 +00005090
Peter Collingbournee9200682011-05-13 03:29:01 +00005091bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5092 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005093
Eli Friedman847a2bc2009-12-27 05:43:15 +00005094 switch (E->getCastKind()) {
5095 default:
5096 break;
5097
John McCalle3027922010-08-25 11:45:40 +00005098 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005099 case CK_CPointerToObjCPointerCast:
5100 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005101 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005102 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005103 if (!Visit(SubExpr))
5104 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005105 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5106 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5107 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005108 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005109 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005110 if (SubExpr->getType()->isVoidPointerType())
5111 CCEDiag(E, diag::note_constexpr_invalid_cast)
5112 << 3 << SubExpr->getType();
5113 else
5114 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5115 }
Richard Smith96e0c102011-11-04 02:25:55 +00005116 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005117
Anders Carlsson18275092010-10-31 20:41:46 +00005118 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005119 case CK_UncheckedDerivedToBase:
Richard Smith0b0a0b62011-10-29 20:57:55 +00005120 if (!EvaluatePointer(E->getSubExpr(), Result, Info))
Anders Carlsson18275092010-10-31 20:41:46 +00005121 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005122 if (!Result.Base && Result.Offset.isZero())
5123 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005124
Richard Smithd62306a2011-11-10 06:34:14 +00005125 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005126 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005127 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5128 castAs<PointerType>()->getPointeeType(),
5129 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005130
Richard Smith027bf112011-11-17 22:56:20 +00005131 case CK_BaseToDerived:
5132 if (!Visit(E->getSubExpr()))
5133 return false;
5134 if (!Result.Base && Result.Offset.isZero())
5135 return true;
5136 return HandleBaseToDerivedCast(Info, E, Result);
5137
Richard Smith0b0a0b62011-10-29 20:57:55 +00005138 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005139 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005140 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005141
John McCalle3027922010-08-25 11:45:40 +00005142 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005143 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5144
Richard Smith2e312c82012-03-03 22:46:17 +00005145 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005146 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005147 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005148
John McCall45d55e42010-05-07 21:00:08 +00005149 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005150 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5151 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005152 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005153 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005154 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005155 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005156 Result.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00005157 return true;
5158 } else {
5159 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005160 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005161 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005162 }
5163 }
John McCalle3027922010-08-25 11:45:40 +00005164 case CK_ArrayToPointerDecay:
Richard Smith027bf112011-11-17 22:56:20 +00005165 if (SubExpr->isGLValue()) {
5166 if (!EvaluateLValue(SubExpr, Result, Info))
5167 return false;
5168 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005169 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005170 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005171 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005172 return false;
5173 }
Richard Smith96e0c102011-11-04 02:25:55 +00005174 // The result is a pointer to the first element of the array.
Richard Smitha8105bc2012-01-06 16:39:00 +00005175 if (const ConstantArrayType *CAT
5176 = Info.Ctx.getAsConstantArrayType(SubExpr->getType()))
5177 Result.addArray(Info, E, CAT);
5178 else
5179 Result.Designator.setInvalid();
Richard Smith96e0c102011-11-04 02:25:55 +00005180 return true;
Richard Smithdd785442011-10-31 20:57:44 +00005181
John McCalle3027922010-08-25 11:45:40 +00005182 case CK_FunctionToPointerDecay:
Richard Smithdd785442011-10-31 20:57:44 +00005183 return EvaluateLValue(SubExpr, Result, Info);
Eli Friedman9a156e52008-11-12 09:44:48 +00005184 }
5185
Richard Smith11562c52011-10-28 17:51:58 +00005186 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005187}
Chris Lattner05706e882008-07-11 18:11:29 +00005188
Hal Finkel0dd05d42014-10-03 17:18:37 +00005189static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5190 // C++ [expr.alignof]p3:
5191 // When alignof is applied to a reference type, the result is the
5192 // alignment of the referenced type.
5193 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5194 T = Ref->getPointeeType();
5195
5196 // __alignof is defined to return the preferred alignment.
5197 return Info.Ctx.toCharUnitsFromBits(
5198 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5199}
5200
5201static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5202 E = E->IgnoreParens();
5203
5204 // The kinds of expressions that we have special-case logic here for
5205 // should be kept up to date with the special checks for those
5206 // expressions in Sema.
5207
5208 // alignof decl is always accepted, even if it doesn't make sense: we default
5209 // to 1 in those cases.
5210 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5211 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5212 /*RefAsPointee*/true);
5213
5214 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5215 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5216 /*RefAsPointee*/true);
5217
5218 return GetAlignOfType(Info, E->getType());
5219}
5220
Peter Collingbournee9200682011-05-13 03:29:01 +00005221bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005222 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005223 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005224
Alp Tokera724cff2013-12-28 21:59:02 +00005225 switch (E->getBuiltinCallee()) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005226 case Builtin::BI__builtin_addressof:
5227 return EvaluateLValue(E->getArg(0), Result, Info);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005228 case Builtin::BI__builtin_assume_aligned: {
5229 // We need to be very careful here because: if the pointer does not have the
5230 // asserted alignment, then the behavior is undefined, and undefined
5231 // behavior is non-constant.
5232 if (!EvaluatePointer(E->getArg(0), Result, Info))
5233 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005234
Hal Finkel0dd05d42014-10-03 17:18:37 +00005235 LValue OffsetResult(Result);
5236 APSInt Alignment;
5237 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5238 return false;
5239 CharUnits Align = CharUnits::fromQuantity(getExtValue(Alignment));
5240
5241 if (E->getNumArgs() > 2) {
5242 APSInt Offset;
5243 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5244 return false;
5245
5246 int64_t AdditionalOffset = -getExtValue(Offset);
5247 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5248 }
5249
5250 // If there is a base object, then it must have the correct alignment.
5251 if (OffsetResult.Base) {
5252 CharUnits BaseAlignment;
5253 if (const ValueDecl *VD =
5254 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5255 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5256 } else {
5257 BaseAlignment =
5258 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5259 }
5260
5261 if (BaseAlignment < Align) {
5262 Result.Designator.setInvalid();
5263 // FIXME: Quantities here cast to integers because the plural modifier
5264 // does not work on APSInts yet.
5265 CCEDiag(E->getArg(0),
5266 diag::note_constexpr_baa_insufficient_alignment) << 0
5267 << (int) BaseAlignment.getQuantity()
5268 << (unsigned) getExtValue(Alignment);
5269 return false;
5270 }
5271 }
5272
5273 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005274 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005275 Result.Designator.setInvalid();
5276 APSInt Offset(64, false);
5277 Offset = OffsetResult.Offset.getQuantity();
5278
5279 if (OffsetResult.Base)
5280 CCEDiag(E->getArg(0),
5281 diag::note_constexpr_baa_insufficient_alignment) << 1
5282 << (int) getExtValue(Offset) << (unsigned) getExtValue(Alignment);
5283 else
5284 CCEDiag(E->getArg(0),
5285 diag::note_constexpr_baa_value_insufficient_alignment)
5286 << Offset << (unsigned) getExtValue(Alignment);
5287
5288 return false;
5289 }
5290
5291 return true;
5292 }
Richard Smith6cbd65d2013-07-11 02:27:57 +00005293 default:
5294 return ExprEvaluatorBaseTy::VisitCallExpr(E);
5295 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005296}
Chris Lattner05706e882008-07-11 18:11:29 +00005297
5298//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005299// Member Pointer Evaluation
5300//===----------------------------------------------------------------------===//
5301
5302namespace {
5303class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005304 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00005305 MemberPtr &Result;
5306
5307 bool Success(const ValueDecl *D) {
5308 Result = MemberPtr(D);
5309 return true;
5310 }
5311public:
5312
5313 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
5314 : ExprEvaluatorBaseTy(Info), Result(Result) {}
5315
Richard Smith2e312c82012-03-03 22:46:17 +00005316 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00005317 Result.setFrom(V);
5318 return true;
5319 }
Richard Smithfddd3842011-12-30 21:15:51 +00005320 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00005321 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00005322 }
5323
5324 bool VisitCastExpr(const CastExpr *E);
5325 bool VisitUnaryAddrOf(const UnaryOperator *E);
5326};
5327} // end anonymous namespace
5328
5329static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
5330 EvalInfo &Info) {
5331 assert(E->isRValue() && E->getType()->isMemberPointerType());
5332 return MemberPointerExprEvaluator(Info, Result).Visit(E);
5333}
5334
5335bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
5336 switch (E->getCastKind()) {
5337 default:
5338 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5339
5340 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005341 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005342 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00005343
5344 case CK_BaseToDerivedMemberPointer: {
5345 if (!Visit(E->getSubExpr()))
5346 return false;
5347 if (E->path_empty())
5348 return true;
5349 // Base-to-derived member pointer casts store the path in derived-to-base
5350 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
5351 // the wrong end of the derived->base arc, so stagger the path by one class.
5352 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
5353 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
5354 PathI != PathE; ++PathI) {
5355 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5356 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
5357 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005358 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005359 }
5360 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
5361 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005362 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005363 return true;
5364 }
5365
5366 case CK_DerivedToBaseMemberPointer:
5367 if (!Visit(E->getSubExpr()))
5368 return false;
5369 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5370 PathE = E->path_end(); PathI != PathE; ++PathI) {
5371 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
5372 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5373 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005374 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005375 }
5376 return true;
5377 }
5378}
5379
5380bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
5381 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5382 // member can be formed.
5383 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
5384}
5385
5386//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00005387// Record Evaluation
5388//===----------------------------------------------------------------------===//
5389
5390namespace {
5391 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005392 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005393 const LValue &This;
5394 APValue &Result;
5395 public:
5396
5397 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
5398 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
5399
Richard Smith2e312c82012-03-03 22:46:17 +00005400 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005401 Result = V;
5402 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00005403 }
Richard Smithb8348f52016-05-12 22:16:28 +00005404 bool ZeroInitialization(const Expr *E) {
5405 return ZeroInitialization(E, E->getType());
5406 }
5407 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00005408
Richard Smith52a980a2015-08-28 02:43:42 +00005409 bool VisitCallExpr(const CallExpr *E) {
5410 return handleCallExpr(E, Result, &This);
5411 }
Richard Smithe97cbd72011-11-11 04:05:33 +00005412 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005413 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005414 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5415 return VisitCXXConstructExpr(E, E->getType());
5416 }
Richard Smith5179eb72016-06-28 19:03:57 +00005417 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00005418 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00005419 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00005420 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005421}
Richard Smithd62306a2011-11-10 06:34:14 +00005422
Richard Smithfddd3842011-12-30 21:15:51 +00005423/// Perform zero-initialization on an object of non-union class type.
5424/// C++11 [dcl.init]p5:
5425/// To zero-initialize an object or reference of type T means:
5426/// [...]
5427/// -- if T is a (possibly cv-qualified) non-union class type,
5428/// each non-static data member and each base-class subobject is
5429/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00005430static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
5431 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00005432 const LValue &This, APValue &Result) {
5433 assert(!RD->isUnion() && "Expected non-union class type");
5434 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
5435 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00005436 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00005437
John McCalld7bca762012-05-01 00:38:49 +00005438 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005439 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5440
5441 if (CD) {
5442 unsigned Index = 0;
5443 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00005444 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00005445 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
5446 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005447 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
5448 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00005449 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00005450 Result.getStructBase(Index)))
5451 return false;
5452 }
5453 }
5454
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005455 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00005456 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00005457 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00005458 continue;
5459
5460 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005461 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005462 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005463
David Blaikie2d7c57e2012-04-30 02:36:29 +00005464 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005465 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00005466 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00005467 return false;
5468 }
5469
5470 return true;
5471}
5472
Richard Smithb8348f52016-05-12 22:16:28 +00005473bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
5474 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005475 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00005476 if (RD->isUnion()) {
5477 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5478 // object's first non-static named data member is zero-initialized
5479 RecordDecl::field_iterator I = RD->field_begin();
5480 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00005481 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00005482 return true;
5483 }
5484
5485 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00005486 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00005487 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00005488 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00005489 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00005490 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00005491 }
5492
Richard Smith5d108602012-02-17 00:44:16 +00005493 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00005494 Info.Diag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00005495 return false;
5496 }
5497
Richard Smitha8105bc2012-01-06 16:39:00 +00005498 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00005499}
5500
Richard Smithe97cbd72011-11-11 04:05:33 +00005501bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
5502 switch (E->getCastKind()) {
5503 default:
5504 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5505
5506 case CK_ConstructorConversion:
5507 return Visit(E->getSubExpr());
5508
5509 case CK_DerivedToBase:
5510 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00005511 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005512 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00005513 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00005514 if (!DerivedObject.isStruct())
5515 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00005516
5517 // Derived-to-base rvalue conversion: just slice off the derived part.
5518 APValue *Value = &DerivedObject;
5519 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
5520 for (CastExpr::path_const_iterator PathI = E->path_begin(),
5521 PathE = E->path_end(); PathI != PathE; ++PathI) {
5522 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
5523 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
5524 Value = &Value->getStructBase(getBaseIndex(RD, Base));
5525 RD = Base;
5526 }
5527 Result = *Value;
5528 return true;
5529 }
5530 }
5531}
5532
Richard Smithd62306a2011-11-10 06:34:14 +00005533bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
5534 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00005535 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005536 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
5537
5538 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00005539 const FieldDecl *Field = E->getInitializedFieldInUnion();
5540 Result = APValue(Field);
5541 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00005542 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00005543
5544 // If the initializer list for a union does not contain any elements, the
5545 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00005546 // FIXME: The element should be initialized from an initializer list.
5547 // Is this difference ever observable for initializer lists which
5548 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00005549 ImplicitValueInitExpr VIE(Field->getType());
5550 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
5551
Richard Smithd62306a2011-11-10 06:34:14 +00005552 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00005553 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
5554 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00005555
5556 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5557 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5558 isa<CXXDefaultInitExpr>(InitExpr));
5559
Richard Smithb228a862012-02-15 02:18:13 +00005560 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00005561 }
5562
Richard Smith872307e2016-03-08 22:17:41 +00005563 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00005564 if (Result.isUninit())
5565 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
5566 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00005567 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00005568 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00005569
5570 // Initialize base classes.
5571 if (CXXRD) {
5572 for (const auto &Base : CXXRD->bases()) {
5573 assert(ElementNo < E->getNumInits() && "missing init for base class");
5574 const Expr *Init = E->getInit(ElementNo);
5575
5576 LValue Subobject = This;
5577 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
5578 return false;
5579
5580 APValue &FieldVal = Result.getStructBase(ElementNo);
5581 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00005582 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00005583 return false;
5584 Success = false;
5585 }
5586 ++ElementNo;
5587 }
5588 }
5589
5590 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005591 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00005592 // Anonymous bit-fields are not considered members of the class for
5593 // purposes of aggregate initialization.
5594 if (Field->isUnnamedBitfield())
5595 continue;
5596
5597 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00005598
Richard Smith253c2a32012-01-27 01:14:48 +00005599 bool HaveInit = ElementNo < E->getNumInits();
5600
5601 // FIXME: Diagnostics here should point to the end of the initializer
5602 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00005603 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005604 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00005605 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005606
5607 // Perform an implicit value-initialization for members beyond the end of
5608 // the initializer list.
5609 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00005610 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00005611
Richard Smith852c9db2013-04-20 22:23:05 +00005612 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
5613 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
5614 isa<CXXDefaultInitExpr>(Init));
5615
Richard Smith49ca8aa2013-08-06 07:09:20 +00005616 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
5617 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
5618 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005619 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00005620 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00005621 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00005622 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00005623 }
5624 }
5625
Richard Smith253c2a32012-01-27 01:14:48 +00005626 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00005627}
5628
Richard Smithb8348f52016-05-12 22:16:28 +00005629bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
5630 QualType T) {
5631 // Note that E's type is not necessarily the type of our class here; we might
5632 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00005633 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00005634 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
5635
Richard Smithfddd3842011-12-30 21:15:51 +00005636 bool ZeroInit = E->requiresZeroInitialization();
5637 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00005638 // If we've already performed zero-initialization, we're already done.
5639 if (!Result.isUninit())
5640 return true;
5641
Richard Smithda3f4fd2014-03-05 23:32:50 +00005642 // We can get here in two different ways:
5643 // 1) We're performing value-initialization, and should zero-initialize
5644 // the object, or
5645 // 2) We're performing default-initialization of an object with a trivial
5646 // constexpr default constructor, in which case we should start the
5647 // lifetimes of all the base subobjects (there can be no data member
5648 // subobjects in this case) per [basic.life]p1.
5649 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00005650 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00005651 }
5652
Craig Topper36250ad2014-05-12 05:36:57 +00005653 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005654 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00005655
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00005656 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00005657 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00005658
Richard Smith1bc5c2c2012-01-10 04:32:03 +00005659 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00005660 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00005661 if (const MaterializeTemporaryExpr *ME
5662 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
5663 return Visit(ME->GetTemporaryExpr());
5664
Richard Smithb8348f52016-05-12 22:16:28 +00005665 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00005666 return false;
5667
Craig Topper5fc8fc22014-08-27 06:28:36 +00005668 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00005669 return HandleConstructorCall(E, This, Args,
5670 cast<CXXConstructorDecl>(Definition), Info,
5671 Result);
5672}
5673
5674bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
5675 const CXXInheritedCtorInitExpr *E) {
5676 if (!Info.CurrentCall) {
5677 assert(Info.checkingPotentialConstantExpression());
5678 return false;
5679 }
5680
5681 const CXXConstructorDecl *FD = E->getConstructor();
5682 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
5683 return false;
5684
5685 const FunctionDecl *Definition = nullptr;
5686 auto Body = FD->getBody(Definition);
5687
5688 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
5689 return false;
5690
5691 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00005692 cast<CXXConstructorDecl>(Definition), Info,
5693 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00005694}
5695
Richard Smithcc1b96d2013-06-12 22:31:48 +00005696bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
5697 const CXXStdInitializerListExpr *E) {
5698 const ConstantArrayType *ArrayType =
5699 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
5700
5701 LValue Array;
5702 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
5703 return false;
5704
5705 // Get a pointer to the first element of the array.
5706 Array.addArray(Info, E, ArrayType);
5707
5708 // FIXME: Perform the checks on the field types in SemaInit.
5709 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
5710 RecordDecl::field_iterator Field = Record->field_begin();
5711 if (Field == Record->field_end())
5712 return Error(E);
5713
5714 // Start pointer.
5715 if (!Field->getType()->isPointerType() ||
5716 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5717 ArrayType->getElementType()))
5718 return Error(E);
5719
5720 // FIXME: What if the initializer_list type has base classes, etc?
5721 Result = APValue(APValue::UninitStruct(), 0, 2);
5722 Array.moveInto(Result.getStructField(0));
5723
5724 if (++Field == Record->field_end())
5725 return Error(E);
5726
5727 if (Field->getType()->isPointerType() &&
5728 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
5729 ArrayType->getElementType())) {
5730 // End pointer.
5731 if (!HandleLValueArrayAdjustment(Info, E, Array,
5732 ArrayType->getElementType(),
5733 ArrayType->getSize().getZExtValue()))
5734 return false;
5735 Array.moveInto(Result.getStructField(1));
5736 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
5737 // Length.
5738 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
5739 else
5740 return Error(E);
5741
5742 if (++Field != Record->field_end())
5743 return Error(E);
5744
5745 return true;
5746}
5747
Richard Smithd62306a2011-11-10 06:34:14 +00005748static bool EvaluateRecord(const Expr *E, const LValue &This,
5749 APValue &Result, EvalInfo &Info) {
5750 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00005751 "can't evaluate expression as a record rvalue");
5752 return RecordExprEvaluator(Info, This, Result).Visit(E);
5753}
5754
5755//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005756// Temporary Evaluation
5757//
5758// Temporaries are represented in the AST as rvalues, but generally behave like
5759// lvalues. The full-object of which the temporary is a subobject is implicitly
5760// materialized so that a reference can bind to it.
5761//===----------------------------------------------------------------------===//
5762namespace {
5763class TemporaryExprEvaluator
5764 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
5765public:
5766 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
5767 LValueExprEvaluatorBaseTy(Info, Result) {}
5768
5769 /// Visit an expression which constructs the value of this temporary.
5770 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00005771 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005772 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
5773 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00005774 }
5775
5776 bool VisitCastExpr(const CastExpr *E) {
5777 switch (E->getCastKind()) {
5778 default:
5779 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
5780
5781 case CK_ConstructorConversion:
5782 return VisitConstructExpr(E->getSubExpr());
5783 }
5784 }
5785 bool VisitInitListExpr(const InitListExpr *E) {
5786 return VisitConstructExpr(E);
5787 }
5788 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
5789 return VisitConstructExpr(E);
5790 }
5791 bool VisitCallExpr(const CallExpr *E) {
5792 return VisitConstructExpr(E);
5793 }
Richard Smith513955c2014-12-17 19:24:30 +00005794 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
5795 return VisitConstructExpr(E);
5796 }
Richard Smith027bf112011-11-17 22:56:20 +00005797};
5798} // end anonymous namespace
5799
5800/// Evaluate an expression of record type as a temporary.
5801static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00005802 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00005803 return TemporaryExprEvaluator(Info, Result).Visit(E);
5804}
5805
5806//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005807// Vector Evaluation
5808//===----------------------------------------------------------------------===//
5809
5810namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005811 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005812 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00005813 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005814 public:
Mike Stump11289f42009-09-09 15:08:12 +00005815
Richard Smith2d406342011-10-22 21:10:00 +00005816 VectorExprEvaluator(EvalInfo &info, APValue &Result)
5817 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00005818
Craig Topper9798b932015-09-29 04:30:05 +00005819 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005820 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
5821 // FIXME: remove this APValue copy.
5822 Result = APValue(V.data(), V.size());
5823 return true;
5824 }
Richard Smith2e312c82012-03-03 22:46:17 +00005825 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00005826 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00005827 Result = V;
5828 return true;
5829 }
Richard Smithfddd3842011-12-30 21:15:51 +00005830 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00005831
Richard Smith2d406342011-10-22 21:10:00 +00005832 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00005833 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00005834 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00005835 bool VisitInitListExpr(const InitListExpr *E);
5836 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005837 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00005838 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00005839 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005840 };
5841} // end anonymous namespace
5842
5843static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00005844 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00005845 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005846}
5847
George Burgess IV533ff002015-12-11 00:23:35 +00005848bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005849 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005850 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005851
Richard Smith161f09a2011-12-06 22:44:34 +00005852 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00005853 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005854
Eli Friedmanc757de22011-03-25 00:43:55 +00005855 switch (E->getCastKind()) {
5856 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00005857 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00005858 if (SETy->isIntegerType()) {
5859 APSInt IntResult;
5860 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00005861 return false;
5862 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005863 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00005864 APFloat FloatResult(0.0);
5865 if (!EvaluateFloat(SE, FloatResult, Info))
5866 return false;
5867 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00005868 } else {
Richard Smith2d406342011-10-22 21:10:00 +00005869 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005870 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00005871
5872 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00005873 SmallVector<APValue, 4> Elts(NElts, Val);
5874 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00005875 }
Eli Friedman803acb32011-12-22 03:51:45 +00005876 case CK_BitCast: {
5877 // Evaluate the operand into an APInt we can extract from.
5878 llvm::APInt SValInt;
5879 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
5880 return false;
5881 // Extract the elements
5882 QualType EltTy = VTy->getElementType();
5883 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
5884 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
5885 SmallVector<APValue, 4> Elts;
5886 if (EltTy->isRealFloatingType()) {
5887 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00005888 unsigned FloatEltSize = EltSize;
5889 if (&Sem == &APFloat::x87DoubleExtended)
5890 FloatEltSize = 80;
5891 for (unsigned i = 0; i < NElts; i++) {
5892 llvm::APInt Elt;
5893 if (BigEndian)
5894 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
5895 else
5896 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00005897 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00005898 }
5899 } else if (EltTy->isIntegerType()) {
5900 for (unsigned i = 0; i < NElts; i++) {
5901 llvm::APInt Elt;
5902 if (BigEndian)
5903 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
5904 else
5905 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
5906 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
5907 }
5908 } else {
5909 return Error(E);
5910 }
5911 return Success(Elts, E);
5912 }
Eli Friedmanc757de22011-03-25 00:43:55 +00005913 default:
Richard Smith11562c52011-10-28 17:51:58 +00005914 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00005915 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005916}
5917
Richard Smith2d406342011-10-22 21:10:00 +00005918bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005919VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005920 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005921 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00005922 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00005923
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005924 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005925 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005926
Eli Friedmanb9c71292012-01-03 23:24:20 +00005927 // The number of initializers can be less than the number of
5928 // vector elements. For OpenCL, this can be due to nested vector
5929 // initialization. For GCC compatibility, missing trailing elements
5930 // should be initialized with zeroes.
5931 unsigned CountInits = 0, CountElts = 0;
5932 while (CountElts < NumElements) {
5933 // Handle nested vector initialization.
5934 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00005935 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00005936 APValue v;
5937 if (!EvaluateVector(E->getInit(CountInits), v, Info))
5938 return Error(E);
5939 unsigned vlen = v.getVectorLength();
5940 for (unsigned j = 0; j < vlen; j++)
5941 Elements.push_back(v.getVectorElt(j));
5942 CountElts += vlen;
5943 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005944 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005945 if (CountInits < NumInits) {
5946 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005947 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005948 } else // trailing integer zero.
5949 sInt = Info.Ctx.MakeIntValue(0, EltTy);
5950 Elements.push_back(APValue(sInt));
5951 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005952 } else {
5953 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00005954 if (CountInits < NumInits) {
5955 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00005956 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00005957 } else // trailing float zero.
5958 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
5959 Elements.push_back(APValue(f));
5960 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00005961 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00005962 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005963 }
Richard Smith2d406342011-10-22 21:10:00 +00005964 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005965}
5966
Richard Smith2d406342011-10-22 21:10:00 +00005967bool
Richard Smithfddd3842011-12-30 21:15:51 +00005968VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00005969 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00005970 QualType EltTy = VT->getElementType();
5971 APValue ZeroElement;
5972 if (EltTy->isIntegerType())
5973 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
5974 else
5975 ZeroElement =
5976 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
5977
Chris Lattner0e62c1c2011-07-23 10:55:15 +00005978 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00005979 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005980}
5981
Richard Smith2d406342011-10-22 21:10:00 +00005982bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00005983 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005984 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00005985}
5986
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00005987//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00005988// Array Evaluation
5989//===----------------------------------------------------------------------===//
5990
5991namespace {
5992 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005993 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00005994 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00005995 APValue &Result;
5996 public:
5997
Richard Smithd62306a2011-11-10 06:34:14 +00005998 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
5999 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006000
6001 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006002 assert((V.isArray() || V.isLValue()) &&
6003 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006004 Result = V;
6005 return true;
6006 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006007
Richard Smithfddd3842011-12-30 21:15:51 +00006008 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006009 const ConstantArrayType *CAT =
6010 Info.Ctx.getAsConstantArrayType(E->getType());
6011 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006012 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006013
6014 Result = APValue(APValue::UninitArray(), 0,
6015 CAT->getSize().getZExtValue());
6016 if (!Result.hasArrayFiller()) return true;
6017
Richard Smithfddd3842011-12-30 21:15:51 +00006018 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006019 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006020 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006021 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006022 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006023 }
6024
Richard Smith52a980a2015-08-28 02:43:42 +00006025 bool VisitCallExpr(const CallExpr *E) {
6026 return handleCallExpr(E, Result, &This);
6027 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006028 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006029 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006030 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6031 const LValue &Subobject,
6032 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006033 };
6034} // end anonymous namespace
6035
Richard Smithd62306a2011-11-10 06:34:14 +00006036static bool EvaluateArray(const Expr *E, const LValue &This,
6037 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006038 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006039 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006040}
6041
6042bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6043 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6044 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006045 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006046
Richard Smithca2cfbf2011-12-22 01:07:19 +00006047 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6048 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006049 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006050 LValue LV;
6051 if (!EvaluateLValue(E->getInit(0), LV, Info))
6052 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006053 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006054 LV.moveInto(Val);
6055 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006056 }
6057
Richard Smith253c2a32012-01-27 01:14:48 +00006058 bool Success = true;
6059
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006060 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6061 "zero-initialized array shouldn't have any initialized elts");
6062 APValue Filler;
6063 if (Result.isArray() && Result.hasArrayFiller())
6064 Filler = Result.getArrayFiller();
6065
Richard Smith9543c5e2013-04-22 14:44:29 +00006066 unsigned NumEltsToInit = E->getNumInits();
6067 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006068 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006069
6070 // If the initializer might depend on the array index, run it for each
6071 // array element. For now, just whitelist non-class value-initialization.
6072 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6073 NumEltsToInit = NumElts;
6074
6075 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006076
6077 // If the array was previously zero-initialized, preserve the
6078 // zero-initialized values.
6079 if (!Filler.isUninit()) {
6080 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6081 Result.getArrayInitializedElt(I) = Filler;
6082 if (Result.hasArrayFiller())
6083 Result.getArrayFiller() = Filler;
6084 }
6085
Richard Smithd62306a2011-11-10 06:34:14 +00006086 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006087 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006088 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6089 const Expr *Init =
6090 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006091 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006092 Info, Subobject, Init) ||
6093 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006094 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006095 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006096 return false;
6097 Success = false;
6098 }
Richard Smithd62306a2011-11-10 06:34:14 +00006099 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006100
Richard Smith9543c5e2013-04-22 14:44:29 +00006101 if (!Result.hasArrayFiller())
6102 return Success;
6103
6104 // If we get here, we have a trivial filler, which we can just evaluate
6105 // once and splat over the rest of the array elements.
6106 assert(FillerExpr && "no array filler for incomplete init list");
6107 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6108 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006109}
6110
Richard Smith027bf112011-11-17 22:56:20 +00006111bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006112 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6113}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006114
Richard Smith9543c5e2013-04-22 14:44:29 +00006115bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6116 const LValue &Subobject,
6117 APValue *Value,
6118 QualType Type) {
6119 bool HadZeroInit = !Value->isUninit();
6120
6121 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6122 unsigned N = CAT->getSize().getZExtValue();
6123
6124 // Preserve the array filler if we had prior zero-initialization.
6125 APValue Filler =
6126 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6127 : APValue();
6128
6129 *Value = APValue(APValue::UninitArray(), N, N);
6130
6131 if (HadZeroInit)
6132 for (unsigned I = 0; I != N; ++I)
6133 Value->getArrayInitializedElt(I) = Filler;
6134
6135 // Initialize the elements.
6136 LValue ArrayElt = Subobject;
6137 ArrayElt.addArray(Info, E, CAT);
6138 for (unsigned I = 0; I != N; ++I)
6139 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6140 CAT->getElementType()) ||
6141 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6142 CAT->getElementType(), 1))
6143 return false;
6144
6145 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006146 }
Richard Smith027bf112011-11-17 22:56:20 +00006147
Richard Smith9543c5e2013-04-22 14:44:29 +00006148 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006149 return Error(E);
6150
Richard Smithb8348f52016-05-12 22:16:28 +00006151 return RecordExprEvaluator(Info, Subobject, *Value)
6152 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006153}
6154
Richard Smithf3e9e432011-11-07 09:22:26 +00006155//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006156// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006157//
6158// As a GNU extension, we support casting pointers to sufficiently-wide integer
6159// types and back in constant folding. Integer values are thus represented
6160// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006161//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006162
6163namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006164class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006165 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006166 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006167public:
Richard Smith2e312c82012-03-03 22:46:17 +00006168 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006169 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006170
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006171 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006172 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006173 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006174 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006175 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006176 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006177 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006178 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006179 return true;
6180 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006181 bool Success(const llvm::APSInt &SI, const Expr *E) {
6182 return Success(SI, E, Result);
6183 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006184
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006185 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006186 assert(E->getType()->isIntegralOrEnumerationType() &&
6187 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006188 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006189 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006190 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006191 Result.getInt().setIsUnsigned(
6192 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006193 return true;
6194 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006195 bool Success(const llvm::APInt &I, const Expr *E) {
6196 return Success(I, E, Result);
6197 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006198
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006199 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Douglas Gregorb90df602010-06-16 00:17:44 +00006200 assert(E->getType()->isIntegralOrEnumerationType() &&
6201 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006202 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006203 return true;
6204 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006205 bool Success(uint64_t Value, const Expr *E) {
6206 return Success(Value, E, Result);
6207 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006208
Ken Dyckdbc01912011-03-11 02:13:43 +00006209 bool Success(CharUnits Size, const Expr *E) {
6210 return Success(Size.getQuantity(), E);
6211 }
6212
Richard Smith2e312c82012-03-03 22:46:17 +00006213 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006214 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006215 Result = V;
6216 return true;
6217 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006218 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006219 }
Mike Stump11289f42009-09-09 15:08:12 +00006220
Richard Smithfddd3842011-12-30 21:15:51 +00006221 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006222
Peter Collingbournee9200682011-05-13 03:29:01 +00006223 //===--------------------------------------------------------------------===//
6224 // Visitor Methods
6225 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006226
Chris Lattner7174bf32008-07-12 00:38:25 +00006227 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006228 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006229 }
6230 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006231 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00006232 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006233
6234 bool CheckReferencedDecl(const Expr *E, const Decl *D);
6235 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00006236 if (CheckReferencedDecl(E, E->getDecl()))
6237 return true;
6238
6239 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006240 }
6241 bool VisitMemberExpr(const MemberExpr *E) {
6242 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00006243 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006244 return true;
6245 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006246
6247 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006248 }
6249
Peter Collingbournee9200682011-05-13 03:29:01 +00006250 bool VisitCallExpr(const CallExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006251 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00006252 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00006253 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00006254
Peter Collingbournee9200682011-05-13 03:29:01 +00006255 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00006256 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00006257
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006258 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006259 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00006260 }
Mike Stump11289f42009-09-09 15:08:12 +00006261
Ted Kremeneke65b0862012-03-06 20:05:56 +00006262 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
6263 return Success(E->getValue(), E);
6264 }
6265
Richard Smith4ce706a2011-10-11 21:43:33 +00006266 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00006267 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00006268 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006269 }
6270
Douglas Gregor29c42f22012-02-24 07:38:34 +00006271 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
6272 return Success(E->getValue(), E);
6273 }
6274
John Wiegley6242b6a2011-04-28 00:16:57 +00006275 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
6276 return Success(E->getValue(), E);
6277 }
6278
John Wiegleyf9f65842011-04-25 06:54:41 +00006279 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
6280 return Success(E->getValue(), E);
6281 }
6282
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00006283 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006284 bool VisitUnaryImag(const UnaryOperator *E);
6285
Sebastian Redl5f0180d2010-09-10 20:55:47 +00006286 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00006287 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00006288
Chris Lattnerf8d7f722008-07-11 21:24:13 +00006289private:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006290 bool TryEvaluateBuiltinObjectSize(const CallExpr *E, unsigned Type);
Eli Friedman4e7a2412009-02-27 04:45:43 +00006291 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00006292};
Chris Lattner05706e882008-07-11 18:11:29 +00006293} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006294
Richard Smith11562c52011-10-28 17:51:58 +00006295/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
6296/// produce either the integer value or a pointer.
6297///
6298/// GCC has a heinous extension which folds casts between pointer types and
6299/// pointer-sized integral types. We support this by allowing the evaluation of
6300/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
6301/// Some simple arithmetic on such values is supported (they are treated much
6302/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00006303static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00006304 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006305 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00006306 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00006307}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006308
Richard Smithf57d8cb2011-12-09 22:58:01 +00006309static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00006310 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006311 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00006312 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006313 if (!Val.isInt()) {
6314 // FIXME: It would be better to produce the diagnostic for casting
6315 // a pointer to an integer.
Richard Smithce1ec5e2012-03-15 04:53:45 +00006316 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00006317 return false;
6318 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006319 Result = Val.getInt();
6320 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006321}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00006322
Richard Smithf57d8cb2011-12-09 22:58:01 +00006323/// Check whether the given declaration can be directly converted to an integral
6324/// rvalue. If not, no diagnostic is produced; there are other things we can
6325/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00006326bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00006327 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006328 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006329 // Check for signedness/width mismatches between E type and ECD value.
6330 bool SameSign = (ECD->getInitVal().isSigned()
6331 == E->getType()->isSignedIntegerOrEnumerationType());
6332 bool SameWidth = (ECD->getInitVal().getBitWidth()
6333 == Info.Ctx.getIntWidth(E->getType()));
6334 if (SameSign && SameWidth)
6335 return Success(ECD->getInitVal(), E);
6336 else {
6337 // Get rid of mismatch (otherwise Success assertions will fail)
6338 // by computing a new value matching the type of E.
6339 llvm::APSInt Val = ECD->getInitVal();
6340 if (!SameSign)
6341 Val.setIsSigned(!ECD->getInitVal().isSigned());
6342 if (!SameWidth)
6343 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
6344 return Success(Val, E);
6345 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00006346 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006347 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00006348}
6349
Chris Lattner86ee2862008-10-06 06:40:35 +00006350/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
6351/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006352static int EvaluateBuiltinClassifyType(const CallExpr *E,
6353 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00006354 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00006355 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00006356 enum gcc_type_class {
6357 no_type_class = -1,
6358 void_type_class, integer_type_class, char_type_class,
6359 enumeral_type_class, boolean_type_class,
6360 pointer_type_class, reference_type_class, offset_type_class,
6361 real_type_class, complex_type_class,
6362 function_type_class, method_type_class,
6363 record_type_class, union_type_class,
6364 array_type_class, string_type_class,
6365 lang_type_class
6366 };
Mike Stump11289f42009-09-09 15:08:12 +00006367
6368 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00006369 // ideal, however it is what gcc does.
6370 if (E->getNumArgs() == 0)
6371 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00006372
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006373 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
6374 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
6375
6376 switch (CanTy->getTypeClass()) {
6377#define TYPE(ID, BASE)
6378#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
6379#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
6380#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
6381#include "clang/AST/TypeNodes.def"
6382 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6383
6384 case Type::Builtin:
6385 switch (BT->getKind()) {
6386#define BUILTIN_TYPE(ID, SINGLETON_ID)
6387#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
6388#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
6389#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
6390#include "clang/AST/BuiltinTypes.def"
6391 case BuiltinType::Void:
6392 return void_type_class;
6393
6394 case BuiltinType::Bool:
6395 return boolean_type_class;
6396
6397 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
6398 case BuiltinType::UChar:
6399 case BuiltinType::UShort:
6400 case BuiltinType::UInt:
6401 case BuiltinType::ULong:
6402 case BuiltinType::ULongLong:
6403 case BuiltinType::UInt128:
6404 return integer_type_class;
6405
6406 case BuiltinType::NullPtr:
6407 return pointer_type_class;
6408
6409 case BuiltinType::WChar_U:
6410 case BuiltinType::Char16:
6411 case BuiltinType::Char32:
6412 case BuiltinType::ObjCId:
6413 case BuiltinType::ObjCClass:
6414 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00006415#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
6416 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00006417#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006418 case BuiltinType::OCLSampler:
6419 case BuiltinType::OCLEvent:
6420 case BuiltinType::OCLClkEvent:
6421 case BuiltinType::OCLQueue:
6422 case BuiltinType::OCLNDRange:
6423 case BuiltinType::OCLReserveID:
6424 case BuiltinType::Dependent:
6425 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6426 };
6427
6428 case Type::Enum:
6429 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6430 break;
6431
6432 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00006433 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006434 break;
6435
6436 case Type::MemberPointer:
6437 if (CanTy->isMemberDataPointerType())
6438 return offset_type_class;
6439 else {
6440 // We expect member pointers to be either data or function pointers,
6441 // nothing else.
6442 assert(CanTy->isMemberFunctionPointerType());
6443 return method_type_class;
6444 }
6445
6446 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00006447 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006448
6449 case Type::FunctionNoProto:
6450 case Type::FunctionProto:
6451 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
6452
6453 case Type::Record:
6454 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
6455 switch (RT->getDecl()->getTagKind()) {
6456 case TagTypeKind::TTK_Struct:
6457 case TagTypeKind::TTK_Class:
6458 case TagTypeKind::TTK_Interface:
6459 return record_type_class;
6460
6461 case TagTypeKind::TTK_Enum:
6462 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
6463
6464 case TagTypeKind::TTK_Union:
6465 return union_type_class;
6466 }
6467 }
David Blaikie83d382b2011-09-23 05:06:16 +00006468 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006469
6470 case Type::ConstantArray:
6471 case Type::VariableArray:
6472 case Type::IncompleteArray:
6473 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
6474
6475 case Type::BlockPointer:
6476 case Type::LValueReference:
6477 case Type::RValueReference:
6478 case Type::Vector:
6479 case Type::ExtVector:
6480 case Type::Auto:
6481 case Type::ObjCObject:
6482 case Type::ObjCInterface:
6483 case Type::ObjCObjectPointer:
6484 case Type::Pipe:
6485 case Type::Atomic:
6486 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
6487 }
6488
6489 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00006490}
6491
Richard Smith5fab0c92011-12-28 19:48:30 +00006492/// EvaluateBuiltinConstantPForLValue - Determine the result of
6493/// __builtin_constant_p when applied to the given lvalue.
6494///
6495/// An lvalue is only "constant" if it is a pointer or reference to the first
6496/// character of a string literal.
6497template<typename LValue>
6498static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00006499 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00006500 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
6501}
6502
6503/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
6504/// GCC as we can manage.
6505static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
6506 QualType ArgType = Arg->getType();
6507
6508 // __builtin_constant_p always has one operand. The rules which gcc follows
6509 // are not precisely documented, but are as follows:
6510 //
6511 // - If the operand is of integral, floating, complex or enumeration type,
6512 // and can be folded to a known value of that type, it returns 1.
6513 // - If the operand and can be folded to a pointer to the first character
6514 // of a string literal (or such a pointer cast to an integral type), it
6515 // returns 1.
6516 //
6517 // Otherwise, it returns 0.
6518 //
6519 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
6520 // its support for this does not currently work.
6521 if (ArgType->isIntegralOrEnumerationType()) {
6522 Expr::EvalResult Result;
6523 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
6524 return false;
6525
6526 APValue &V = Result.Val;
6527 if (V.getKind() == APValue::Int)
6528 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00006529 if (V.getKind() == APValue::LValue)
6530 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00006531 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
6532 return Arg->isEvaluatable(Ctx);
6533 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
6534 LValue LV;
6535 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00006536 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00006537 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
6538 : EvaluatePointer(Arg, LV, Info)) &&
6539 !Status.HasSideEffects)
6540 return EvaluateBuiltinConstantPForLValue(LV);
6541 }
6542
6543 // Anything else isn't considered to be sufficiently constant.
6544 return false;
6545}
6546
John McCall95007602010-05-10 23:27:23 +00006547/// Retrieves the "underlying object type" of the given expression,
6548/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00006549static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00006550 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
6551 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00006552 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00006553 } else if (const Expr *E = B.get<const Expr*>()) {
6554 if (isa<CompoundLiteralExpr>(E))
6555 return E->getType();
John McCall95007602010-05-10 23:27:23 +00006556 }
6557
6558 return QualType();
6559}
6560
George Burgess IV3a03fab2015-09-04 21:28:13 +00006561/// A more selective version of E->IgnoreParenCasts for
George Burgess IVb40cd562015-09-04 22:36:18 +00006562/// TryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
6563/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00006564/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
6565///
6566/// Always returns an RValue with a pointer representation.
6567static const Expr *ignorePointerCastsAndParens(const Expr *E) {
6568 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
6569
6570 auto *NoParens = E->IgnoreParens();
6571 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00006572 if (Cast == nullptr)
6573 return NoParens;
6574
6575 // We only conservatively allow a few kinds of casts, because this code is
6576 // inherently a simple solution that seeks to support the common case.
6577 auto CastKind = Cast->getCastKind();
6578 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
6579 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00006580 return NoParens;
6581
6582 auto *SubExpr = Cast->getSubExpr();
6583 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
6584 return NoParens;
6585 return ignorePointerCastsAndParens(SubExpr);
6586}
6587
George Burgess IVa51c4072015-10-16 01:49:01 +00006588/// Checks to see if the given LValue's Designator is at the end of the LValue's
6589/// record layout. e.g.
6590/// struct { struct { int a, b; } fst, snd; } obj;
6591/// obj.fst // no
6592/// obj.snd // yes
6593/// obj.fst.a // no
6594/// obj.fst.b // no
6595/// obj.snd.a // no
6596/// obj.snd.b // yes
6597///
6598/// Please note: this function is specialized for how __builtin_object_size
6599/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00006600///
6601/// If this encounters an invalid RecordDecl, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00006602static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
6603 assert(!LVal.Designator.Invalid);
6604
George Burgess IV4168d752016-06-27 19:40:41 +00006605 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
6606 const RecordDecl *Parent = FD->getParent();
6607 Invalid = Parent->isInvalidDecl();
6608 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00006609 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00006610 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00006611 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
6612 };
6613
6614 auto &Base = LVal.getLValueBase();
6615 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
6616 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006617 bool Invalid;
6618 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6619 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006620 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00006621 for (auto *FD : IFD->chain()) {
6622 bool Invalid;
6623 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
6624 return Invalid;
6625 }
George Burgess IVa51c4072015-10-16 01:49:01 +00006626 }
6627 }
6628
6629 QualType BaseType = getType(Base);
6630 for (int I = 0, E = LVal.Designator.Entries.size(); I != E; ++I) {
6631 if (BaseType->isArrayType()) {
6632 // Because __builtin_object_size treats arrays as objects, we can ignore
6633 // the index iff this is the last array in the Designator.
6634 if (I + 1 == E)
6635 return true;
6636 auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
6637 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6638 if (Index + 1 != CAT->getSize())
6639 return false;
6640 BaseType = CAT->getElementType();
6641 } else if (BaseType->isAnyComplexType()) {
6642 auto *CT = BaseType->castAs<ComplexType>();
6643 uint64_t Index = LVal.Designator.Entries[I].ArrayIndex;
6644 if (Index != 1)
6645 return false;
6646 BaseType = CT->getElementType();
6647 } else if (auto *FD = getAsField(LVal.Designator.Entries[I])) {
George Burgess IV4168d752016-06-27 19:40:41 +00006648 bool Invalid;
6649 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
6650 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00006651 BaseType = FD->getType();
6652 } else {
6653 assert(getAsBaseClass(LVal.Designator.Entries[I]) != nullptr &&
6654 "Expecting cast to a base class");
6655 return false;
6656 }
6657 }
6658 return true;
6659}
6660
6661/// Tests to see if the LValue has a designator (that isn't necessarily valid).
6662static bool refersToCompleteObject(const LValue &LVal) {
6663 if (LVal.Designator.Invalid || !LVal.Designator.Entries.empty())
6664 return false;
6665
6666 if (!LVal.InvalidBase)
6667 return true;
6668
6669 auto *E = LVal.Base.dyn_cast<const Expr *>();
6670 (void)E;
6671 assert(E != nullptr && isa<MemberExpr>(E));
6672 return false;
6673}
6674
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006675/// Tries to evaluate the __builtin_object_size for @p E. If successful, returns
6676/// true and stores the result in @p Size.
6677///
6678/// If @p WasError is non-null, this will report whether the failure to evaluate
6679/// is to be treated as an Error in IntExprEvaluator.
6680static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
6681 EvalInfo &Info, uint64_t &Size,
6682 bool *WasError = nullptr) {
6683 if (WasError != nullptr)
6684 *WasError = false;
6685
6686 auto Error = [&](const Expr *E) {
6687 if (WasError != nullptr)
6688 *WasError = true;
6689 return false;
6690 };
6691
6692 auto Success = [&](uint64_t S, const Expr *E) {
6693 Size = S;
6694 return true;
6695 };
6696
George Burgess IVbdb5b262015-08-19 02:19:07 +00006697 // Determine the denoted object.
John McCall95007602010-05-10 23:27:23 +00006698 LValue Base;
Richard Smith01ade172012-05-23 04:13:20 +00006699 {
6700 // The operand of __builtin_object_size is never evaluated for side-effects.
6701 // If there are any, but we can determine the pointed-to object anyway, then
6702 // ignore the side-effects.
6703 SpeculativeEvaluationRAII SpeculativeEval(Info);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006704 FoldOffsetRAII Fold(Info, Type & 1);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006705
6706 if (E->isGLValue()) {
6707 // It's possible for us to be given GLValues if we're called via
6708 // Expr::tryEvaluateObjectSize.
6709 APValue RVal;
6710 if (!EvaluateAsRValue(Info, E, RVal))
6711 return false;
6712 Base.setFrom(Info.Ctx, RVal);
6713 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), Base, Info))
Richard Smith01ade172012-05-23 04:13:20 +00006714 return false;
6715 }
John McCall95007602010-05-10 23:27:23 +00006716
George Burgess IVbdb5b262015-08-19 02:19:07 +00006717 CharUnits BaseOffset = Base.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00006718 // If we point to before the start of the object, there are no accessible
6719 // bytes.
6720 if (BaseOffset.isNegative())
George Burgess IVbdb5b262015-08-19 02:19:07 +00006721 return Success(0, E);
6722
George Burgess IV3a03fab2015-09-04 21:28:13 +00006723 // In the case where we're not dealing with a subobject, we discard the
6724 // subobject bit.
George Burgess IVa51c4072015-10-16 01:49:01 +00006725 bool SubobjectOnly = (Type & 1) != 0 && !refersToCompleteObject(Base);
George Burgess IV3a03fab2015-09-04 21:28:13 +00006726
6727 // If Type & 1 is 0, we need to be able to statically guarantee that the bytes
6728 // exist. If we can't verify the base, then we can't do that.
6729 //
6730 // As a special case, we produce a valid object size for an unknown object
6731 // with a known designator if Type & 1 is 1. For instance:
6732 //
6733 // extern struct X { char buff[32]; int a, b, c; } *p;
6734 // int a = __builtin_object_size(p->buff + 4, 3); // returns 28
6735 // int b = __builtin_object_size(p->buff + 4, 2); // returns 0, not 40
6736 //
6737 // This matches GCC's behavior.
George Burgess IVa51c4072015-10-16 01:49:01 +00006738 if (Base.InvalidBase && !SubobjectOnly)
Nico Weber19999b42015-08-18 20:32:55 +00006739 return Error(E);
George Burgess IVbdb5b262015-08-19 02:19:07 +00006740
George Burgess IVa51c4072015-10-16 01:49:01 +00006741 // If we're not examining only the subobject, then we reset to a complete
6742 // object designator
George Burgess IVbdb5b262015-08-19 02:19:07 +00006743 //
6744 // If Type is 1 and we've lost track of the subobject, just find the complete
6745 // object instead. (If Type is 3, that's not correct behavior and we should
6746 // return 0 instead.)
6747 LValue End = Base;
George Burgess IVa51c4072015-10-16 01:49:01 +00006748 if (!SubobjectOnly || (End.Designator.Invalid && Type == 1)) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006749 QualType T = getObjectType(End.getLValueBase());
6750 if (T.isNull())
6751 End.Designator.setInvalid();
6752 else {
6753 End.Designator = SubobjectDesignator(T);
6754 End.Offset = CharUnits::Zero();
6755 }
Fariborz Jahaniana3d88792014-09-22 17:11:59 +00006756 }
John McCall95007602010-05-10 23:27:23 +00006757
George Burgess IVbdb5b262015-08-19 02:19:07 +00006758 // If it is not possible to determine which objects ptr points to at compile
6759 // time, __builtin_object_size should return (size_t) -1 for type 0 or 1
6760 // and (size_t) 0 for type 2 or 3.
6761 if (End.Designator.Invalid)
6762 return false;
6763
6764 // According to the GCC documentation, we want the size of the subobject
6765 // denoted by the pointer. But that's not quite right -- what we actually
6766 // want is the size of the immediately-enclosing array, if there is one.
6767 int64_t AmountToAdd = 1;
George Burgess IVa51c4072015-10-16 01:49:01 +00006768 if (End.Designator.MostDerivedIsArrayElement &&
George Burgess IVbdb5b262015-08-19 02:19:07 +00006769 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength) {
6770 // We got a pointer to an array. Step to its end.
6771 AmountToAdd = End.Designator.MostDerivedArraySize -
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006772 End.Designator.Entries.back().ArrayIndex;
George Burgess IV3a03fab2015-09-04 21:28:13 +00006773 } else if (End.Designator.isOnePastTheEnd()) {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006774 // We're already pointing at the end of the object.
6775 AmountToAdd = 0;
6776 }
6777
George Burgess IV3a03fab2015-09-04 21:28:13 +00006778 QualType PointeeType = End.Designator.MostDerivedType;
6779 assert(!PointeeType.isNull());
6780 if (PointeeType->isIncompleteType() || PointeeType->isFunctionType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00006781 return Error(E);
John McCall95007602010-05-10 23:27:23 +00006782
George Burgess IVbdb5b262015-08-19 02:19:07 +00006783 if (!HandleLValueArrayAdjustment(Info, E, End, End.Designator.MostDerivedType,
6784 AmountToAdd))
6785 return false;
John McCall95007602010-05-10 23:27:23 +00006786
George Burgess IVbdb5b262015-08-19 02:19:07 +00006787 auto EndOffset = End.getLValueOffset();
George Burgess IVa51c4072015-10-16 01:49:01 +00006788
6789 // The following is a moderately common idiom in C:
6790 //
6791 // struct Foo { int a; char c[1]; };
6792 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
6793 // strcpy(&F->c[0], Bar);
6794 //
6795 // So, if we see that we're examining a 1-length (or 0-length) array at the
6796 // end of a struct with an unknown base, we give up instead of breaking code
6797 // that behaves this way. Note that we only do this when Type=1, because
6798 // Type=3 is a lower bound, so answering conservatively is fine.
6799 if (End.InvalidBase && SubobjectOnly && Type == 1 &&
6800 End.Designator.Entries.size() == End.Designator.MostDerivedPathLength &&
6801 End.Designator.MostDerivedIsArrayElement &&
6802 End.Designator.MostDerivedArraySize < 2 &&
6803 isDesignatorAtObjectEnd(Info.Ctx, End))
6804 return false;
6805
George Burgess IVbdb5b262015-08-19 02:19:07 +00006806 if (BaseOffset > EndOffset)
6807 return Success(0, E);
6808
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006809 return Success((EndOffset - BaseOffset).getQuantity(), E);
6810}
6811
6812bool IntExprEvaluator::TryEvaluateBuiltinObjectSize(const CallExpr *E,
6813 unsigned Type) {
6814 uint64_t Size;
6815 bool WasError;
6816 if (::tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size, &WasError))
6817 return Success(Size, E);
6818 if (WasError)
6819 return Error(E);
6820 return false;
John McCall95007602010-05-10 23:27:23 +00006821}
6822
Peter Collingbournee9200682011-05-13 03:29:01 +00006823bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00006824 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00006825 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00006826 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00006827
6828 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00006829 // The type was checked when we built the expression.
6830 unsigned Type =
6831 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6832 assert(Type <= 3 && "unexpected type");
6833
6834 if (TryEvaluateBuiltinObjectSize(E, Type))
John McCall95007602010-05-10 23:27:23 +00006835 return true;
Mike Stump722cedf2009-10-26 18:35:08 +00006836
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00006837 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00006838 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00006839
Richard Smith01ade172012-05-23 04:13:20 +00006840 // Expression had no side effects, but we couldn't statically determine the
6841 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006842 switch (Info.EvalMode) {
6843 case EvalInfo::EM_ConstantExpression:
6844 case EvalInfo::EM_PotentialConstantExpression:
6845 case EvalInfo::EM_ConstantFold:
6846 case EvalInfo::EM_EvaluateForOverflow:
6847 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IV3a03fab2015-09-04 21:28:13 +00006848 case EvalInfo::EM_DesignatorFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006849 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006850 return Error(E);
6851 case EvalInfo::EM_ConstantExpressionUnevaluated:
6852 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00006853 // Reduce it to a constant now.
6854 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00006855 }
Mike Stump722cedf2009-10-26 18:35:08 +00006856 }
6857
Benjamin Kramera801f4a2012-10-06 14:42:22 +00006858 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00006859 case Builtin::BI__builtin_bswap32:
6860 case Builtin::BI__builtin_bswap64: {
6861 APSInt Val;
6862 if (!EvaluateInteger(E->getArg(0), Val, Info))
6863 return false;
6864
6865 return Success(Val.byteSwap(), E);
6866 }
6867
Richard Smith8889a3d2013-06-13 06:26:32 +00006868 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00006869 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00006870
6871 // FIXME: BI__builtin_clrsb
6872 // FIXME: BI__builtin_clrsbl
6873 // FIXME: BI__builtin_clrsbll
6874
Richard Smith80b3c8e2013-06-13 05:04:16 +00006875 case Builtin::BI__builtin_clz:
6876 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006877 case Builtin::BI__builtin_clzll:
6878 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006879 APSInt Val;
6880 if (!EvaluateInteger(E->getArg(0), Val, Info))
6881 return false;
6882 if (!Val)
6883 return Error(E);
6884
6885 return Success(Val.countLeadingZeros(), E);
6886 }
6887
Richard Smith8889a3d2013-06-13 06:26:32 +00006888 case Builtin::BI__builtin_constant_p:
6889 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
6890
Richard Smith80b3c8e2013-06-13 05:04:16 +00006891 case Builtin::BI__builtin_ctz:
6892 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00006893 case Builtin::BI__builtin_ctzll:
6894 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00006895 APSInt Val;
6896 if (!EvaluateInteger(E->getArg(0), Val, Info))
6897 return false;
6898 if (!Val)
6899 return Error(E);
6900
6901 return Success(Val.countTrailingZeros(), E);
6902 }
6903
Richard Smith8889a3d2013-06-13 06:26:32 +00006904 case Builtin::BI__builtin_eh_return_data_regno: {
6905 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
6906 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
6907 return Success(Operand, E);
6908 }
6909
6910 case Builtin::BI__builtin_expect:
6911 return Visit(E->getArg(0));
6912
6913 case Builtin::BI__builtin_ffs:
6914 case Builtin::BI__builtin_ffsl:
6915 case Builtin::BI__builtin_ffsll: {
6916 APSInt Val;
6917 if (!EvaluateInteger(E->getArg(0), Val, Info))
6918 return false;
6919
6920 unsigned N = Val.countTrailingZeros();
6921 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
6922 }
6923
6924 case Builtin::BI__builtin_fpclassify: {
6925 APFloat Val(0.0);
6926 if (!EvaluateFloat(E->getArg(5), Val, Info))
6927 return false;
6928 unsigned Arg;
6929 switch (Val.getCategory()) {
6930 case APFloat::fcNaN: Arg = 0; break;
6931 case APFloat::fcInfinity: Arg = 1; break;
6932 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
6933 case APFloat::fcZero: Arg = 4; break;
6934 }
6935 return Visit(E->getArg(Arg));
6936 }
6937
6938 case Builtin::BI__builtin_isinf_sign: {
6939 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00006940 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00006941 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
6942 }
6943
Richard Smithea3019d2013-10-15 19:07:14 +00006944 case Builtin::BI__builtin_isinf: {
6945 APFloat Val(0.0);
6946 return EvaluateFloat(E->getArg(0), Val, Info) &&
6947 Success(Val.isInfinity() ? 1 : 0, E);
6948 }
6949
6950 case Builtin::BI__builtin_isfinite: {
6951 APFloat Val(0.0);
6952 return EvaluateFloat(E->getArg(0), Val, Info) &&
6953 Success(Val.isFinite() ? 1 : 0, E);
6954 }
6955
6956 case Builtin::BI__builtin_isnan: {
6957 APFloat Val(0.0);
6958 return EvaluateFloat(E->getArg(0), Val, Info) &&
6959 Success(Val.isNaN() ? 1 : 0, E);
6960 }
6961
6962 case Builtin::BI__builtin_isnormal: {
6963 APFloat Val(0.0);
6964 return EvaluateFloat(E->getArg(0), Val, Info) &&
6965 Success(Val.isNormal() ? 1 : 0, E);
6966 }
6967
Richard Smith8889a3d2013-06-13 06:26:32 +00006968 case Builtin::BI__builtin_parity:
6969 case Builtin::BI__builtin_parityl:
6970 case Builtin::BI__builtin_parityll: {
6971 APSInt Val;
6972 if (!EvaluateInteger(E->getArg(0), Val, Info))
6973 return false;
6974
6975 return Success(Val.countPopulation() % 2, E);
6976 }
6977
Richard Smith80b3c8e2013-06-13 05:04:16 +00006978 case Builtin::BI__builtin_popcount:
6979 case Builtin::BI__builtin_popcountl:
6980 case Builtin::BI__builtin_popcountll: {
6981 APSInt Val;
6982 if (!EvaluateInteger(E->getArg(0), Val, Info))
6983 return false;
6984
6985 return Success(Val.countPopulation(), E);
6986 }
6987
Douglas Gregor6a6dac22010-09-10 06:27:15 +00006988 case Builtin::BIstrlen:
Richard Smith9cf080f2012-01-18 03:06:12 +00006989 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00006990 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00006991 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith9cf080f2012-01-18 03:06:12 +00006992 << /*isConstexpr*/0 << /*isConstructor*/0 << "'strlen'";
6993 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00006994 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00006995 // Fall through.
Richard Smithe6c19f22013-11-15 02:10:04 +00006996 case Builtin::BI__builtin_strlen: {
6997 // As an extension, we support __builtin_strlen() as a constant expression,
6998 // and support folding strlen() to a constant.
6999 LValue String;
7000 if (!EvaluatePointer(E->getArg(0), String, Info))
7001 return false;
7002
7003 // Fast path: if it's a string literal, search the string value.
7004 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7005 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007006 // The string literal may have embedded null characters. Find the first
7007 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007008 StringRef Str = S->getBytes();
7009 int64_t Off = String.Offset.getQuantity();
7010 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
7011 S->getCharByteWidth() == 1) {
7012 Str = Str.substr(Off);
7013
7014 StringRef::size_type Pos = Str.find(0);
7015 if (Pos != StringRef::npos)
7016 Str = Str.substr(0, Pos);
7017
7018 return Success(Str.size(), E);
7019 }
7020
7021 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007022 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007023
7024 // Slow path: scan the bytes of the string looking for the terminating 0.
7025 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7026 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7027 APValue Char;
7028 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7029 !Char.isInt())
7030 return false;
7031 if (!Char.getInt())
7032 return Success(Strlen, E);
7033 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7034 return false;
7035 }
7036 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007037
Richard Smith01ba47d2012-04-13 00:45:38 +00007038 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007039 case Builtin::BI__atomic_is_lock_free:
7040 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007041 APSInt SizeVal;
7042 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7043 return false;
7044
7045 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7046 // of two less than the maximum inline atomic width, we know it is
7047 // lock-free. If the size isn't a power of two, or greater than the
7048 // maximum alignment where we promote atomics, we know it is not lock-free
7049 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7050 // the answer can only be determined at runtime; for example, 16-byte
7051 // atomics have lock-free implementations on some, but not all,
7052 // x86-64 processors.
7053
7054 // Check power-of-two.
7055 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007056 if (Size.isPowerOfTwo()) {
7057 // Check against inlining width.
7058 unsigned InlineWidthBits =
7059 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7060 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7061 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7062 Size == CharUnits::One() ||
7063 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7064 Expr::NPC_NeverValueDependent))
7065 // OK, we will inline appropriately-aligned operations of this size,
7066 // and _Atomic(T) is appropriately-aligned.
7067 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007068
Richard Smith01ba47d2012-04-13 00:45:38 +00007069 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7070 castAs<PointerType>()->getPointeeType();
7071 if (!PointeeType->isIncompleteType() &&
7072 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7073 // OK, we will inline operations on this object.
7074 return Success(1, E);
7075 }
7076 }
7077 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007078
Richard Smith01ba47d2012-04-13 00:45:38 +00007079 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7080 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007081 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007082 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007083}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007084
Richard Smith8b3497e2011-10-31 01:37:14 +00007085static bool HasSameBase(const LValue &A, const LValue &B) {
7086 if (!A.getLValueBase())
7087 return !B.getLValueBase();
7088 if (!B.getLValueBase())
7089 return false;
7090
Richard Smithce40ad62011-11-12 22:28:03 +00007091 if (A.getLValueBase().getOpaqueValue() !=
7092 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007093 const Decl *ADecl = GetLValueBaseDecl(A);
7094 if (!ADecl)
7095 return false;
7096 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007097 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007098 return false;
7099 }
7100
7101 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007102 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007103}
7104
Richard Smithd20f1e62014-10-21 23:01:04 +00007105/// \brief Determine whether this is a pointer past the end of the complete
7106/// object referred to by the lvalue.
7107static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
7108 const LValue &LV) {
7109 // A null pointer can be viewed as being "past the end" but we don't
7110 // choose to look at it that way here.
7111 if (!LV.getLValueBase())
7112 return false;
7113
7114 // If the designator is valid and refers to a subobject, we're not pointing
7115 // past the end.
7116 if (!LV.getLValueDesignator().Invalid &&
7117 !LV.getLValueDesignator().isOnePastTheEnd())
7118 return false;
7119
David Majnemerc378ca52015-08-29 08:32:55 +00007120 // A pointer to an incomplete type might be past-the-end if the type's size is
7121 // zero. We cannot tell because the type is incomplete.
7122 QualType Ty = getType(LV.getLValueBase());
7123 if (Ty->isIncompleteType())
7124 return true;
7125
Richard Smithd20f1e62014-10-21 23:01:04 +00007126 // We're a past-the-end pointer if we point to the byte after the object,
7127 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00007128 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00007129 return LV.getLValueOffset() == Size;
7130}
7131
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007132namespace {
Richard Smith11562c52011-10-28 17:51:58 +00007133
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007134/// \brief Data recursive integer evaluator of certain binary operators.
7135///
7136/// We use a data recursive algorithm for binary operators so that we are able
7137/// to handle extreme cases of chained binary operators without causing stack
7138/// overflow.
7139class DataRecursiveIntBinOpEvaluator {
7140 struct EvalResult {
7141 APValue Val;
7142 bool Failed;
7143
7144 EvalResult() : Failed(false) { }
7145
7146 void swap(EvalResult &RHS) {
7147 Val.swap(RHS.Val);
7148 Failed = RHS.Failed;
7149 RHS.Failed = false;
7150 }
7151 };
7152
7153 struct Job {
7154 const Expr *E;
7155 EvalResult LHSResult; // meaningful only for binary operator expression.
7156 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00007157
David Blaikie73726062015-08-12 23:09:24 +00007158 Job() = default;
7159 Job(Job &&J)
7160 : E(J.E), LHSResult(J.LHSResult), Kind(J.Kind),
George Burgess IV8c892b52016-05-25 22:31:54 +00007161 SpecEvalRAII(std::move(J.SpecEvalRAII)) {}
David Blaikie73726062015-08-12 23:09:24 +00007162
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007163 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007164 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007165 }
George Burgess IV8c892b52016-05-25 22:31:54 +00007166
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007167 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00007168 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007169 };
7170
7171 SmallVector<Job, 16> Queue;
7172
7173 IntExprEvaluator &IntEval;
7174 EvalInfo &Info;
7175 APValue &FinalResult;
7176
7177public:
7178 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
7179 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
7180
7181 /// \brief True if \param E is a binary operator that we are going to handle
7182 /// data recursively.
7183 /// We handle binary operators that are comma, logical, or that have operands
7184 /// with integral or enumeration type.
7185 static bool shouldEnqueue(const BinaryOperator *E) {
7186 return E->getOpcode() == BO_Comma ||
7187 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00007188 (E->isRValue() &&
7189 E->getType()->isIntegralOrEnumerationType() &&
7190 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007191 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00007192 }
7193
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007194 bool Traverse(const BinaryOperator *E) {
7195 enqueue(E);
7196 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00007197 while (!Queue.empty())
7198 process(PrevResult);
7199
7200 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007201
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007202 FinalResult.swap(PrevResult.Val);
7203 return true;
7204 }
7205
7206private:
7207 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
7208 return IntEval.Success(Value, E, Result);
7209 }
7210 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
7211 return IntEval.Success(Value, E, Result);
7212 }
7213 bool Error(const Expr *E) {
7214 return IntEval.Error(E);
7215 }
7216 bool Error(const Expr *E, diag::kind D) {
7217 return IntEval.Error(E, D);
7218 }
7219
7220 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
7221 return Info.CCEDiag(E, D);
7222 }
7223
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007224 // \brief Returns true if visiting the RHS is necessary, false otherwise.
7225 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007226 bool &SuppressRHSDiags);
7227
7228 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7229 const BinaryOperator *E, APValue &Result);
7230
7231 void EvaluateExpr(const Expr *E, EvalResult &Result) {
7232 Result.Failed = !Evaluate(Result.Val, Info, E);
7233 if (Result.Failed)
7234 Result.Val = APValue();
7235 }
7236
Richard Trieuba4d0872012-03-21 23:30:30 +00007237 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007238
7239 void enqueue(const Expr *E) {
7240 E = E->IgnoreParens();
7241 Queue.resize(Queue.size()+1);
7242 Queue.back().E = E;
7243 Queue.back().Kind = Job::AnyExprKind;
7244 }
7245};
7246
Alexander Kornienkoab9db512015-06-22 23:07:51 +00007247}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007248
7249bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007250 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007251 bool &SuppressRHSDiags) {
7252 if (E->getOpcode() == BO_Comma) {
7253 // Ignore LHS but note if we could not evaluate it.
7254 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00007255 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007256 return true;
7257 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007258
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007259 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007260 bool LHSAsBool;
7261 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007262 // We were able to evaluate the LHS, see if we can get away with not
7263 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00007264 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
7265 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007266 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007267 }
7268 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00007269 LHSResult.Failed = true;
7270
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007271 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00007272 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00007273 if (!Info.noteSideEffect())
7274 return false;
7275
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007276 // We can't evaluate the LHS; however, sometimes the result
7277 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7278 // Don't ignore RHS and suppress diagnostics from this arm.
7279 SuppressRHSDiags = true;
7280 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007281
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007282 return true;
7283 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00007284
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007285 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7286 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00007287
George Burgess IVa145e252016-05-25 22:38:36 +00007288 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007289 return false; // Ignore RHS;
7290
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007291 return true;
7292}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007293
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007294bool DataRecursiveIntBinOpEvaluator::
7295 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
7296 const BinaryOperator *E, APValue &Result) {
7297 if (E->getOpcode() == BO_Comma) {
7298 if (RHSResult.Failed)
7299 return false;
7300 Result = RHSResult.Val;
7301 return true;
7302 }
7303
7304 if (E->isLogicalOp()) {
7305 bool lhsResult, rhsResult;
7306 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
7307 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
7308
7309 if (LHSIsOK) {
7310 if (RHSIsOK) {
7311 if (E->getOpcode() == BO_LOr)
7312 return Success(lhsResult || rhsResult, E, Result);
7313 else
7314 return Success(lhsResult && rhsResult, E, Result);
7315 }
7316 } else {
7317 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007318 // We can't evaluate the LHS; however, sometimes the result
7319 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
7320 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007321 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007322 }
7323 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007324
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00007325 return false;
7326 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007327
7328 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
7329 E->getRHS()->getType()->isIntegralOrEnumerationType());
7330
7331 if (LHSResult.Failed || RHSResult.Failed)
7332 return false;
7333
7334 const APValue &LHSVal = LHSResult.Val;
7335 const APValue &RHSVal = RHSResult.Val;
7336
7337 // Handle cases like (unsigned long)&a + 4.
7338 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
7339 Result = LHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007340 CharUnits AdditionalOffset =
7341 CharUnits::fromQuantity(RHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007342 if (E->getOpcode() == BO_Add)
7343 Result.getLValueOffset() += AdditionalOffset;
7344 else
7345 Result.getLValueOffset() -= AdditionalOffset;
7346 return true;
7347 }
7348
7349 // Handle cases like 4 + (unsigned long)&a
7350 if (E->getOpcode() == BO_Add &&
7351 RHSVal.isLValue() && LHSVal.isInt()) {
7352 Result = RHSVal;
Richard Smithe6c19f22013-11-15 02:10:04 +00007353 Result.getLValueOffset() +=
7354 CharUnits::fromQuantity(LHSVal.getInt().getZExtValue());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007355 return true;
7356 }
7357
7358 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
7359 // Handle (intptr_t)&&A - (intptr_t)&&B.
7360 if (!LHSVal.getLValueOffset().isZero() ||
7361 !RHSVal.getLValueOffset().isZero())
7362 return false;
7363 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
7364 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
7365 if (!LHSExpr || !RHSExpr)
7366 return false;
7367 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7368 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7369 if (!LHSAddrExpr || !RHSAddrExpr)
7370 return false;
7371 // Make sure both labels come from the same function.
7372 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7373 RHSAddrExpr->getLabel()->getDeclContext())
7374 return false;
7375 Result = APValue(LHSAddrExpr, RHSAddrExpr);
7376 return true;
7377 }
Richard Smith43e77732013-05-07 04:50:00 +00007378
7379 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007380 if (!LHSVal.isInt() || !RHSVal.isInt())
7381 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00007382
7383 // Set up the width and signedness manually, in case it can't be deduced
7384 // from the operation we're performing.
7385 // FIXME: Don't do this in the cases where we can deduce it.
7386 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
7387 E->getType()->isUnsignedIntegerOrEnumerationType());
7388 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
7389 RHSVal.getInt(), Value))
7390 return false;
7391 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007392}
7393
Richard Trieuba4d0872012-03-21 23:30:30 +00007394void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007395 Job &job = Queue.back();
7396
7397 switch (job.Kind) {
7398 case Job::AnyExprKind: {
7399 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
7400 if (shouldEnqueue(Bop)) {
7401 job.Kind = Job::BinOpKind;
7402 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007403 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007404 }
7405 }
7406
7407 EvaluateExpr(job.E, Result);
7408 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007409 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007410 }
7411
7412 case Job::BinOpKind: {
7413 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007414 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007415 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007416 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007417 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007418 }
7419 if (SuppressRHSDiags)
7420 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00007421 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007422 job.Kind = Job::BinOpVisitedLHSKind;
7423 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00007424 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007425 }
7426
7427 case Job::BinOpVisitedLHSKind: {
7428 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
7429 EvalResult RHS;
7430 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00007431 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007432 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00007433 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007434 }
7435 }
7436
7437 llvm_unreachable("Invalid Job::Kind!");
7438}
7439
George Burgess IV8c892b52016-05-25 22:31:54 +00007440namespace {
7441/// Used when we determine that we should fail, but can keep evaluating prior to
7442/// noting that we had a failure.
7443class DelayedNoteFailureRAII {
7444 EvalInfo &Info;
7445 bool NoteFailure;
7446
7447public:
7448 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
7449 : Info(Info), NoteFailure(NoteFailure) {}
7450 ~DelayedNoteFailureRAII() {
7451 if (NoteFailure) {
7452 bool ContinueAfterFailure = Info.noteFailure();
7453 (void)ContinueAfterFailure;
7454 assert(ContinueAfterFailure &&
7455 "Shouldn't have kept evaluating on failure.");
7456 }
7457 }
7458};
7459}
7460
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007461bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00007462 // We don't call noteFailure immediately because the assignment happens after
7463 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00007464 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007465 return Error(E);
7466
George Burgess IV8c892b52016-05-25 22:31:54 +00007467 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007468 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
7469 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007470
Anders Carlssonacc79812008-11-16 07:17:21 +00007471 QualType LHSTy = E->getLHS()->getType();
7472 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007473
Chandler Carruthb29a7432014-10-11 11:03:30 +00007474 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00007475 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00007476 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00007477 if (E->isAssignmentOp()) {
7478 LValue LV;
7479 EvaluateLValue(E->getLHS(), LV, Info);
7480 LHSOK = false;
7481 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00007482 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
7483 if (LHSOK) {
7484 LHS.makeComplexFloat();
7485 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
7486 }
7487 } else {
7488 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
7489 }
George Burgess IVa145e252016-05-25 22:38:36 +00007490 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007491 return false;
7492
Chandler Carruthb29a7432014-10-11 11:03:30 +00007493 if (E->getRHS()->getType()->isRealFloatingType()) {
7494 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
7495 return false;
7496 RHS.makeComplexFloat();
7497 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
7498 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007499 return false;
7500
7501 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00007502 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007503 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00007504 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007505 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
7506
John McCalle3027922010-08-25 11:45:40 +00007507 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007508 return Success((CR_r == APFloat::cmpEqual &&
7509 CR_i == APFloat::cmpEqual), E);
7510 else {
John McCalle3027922010-08-25 11:45:40 +00007511 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007512 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00007513 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007514 CR_r == APFloat::cmpLessThan ||
7515 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00007516 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00007517 CR_i == APFloat::cmpLessThan ||
7518 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007519 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007520 } else {
John McCalle3027922010-08-25 11:45:40 +00007521 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007522 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
7523 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
7524 else {
John McCalle3027922010-08-25 11:45:40 +00007525 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007526 "Invalid compex comparison.");
7527 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
7528 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
7529 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00007530 }
7531 }
Mike Stump11289f42009-09-09 15:08:12 +00007532
Anders Carlssonacc79812008-11-16 07:17:21 +00007533 if (LHSTy->isRealFloatingType() &&
7534 RHSTy->isRealFloatingType()) {
7535 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00007536
Richard Smith253c2a32012-01-27 01:14:48 +00007537 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007538 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00007539 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007540
Richard Smith253c2a32012-01-27 01:14:48 +00007541 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00007542 return false;
Mike Stump11289f42009-09-09 15:08:12 +00007543
Anders Carlssonacc79812008-11-16 07:17:21 +00007544 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00007545
Anders Carlssonacc79812008-11-16 07:17:21 +00007546 switch (E->getOpcode()) {
7547 default:
David Blaikie83d382b2011-09-23 05:06:16 +00007548 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00007549 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007550 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00007551 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007552 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00007553 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007554 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007555 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00007556 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007557 E);
John McCalle3027922010-08-25 11:45:40 +00007558 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007559 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00007560 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00007561 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00007562 || CR == APFloat::cmpLessThan
7563 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00007564 }
Anders Carlssonacc79812008-11-16 07:17:21 +00007565 }
Mike Stump11289f42009-09-09 15:08:12 +00007566
Eli Friedmana38da572009-04-28 19:17:36 +00007567 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007568 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00007569 LValue LHSValue, RHSValue;
7570
7571 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007572 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007573 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007574
Richard Smith253c2a32012-01-27 01:14:48 +00007575 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007576 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007577
Richard Smith8b3497e2011-10-31 01:37:14 +00007578 // Reject differing bases from the normal codepath; we special-case
7579 // comparisons to null.
7580 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007581 if (E->getOpcode() == BO_Sub) {
7582 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007583 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00007584 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007585 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00007586 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007587 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007588 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007589 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
7590 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
7591 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00007592 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00007593 // Make sure both labels come from the same function.
7594 if (LHSAddrExpr->getLabel()->getDeclContext() !=
7595 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00007596 return Error(E);
7597 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00007598 }
Richard Smith83c68212011-10-31 05:11:32 +00007599 // Inequalities and subtractions between unrelated pointers have
7600 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00007601 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007602 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007603 // A constant address may compare equal to the address of a symbol.
7604 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00007605 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00007606 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
7607 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007608 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007609 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00007610 // distinct addresses. In clang, the result of such a comparison is
7611 // unspecified, so it is not a constant expression. However, we do know
7612 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00007613 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
7614 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007615 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007616 // We can't tell whether weak symbols will end up pointing to the same
7617 // object.
7618 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00007619 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00007620 // We can't compare the address of the start of one object with the
7621 // past-the-end address of another object, per C++ DR1652.
7622 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
7623 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
7624 (RHSValue.Base && RHSValue.Offset.isZero() &&
7625 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
7626 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00007627 // We can't tell whether an object is at the same address as another
7628 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00007629 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
7630 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00007631 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00007632 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00007633 // (Note that clang defaults to -fmerge-all-constants, which can
7634 // lead to inconsistent results for comparisons involving the address
7635 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00007636 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00007637 }
Eli Friedman64004332009-03-23 04:38:34 +00007638
Richard Smith1b470412012-02-01 08:10:20 +00007639 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
7640 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
7641
Richard Smith84f6dcf2012-02-02 01:16:57 +00007642 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
7643 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
7644
John McCalle3027922010-08-25 11:45:40 +00007645 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00007646 // C++11 [expr.add]p6:
7647 // Unless both pointers point to elements of the same array object, or
7648 // one past the last element of the array object, the behavior is
7649 // undefined.
7650 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7651 !AreElementsOfSameArray(getType(LHSValue.Base),
7652 LHSDesignator, RHSDesignator))
7653 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
7654
Chris Lattner882bdf22010-04-20 17:13:14 +00007655 QualType Type = E->getLHS()->getType();
7656 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007657
Richard Smithd62306a2011-11-10 06:34:14 +00007658 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00007659 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00007660 return false;
Eli Friedman64004332009-03-23 04:38:34 +00007661
Richard Smith84c6b3d2013-09-10 21:34:14 +00007662 // As an extension, a type may have zero size (empty struct or union in
7663 // C, array of zero length). Pointer subtraction in such cases has
7664 // undefined behavior, so is not constant.
7665 if (ElementSize.isZero()) {
7666 Info.Diag(E, diag::note_constexpr_pointer_subtraction_zero_size)
7667 << ElementType;
7668 return false;
7669 }
7670
Richard Smith1b470412012-02-01 08:10:20 +00007671 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
7672 // and produce incorrect results when it overflows. Such behavior
7673 // appears to be non-conforming, but is common, so perhaps we should
7674 // assume the standard intended for such cases to be undefined behavior
7675 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00007676
Richard Smith1b470412012-02-01 08:10:20 +00007677 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
7678 // overflow in the final conversion to ptrdiff_t.
7679 APSInt LHS(
7680 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
7681 APSInt RHS(
7682 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
7683 APSInt ElemSize(
7684 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
7685 APSInt TrueResult = (LHS - RHS) / ElemSize;
7686 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
7687
Richard Smith0c6124b2015-12-03 01:36:22 +00007688 if (Result.extend(65) != TrueResult &&
7689 !HandleOverflow(Info, E, TrueResult, E->getType()))
7690 return false;
Richard Smith1b470412012-02-01 08:10:20 +00007691 return Success(Result, E);
7692 }
Richard Smithde21b242012-01-31 06:41:30 +00007693
7694 // C++11 [expr.rel]p3:
7695 // Pointers to void (after pointer conversions) can be compared, with a
7696 // result defined as follows: If both pointers represent the same
7697 // address or are both the null pointer value, the result is true if the
7698 // operator is <= or >= and false otherwise; otherwise the result is
7699 // unspecified.
7700 // We interpret this as applying to pointers to *cv* void.
7701 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00007702 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00007703 CCEDiag(E, diag::note_constexpr_void_comparison);
7704
Richard Smith84f6dcf2012-02-02 01:16:57 +00007705 // C++11 [expr.rel]p2:
7706 // - If two pointers point to non-static data members of the same object,
7707 // or to subobjects or array elements fo such members, recursively, the
7708 // pointer to the later declared member compares greater provided the
7709 // two members have the same access control and provided their class is
7710 // not a union.
7711 // [...]
7712 // - Otherwise pointer comparisons are unspecified.
7713 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
7714 E->isRelationalOp()) {
7715 bool WasArrayIndex;
7716 unsigned Mismatch =
7717 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
7718 RHSDesignator, WasArrayIndex);
7719 // At the point where the designators diverge, the comparison has a
7720 // specified value if:
7721 // - we are comparing array indices
7722 // - we are comparing fields of a union, or fields with the same access
7723 // Otherwise, the result is unspecified and thus the comparison is not a
7724 // constant expression.
7725 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
7726 Mismatch < RHSDesignator.Entries.size()) {
7727 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
7728 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
7729 if (!LF && !RF)
7730 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
7731 else if (!LF)
7732 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7733 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
7734 << RF->getParent() << RF;
7735 else if (!RF)
7736 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
7737 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
7738 << LF->getParent() << LF;
7739 else if (!LF->getParent()->isUnion() &&
7740 LF->getAccess() != RF->getAccess())
7741 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
7742 << LF << LF->getAccess() << RF << RF->getAccess()
7743 << LF->getParent();
7744 }
7745 }
7746
Eli Friedman6c31cb42012-04-16 04:30:08 +00007747 // The comparison here must be unsigned, and performed with the same
7748 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00007749 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
7750 uint64_t CompareLHS = LHSOffset.getQuantity();
7751 uint64_t CompareRHS = RHSOffset.getQuantity();
7752 assert(PtrSize <= 64 && "Unexpected pointer width");
7753 uint64_t Mask = ~0ULL >> (64 - PtrSize);
7754 CompareLHS &= Mask;
7755 CompareRHS &= Mask;
7756
Eli Friedman2f5b7c52012-04-16 19:23:57 +00007757 // If there is a base and this is a relational operator, we can only
7758 // compare pointers within the object in question; otherwise, the result
7759 // depends on where the object is located in memory.
7760 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
7761 QualType BaseTy = getType(LHSValue.Base);
7762 if (BaseTy->isIncompleteType())
7763 return Error(E);
7764 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
7765 uint64_t OffsetLimit = Size.getQuantity();
7766 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
7767 return Error(E);
7768 }
7769
Richard Smith8b3497e2011-10-31 01:37:14 +00007770 switch (E->getOpcode()) {
7771 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00007772 case BO_LT: return Success(CompareLHS < CompareRHS, E);
7773 case BO_GT: return Success(CompareLHS > CompareRHS, E);
7774 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
7775 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
7776 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
7777 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00007778 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007779 }
7780 }
Richard Smith7bb00672012-02-01 01:42:44 +00007781
7782 if (LHSTy->isMemberPointerType()) {
7783 assert(E->isEqualityOp() && "unexpected member pointer operation");
7784 assert(RHSTy->isMemberPointerType() && "invalid comparison");
7785
7786 MemberPtr LHSValue, RHSValue;
7787
7788 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00007789 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00007790 return false;
7791
7792 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
7793 return false;
7794
7795 // C++11 [expr.eq]p2:
7796 // If both operands are null, they compare equal. Otherwise if only one is
7797 // null, they compare unequal.
7798 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
7799 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
7800 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7801 }
7802
7803 // Otherwise if either is a pointer to a virtual member function, the
7804 // result is unspecified.
7805 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
7806 if (MD->isVirtual())
7807 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7808 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
7809 if (MD->isVirtual())
7810 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
7811
7812 // Otherwise they compare equal if and only if they would refer to the
7813 // same member of the same most derived object or the same subobject if
7814 // they were dereferenced with a hypothetical object of the associated
7815 // class type.
7816 bool Equal = LHSValue == RHSValue;
7817 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
7818 }
7819
Richard Smithab44d9b2012-02-14 22:35:28 +00007820 if (LHSTy->isNullPtrType()) {
7821 assert(E->isComparisonOp() && "unexpected nullptr operation");
7822 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
7823 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
7824 // are compared, the result is true of the operator is <=, >= or ==, and
7825 // false otherwise.
7826 BinaryOperator::Opcode Opcode = E->getOpcode();
7827 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
7828 }
7829
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00007830 assert((!LHSTy->isIntegralOrEnumerationType() ||
7831 !RHSTy->isIntegralOrEnumerationType()) &&
7832 "DataRecursiveIntBinOpEvaluator should have handled integral types");
7833 // We can't continue from here for non-integral types.
7834 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00007835}
7836
Peter Collingbournee190dee2011-03-11 19:24:49 +00007837/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
7838/// a result as the expression's type.
7839bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
7840 const UnaryExprOrTypeTraitExpr *E) {
7841 switch(E->getKind()) {
7842 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00007843 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00007844 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007845 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00007846 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00007847 }
Eli Friedman64004332009-03-23 04:38:34 +00007848
Peter Collingbournee190dee2011-03-11 19:24:49 +00007849 case UETT_VecStep: {
7850 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00007851
Peter Collingbournee190dee2011-03-11 19:24:49 +00007852 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00007853 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00007854
Peter Collingbournee190dee2011-03-11 19:24:49 +00007855 // The vec_step built-in functions that take a 3-component
7856 // vector return 4. (OpenCL 1.1 spec 6.11.12)
7857 if (n == 3)
7858 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00007859
Peter Collingbournee190dee2011-03-11 19:24:49 +00007860 return Success(n, E);
7861 } else
7862 return Success(1, E);
7863 }
7864
7865 case UETT_SizeOf: {
7866 QualType SrcTy = E->getTypeOfArgument();
7867 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
7868 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00007869 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
7870 SrcTy = Ref->getPointeeType();
7871
Richard Smithd62306a2011-11-10 06:34:14 +00007872 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00007873 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00007874 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00007875 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007876 }
Alexey Bataev00396512015-07-02 03:40:19 +00007877 case UETT_OpenMPRequiredSimdAlign:
7878 assert(E->isArgumentType());
7879 return Success(
7880 Info.Ctx.toCharUnitsFromBits(
7881 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
7882 .getQuantity(),
7883 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007884 }
7885
7886 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00007887}
7888
Peter Collingbournee9200682011-05-13 03:29:01 +00007889bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00007890 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00007891 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00007892 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007893 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00007894 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00007895 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00007896 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00007897 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00007898 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00007899 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00007900 APSInt IdxResult;
7901 if (!EvaluateInteger(Idx, IdxResult, Info))
7902 return false;
7903 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
7904 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007905 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007906 CurrentType = AT->getElementType();
7907 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
7908 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00007909 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00007910 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007911
James Y Knight7281c352015-12-29 22:31:18 +00007912 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00007913 FieldDecl *MemberDecl = ON.getField();
7914 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007915 if (!RT)
7916 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007917 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007918 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00007919 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00007920 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00007921 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00007922 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00007923 CurrentType = MemberDecl->getType().getNonReferenceType();
7924 break;
7925 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00007926
James Y Knight7281c352015-12-29 22:31:18 +00007927 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00007928 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00007929
James Y Knight7281c352015-12-29 22:31:18 +00007930 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00007931 CXXBaseSpecifier *BaseSpec = ON.getBase();
7932 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00007933 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007934
7935 // Find the layout of the class whose base we are looking into.
7936 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00007937 if (!RT)
7938 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007939 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00007940 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00007941 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
7942
7943 // Find the base class itself.
7944 CurrentType = BaseSpec->getType();
7945 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
7946 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00007947 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00007948
7949 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00007950 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00007951 break;
7952 }
Douglas Gregor882211c2010-04-28 22:16:22 +00007953 }
7954 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007955 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00007956}
7957
Chris Lattnere13042c2008-07-11 19:10:17 +00007958bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00007959 switch (E->getOpcode()) {
7960 default:
7961 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
7962 // See C99 6.6p3.
7963 return Error(E);
7964 case UO_Extension:
7965 // FIXME: Should extension allow i-c-e extension expressions in its scope?
7966 // If so, we could clear the diagnostic ID.
7967 return Visit(E->getSubExpr());
7968 case UO_Plus:
7969 // The result is just the value.
7970 return Visit(E->getSubExpr());
7971 case UO_Minus: {
7972 if (!Visit(E->getSubExpr()))
7973 return false;
7974 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00007975 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00007976 if (Value.isSigned() && Value.isMinSignedValue() &&
7977 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
7978 E->getType()))
7979 return false;
Richard Smithfe800032012-01-31 04:08:20 +00007980 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007981 }
7982 case UO_Not: {
7983 if (!Visit(E->getSubExpr()))
7984 return false;
7985 if (!Result.isInt()) return Error(E);
7986 return Success(~Result.getInt(), E);
7987 }
7988 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00007989 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00007990 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00007991 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007992 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00007993 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007994 }
Anders Carlsson9c181652008-07-08 14:35:21 +00007995}
Mike Stump11289f42009-09-09 15:08:12 +00007996
Chris Lattner477c4be2008-07-12 01:15:53 +00007997/// HandleCast - This is used to evaluate implicit or explicit casts where the
7998/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00007999bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8000 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008001 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008002 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008003
Eli Friedmanc757de22011-03-25 00:43:55 +00008004 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008005 case CK_BaseToDerived:
8006 case CK_DerivedToBase:
8007 case CK_UncheckedDerivedToBase:
8008 case CK_Dynamic:
8009 case CK_ToUnion:
8010 case CK_ArrayToPointerDecay:
8011 case CK_FunctionToPointerDecay:
8012 case CK_NullToPointer:
8013 case CK_NullToMemberPointer:
8014 case CK_BaseToDerivedMemberPointer:
8015 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008016 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008017 case CK_ConstructorConversion:
8018 case CK_IntegralToPointer:
8019 case CK_ToVoid:
8020 case CK_VectorSplat:
8021 case CK_IntegralToFloating:
8022 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008023 case CK_CPointerToObjCPointerCast:
8024 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008025 case CK_AnyPointerToBlockPointerCast:
8026 case CK_ObjCObjectLValueCast:
8027 case CK_FloatingRealToComplex:
8028 case CK_FloatingComplexToReal:
8029 case CK_FloatingComplexCast:
8030 case CK_FloatingComplexToIntegralComplex:
8031 case CK_IntegralRealToComplex:
8032 case CK_IntegralComplexCast:
8033 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008034 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008035 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008036 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008037 case CK_AddressSpaceConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008038 llvm_unreachable("invalid cast kind for integral value");
8039
Eli Friedman9faf2f92011-03-25 19:07:11 +00008040 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008041 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008042 case CK_LValueBitCast:
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:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008048 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008049
Richard Smith4ef685b2012-01-17 21:17:26 +00008050 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008051 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008052 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008053 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008054 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008055
8056 case CK_MemberPointerToBoolean:
8057 case CK_PointerToBoolean:
8058 case CK_IntegralToBoolean:
8059 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008060 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008061 case CK_FloatingComplexToBoolean:
8062 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008063 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008064 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008065 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008066 uint64_t IntResult = BoolResult;
8067 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8068 IntResult = (uint64_t)-1;
8069 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008070 }
8071
Eli Friedmanc757de22011-03-25 00:43:55 +00008072 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008073 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008074 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008075
Eli Friedman742421e2009-02-20 01:15:07 +00008076 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008077 // Allow casts of address-of-label differences if they are no-ops
8078 // or narrowing. (The narrowing case isn't actually guaranteed to
8079 // be constant-evaluatable except in some narrow cases which are hard
8080 // to detect here. We let it through on the assumption the user knows
8081 // what they are doing.)
8082 if (Result.isAddrLabelDiff())
8083 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008084 // Only allow casts of lvalues if they are lossless.
8085 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8086 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008087
Richard Smith911e1422012-01-30 22:27:01 +00008088 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8089 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008090 }
Mike Stump11289f42009-09-09 15:08:12 +00008091
Eli Friedmanc757de22011-03-25 00:43:55 +00008092 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008093 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8094
John McCall45d55e42010-05-07 21:00:08 +00008095 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008096 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00008097 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00008098
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008099 if (LV.getLValueBase()) {
8100 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00008101 // FIXME: Allow a larger integer size than the pointer size, and allow
8102 // narrowing back down to pointer width in subsequent integral casts.
8103 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008104 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008105 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008106
Richard Smithcf74da72011-11-16 07:18:12 +00008107 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00008108 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00008109 return true;
8110 }
8111
Ken Dyck02990832010-01-15 12:37:54 +00008112 APSInt AsInt = Info.Ctx.MakeIntValue(LV.getLValueOffset().getQuantity(),
8113 SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00008114 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008115 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008116
Eli Friedmanc757de22011-03-25 00:43:55 +00008117 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00008118 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008119 if (!EvaluateComplex(SubExpr, C, Info))
8120 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00008121 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00008122 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00008123
Eli Friedmanc757de22011-03-25 00:43:55 +00008124 case CK_FloatingToIntegral: {
8125 APFloat F(0.0);
8126 if (!EvaluateFloat(SubExpr, F, Info))
8127 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00008128
Richard Smith357362d2011-12-13 06:39:58 +00008129 APSInt Value;
8130 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
8131 return false;
8132 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008133 }
8134 }
Mike Stump11289f42009-09-09 15:08:12 +00008135
Eli Friedmanc757de22011-03-25 00:43:55 +00008136 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00008137}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00008138
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008139bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
8140 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008141 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008142 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8143 return false;
8144 if (!LV.isComplexInt())
8145 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008146 return Success(LV.getComplexIntReal(), E);
8147 }
8148
8149 return Visit(E->getSubExpr());
8150}
8151
Eli Friedman4e7a2412009-02-27 04:45:43 +00008152bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008153 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008154 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00008155 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
8156 return false;
8157 if (!LV.isComplexInt())
8158 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00008159 return Success(LV.getComplexIntImag(), E);
8160 }
8161
Richard Smith4a678122011-10-24 18:44:57 +00008162 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00008163 return Success(0, E);
8164}
8165
Douglas Gregor820ba7b2011-01-04 17:33:58 +00008166bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
8167 return Success(E->getPackLength(), E);
8168}
8169
Sebastian Redl5f0180d2010-09-10 20:55:47 +00008170bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
8171 return Success(E->getValue(), E);
8172}
8173
Chris Lattner05706e882008-07-11 18:11:29 +00008174//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00008175// Float Evaluation
8176//===----------------------------------------------------------------------===//
8177
8178namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008179class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008180 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00008181 APFloat &Result;
8182public:
8183 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008184 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00008185
Richard Smith2e312c82012-03-03 22:46:17 +00008186 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008187 Result = V.getFloat();
8188 return true;
8189 }
Eli Friedman24c01542008-08-22 00:06:13 +00008190
Richard Smithfddd3842011-12-30 21:15:51 +00008191 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00008192 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
8193 return true;
8194 }
8195
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008196 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008197
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008198 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00008199 bool VisitBinaryOperator(const BinaryOperator *E);
8200 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008201 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00008202
John McCallb1fb0d32010-05-07 22:08:54 +00008203 bool VisitUnaryReal(const UnaryOperator *E);
8204 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00008205
Richard Smithfddd3842011-12-30 21:15:51 +00008206 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00008207};
8208} // end anonymous namespace
8209
8210static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008211 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008212 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00008213}
8214
Jay Foad39c79802011-01-12 09:06:06 +00008215static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00008216 QualType ResultTy,
8217 const Expr *Arg,
8218 bool SNaN,
8219 llvm::APFloat &Result) {
8220 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
8221 if (!S) return false;
8222
8223 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
8224
8225 llvm::APInt fill;
8226
8227 // Treat empty strings as if they were zero.
8228 if (S->getString().empty())
8229 fill = llvm::APInt(32, 0);
8230 else if (S->getString().getAsInteger(0, fill))
8231 return false;
8232
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00008233 if (Context.getTargetInfo().isNan2008()) {
8234 if (SNaN)
8235 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8236 else
8237 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8238 } else {
8239 // Prior to IEEE 754-2008, architectures were allowed to choose whether
8240 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
8241 // a different encoding to what became a standard in 2008, and for pre-
8242 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
8243 // sNaN. This is now known as "legacy NaN" encoding.
8244 if (SNaN)
8245 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
8246 else
8247 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
8248 }
8249
John McCall16291492010-02-28 13:00:19 +00008250 return true;
8251}
8252
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008253bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00008254 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008255 default:
8256 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8257
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008258 case Builtin::BI__builtin_huge_val:
8259 case Builtin::BI__builtin_huge_valf:
8260 case Builtin::BI__builtin_huge_vall:
8261 case Builtin::BI__builtin_inf:
8262 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008263 case Builtin::BI__builtin_infl: {
8264 const llvm::fltSemantics &Sem =
8265 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00008266 Result = llvm::APFloat::getInf(Sem);
8267 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00008268 }
Mike Stump11289f42009-09-09 15:08:12 +00008269
John McCall16291492010-02-28 13:00:19 +00008270 case Builtin::BI__builtin_nans:
8271 case Builtin::BI__builtin_nansf:
8272 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008273 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8274 true, Result))
8275 return Error(E);
8276 return true;
John McCall16291492010-02-28 13:00:19 +00008277
Chris Lattner0b7282e2008-10-06 06:31:58 +00008278 case Builtin::BI__builtin_nan:
8279 case Builtin::BI__builtin_nanf:
8280 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00008281 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00008282 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00008283 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
8284 false, Result))
8285 return Error(E);
8286 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008287
8288 case Builtin::BI__builtin_fabs:
8289 case Builtin::BI__builtin_fabsf:
8290 case Builtin::BI__builtin_fabsl:
8291 if (!EvaluateFloat(E->getArg(0), Result, Info))
8292 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008293
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008294 if (Result.isNegative())
8295 Result.changeSign();
8296 return true;
8297
Richard Smith8889a3d2013-06-13 06:26:32 +00008298 // FIXME: Builtin::BI__builtin_powi
8299 // FIXME: Builtin::BI__builtin_powif
8300 // FIXME: Builtin::BI__builtin_powil
8301
Mike Stump11289f42009-09-09 15:08:12 +00008302 case Builtin::BI__builtin_copysign:
8303 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008304 case Builtin::BI__builtin_copysignl: {
8305 APFloat RHS(0.);
8306 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
8307 !EvaluateFloat(E->getArg(1), RHS, Info))
8308 return false;
8309 Result.copySign(RHS);
8310 return true;
8311 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008312 }
8313}
8314
John McCallb1fb0d32010-05-07 22:08:54 +00008315bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008316 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8317 ComplexValue CV;
8318 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8319 return false;
8320 Result = CV.FloatReal;
8321 return true;
8322 }
8323
8324 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00008325}
8326
8327bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00008328 if (E->getSubExpr()->getType()->isAnyComplexType()) {
8329 ComplexValue CV;
8330 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
8331 return false;
8332 Result = CV.FloatImag;
8333 return true;
8334 }
8335
Richard Smith4a678122011-10-24 18:44:57 +00008336 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00008337 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
8338 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00008339 return true;
8340}
8341
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008342bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008343 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008344 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008345 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00008346 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00008347 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00008348 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
8349 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008350 Result.changeSign();
8351 return true;
8352 }
8353}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00008354
Eli Friedman24c01542008-08-22 00:06:13 +00008355bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008356 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
8357 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00008358
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00008359 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00008360 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008361 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00008362 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00008363 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
8364 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00008365}
8366
8367bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
8368 Result = E->getValue();
8369 return true;
8370}
8371
Peter Collingbournee9200682011-05-13 03:29:01 +00008372bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
8373 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00008374
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008375 switch (E->getCastKind()) {
8376 default:
Richard Smith11562c52011-10-28 17:51:58 +00008377 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008378
8379 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008380 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00008381 return EvaluateInteger(SubExpr, IntResult, Info) &&
8382 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
8383 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008384 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008385
8386 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008387 if (!Visit(SubExpr))
8388 return false;
Richard Smith357362d2011-12-13 06:39:58 +00008389 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
8390 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00008391 }
John McCalld7646252010-11-14 08:17:51 +00008392
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008393 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00008394 ComplexValue V;
8395 if (!EvaluateComplex(SubExpr, V, Info))
8396 return false;
8397 Result = V.getComplexFloatReal();
8398 return true;
8399 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00008400 }
Eli Friedman9a156e52008-11-12 09:44:48 +00008401}
8402
Eli Friedman24c01542008-08-22 00:06:13 +00008403//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008404// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00008405//===----------------------------------------------------------------------===//
8406
8407namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00008408class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008409 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00008410 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00008411
Anders Carlsson537969c2008-11-16 20:27:53 +00008412public:
John McCall93d91dc2010-05-07 17:22:02 +00008413 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00008414 : ExprEvaluatorBaseTy(info), Result(Result) {}
8415
Richard Smith2e312c82012-03-03 22:46:17 +00008416 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00008417 Result.setFrom(V);
8418 return true;
8419 }
Mike Stump11289f42009-09-09 15:08:12 +00008420
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008421 bool ZeroInitialization(const Expr *E);
8422
Anders Carlsson537969c2008-11-16 20:27:53 +00008423 //===--------------------------------------------------------------------===//
8424 // Visitor Methods
8425 //===--------------------------------------------------------------------===//
8426
Peter Collingbournee9200682011-05-13 03:29:01 +00008427 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00008428 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00008429 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008430 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008431 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008432};
8433} // end anonymous namespace
8434
John McCall93d91dc2010-05-07 17:22:02 +00008435static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
8436 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00008437 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00008438 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00008439}
8440
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008441bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00008442 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008443 if (ElemTy->isRealFloatingType()) {
8444 Result.makeComplexFloat();
8445 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
8446 Result.FloatReal = Zero;
8447 Result.FloatImag = Zero;
8448 } else {
8449 Result.makeComplexInt();
8450 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
8451 Result.IntReal = Zero;
8452 Result.IntImag = Zero;
8453 }
8454 return true;
8455}
8456
Peter Collingbournee9200682011-05-13 03:29:01 +00008457bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
8458 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008459
8460 if (SubExpr->getType()->isRealFloatingType()) {
8461 Result.makeComplexFloat();
8462 APFloat &Imag = Result.FloatImag;
8463 if (!EvaluateFloat(SubExpr, Imag, Info))
8464 return false;
8465
8466 Result.FloatReal = APFloat(Imag.getSemantics());
8467 return true;
8468 } else {
8469 assert(SubExpr->getType()->isIntegerType() &&
8470 "Unexpected imaginary literal.");
8471
8472 Result.makeComplexInt();
8473 APSInt &Imag = Result.IntImag;
8474 if (!EvaluateInteger(SubExpr, Imag, Info))
8475 return false;
8476
8477 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
8478 return true;
8479 }
8480}
8481
Peter Collingbournee9200682011-05-13 03:29:01 +00008482bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008483
John McCallfcef3cf2010-12-14 17:51:41 +00008484 switch (E->getCastKind()) {
8485 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008486 case CK_BaseToDerived:
8487 case CK_DerivedToBase:
8488 case CK_UncheckedDerivedToBase:
8489 case CK_Dynamic:
8490 case CK_ToUnion:
8491 case CK_ArrayToPointerDecay:
8492 case CK_FunctionToPointerDecay:
8493 case CK_NullToPointer:
8494 case CK_NullToMemberPointer:
8495 case CK_BaseToDerivedMemberPointer:
8496 case CK_DerivedToBaseMemberPointer:
8497 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00008498 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00008499 case CK_ConstructorConversion:
8500 case CK_IntegralToPointer:
8501 case CK_PointerToIntegral:
8502 case CK_PointerToBoolean:
8503 case CK_ToVoid:
8504 case CK_VectorSplat:
8505 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008506 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00008507 case CK_IntegralToBoolean:
8508 case CK_IntegralToFloating:
8509 case CK_FloatingToIntegral:
8510 case CK_FloatingToBoolean:
8511 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008512 case CK_CPointerToObjCPointerCast:
8513 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008514 case CK_AnyPointerToBlockPointerCast:
8515 case CK_ObjCObjectLValueCast:
8516 case CK_FloatingComplexToReal:
8517 case CK_FloatingComplexToBoolean:
8518 case CK_IntegralComplexToReal:
8519 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00008520 case CK_ARCProduceObject:
8521 case CK_ARCConsumeObject:
8522 case CK_ARCReclaimReturnedObject:
8523 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008524 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00008525 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008526 case CK_ZeroToOCLEvent:
Richard Smitha23ab512013-05-23 00:30:41 +00008527 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008528 case CK_AddressSpaceConversion:
John McCallfcef3cf2010-12-14 17:51:41 +00008529 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00008530
John McCallfcef3cf2010-12-14 17:51:41 +00008531 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008532 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00008533 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008534 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008535
8536 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008537 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00008538 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008539 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00008540
8541 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008542 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00008543 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008544 return false;
8545
John McCallfcef3cf2010-12-14 17:51:41 +00008546 Result.makeComplexFloat();
8547 Result.FloatImag = APFloat(Real.getSemantics());
8548 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008549 }
8550
John McCallfcef3cf2010-12-14 17:51:41 +00008551 case CK_FloatingComplexCast: {
8552 if (!Visit(E->getSubExpr()))
8553 return false;
8554
8555 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8556 QualType From
8557 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8558
Richard Smith357362d2011-12-13 06:39:58 +00008559 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
8560 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008561 }
8562
8563 case CK_FloatingComplexToIntegralComplex: {
8564 if (!Visit(E->getSubExpr()))
8565 return false;
8566
8567 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8568 QualType From
8569 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8570 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00008571 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
8572 To, Result.IntReal) &&
8573 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
8574 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008575 }
8576
8577 case CK_IntegralRealToComplex: {
8578 APSInt &Real = Result.IntReal;
8579 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
8580 return false;
8581
8582 Result.makeComplexInt();
8583 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
8584 return true;
8585 }
8586
8587 case CK_IntegralComplexCast: {
8588 if (!Visit(E->getSubExpr()))
8589 return false;
8590
8591 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
8592 QualType From
8593 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
8594
Richard Smith911e1422012-01-30 22:27:01 +00008595 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
8596 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008597 return true;
8598 }
8599
8600 case CK_IntegralComplexToFloatingComplex: {
8601 if (!Visit(E->getSubExpr()))
8602 return false;
8603
Ted Kremenek28831752012-08-23 20:46:57 +00008604 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008605 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00008606 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00008607 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00008608 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
8609 To, Result.FloatReal) &&
8610 HandleIntToFloatCast(Info, E, From, Result.IntImag,
8611 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00008612 }
8613 }
8614
8615 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00008616}
8617
John McCall93d91dc2010-05-07 17:22:02 +00008618bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00008619 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00008620 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
8621
Chandler Carrutha216cad2014-10-11 00:57:18 +00008622 // Track whether the LHS or RHS is real at the type system level. When this is
8623 // the case we can simplify our evaluation strategy.
8624 bool LHSReal = false, RHSReal = false;
8625
8626 bool LHSOK;
8627 if (E->getLHS()->getType()->isRealFloatingType()) {
8628 LHSReal = true;
8629 APFloat &Real = Result.FloatReal;
8630 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
8631 if (LHSOK) {
8632 Result.makeComplexFloat();
8633 Result.FloatImag = APFloat(Real.getSemantics());
8634 }
8635 } else {
8636 LHSOK = Visit(E->getLHS());
8637 }
George Burgess IVa145e252016-05-25 22:38:36 +00008638 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00008639 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008640
John McCall93d91dc2010-05-07 17:22:02 +00008641 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008642 if (E->getRHS()->getType()->isRealFloatingType()) {
8643 RHSReal = true;
8644 APFloat &Real = RHS.FloatReal;
8645 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
8646 return false;
8647 RHS.makeComplexFloat();
8648 RHS.FloatImag = APFloat(Real.getSemantics());
8649 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00008650 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008651
Chandler Carrutha216cad2014-10-11 00:57:18 +00008652 assert(!(LHSReal && RHSReal) &&
8653 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008654 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008655 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00008656 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008657 if (Result.isComplexFloat()) {
8658 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
8659 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008660 if (LHSReal)
8661 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8662 else if (!RHSReal)
8663 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
8664 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008665 } else {
8666 Result.getComplexIntReal() += RHS.getComplexIntReal();
8667 Result.getComplexIntImag() += RHS.getComplexIntImag();
8668 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008669 break;
John McCalle3027922010-08-25 11:45:40 +00008670 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008671 if (Result.isComplexFloat()) {
8672 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
8673 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008674 if (LHSReal) {
8675 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
8676 Result.getComplexFloatImag().changeSign();
8677 } else if (!RHSReal) {
8678 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
8679 APFloat::rmNearestTiesToEven);
8680 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00008681 } else {
8682 Result.getComplexIntReal() -= RHS.getComplexIntReal();
8683 Result.getComplexIntImag() -= RHS.getComplexIntImag();
8684 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008685 break;
John McCalle3027922010-08-25 11:45:40 +00008686 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008687 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008688 // This is an implementation of complex multiplication according to the
8689 // constraints laid out in C11 Annex G. The implemantion uses the
8690 // following naming scheme:
8691 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00008692 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008693 APFloat &A = LHS.getComplexFloatReal();
8694 APFloat &B = LHS.getComplexFloatImag();
8695 APFloat &C = RHS.getComplexFloatReal();
8696 APFloat &D = RHS.getComplexFloatImag();
8697 APFloat &ResR = Result.getComplexFloatReal();
8698 APFloat &ResI = Result.getComplexFloatImag();
8699 if (LHSReal) {
8700 assert(!RHSReal && "Cannot have two real operands for a complex op!");
8701 ResR = A * C;
8702 ResI = A * D;
8703 } else if (RHSReal) {
8704 ResR = C * A;
8705 ResI = C * B;
8706 } else {
8707 // In the fully general case, we need to handle NaNs and infinities
8708 // robustly.
8709 APFloat AC = A * C;
8710 APFloat BD = B * D;
8711 APFloat AD = A * D;
8712 APFloat BC = B * C;
8713 ResR = AC - BD;
8714 ResI = AD + BC;
8715 if (ResR.isNaN() && ResI.isNaN()) {
8716 bool Recalc = false;
8717 if (A.isInfinity() || B.isInfinity()) {
8718 A = APFloat::copySign(
8719 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8720 B = APFloat::copySign(
8721 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8722 if (C.isNaN())
8723 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8724 if (D.isNaN())
8725 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8726 Recalc = true;
8727 }
8728 if (C.isInfinity() || D.isInfinity()) {
8729 C = APFloat::copySign(
8730 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8731 D = APFloat::copySign(
8732 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8733 if (A.isNaN())
8734 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8735 if (B.isNaN())
8736 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8737 Recalc = true;
8738 }
8739 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
8740 AD.isInfinity() || BC.isInfinity())) {
8741 if (A.isNaN())
8742 A = APFloat::copySign(APFloat(A.getSemantics()), A);
8743 if (B.isNaN())
8744 B = APFloat::copySign(APFloat(B.getSemantics()), B);
8745 if (C.isNaN())
8746 C = APFloat::copySign(APFloat(C.getSemantics()), C);
8747 if (D.isNaN())
8748 D = APFloat::copySign(APFloat(D.getSemantics()), D);
8749 Recalc = true;
8750 }
8751 if (Recalc) {
8752 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
8753 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
8754 }
8755 }
8756 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008757 } else {
John McCall93d91dc2010-05-07 17:22:02 +00008758 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00008759 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008760 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
8761 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00008762 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00008763 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
8764 LHS.getComplexIntImag() * RHS.getComplexIntReal());
8765 }
8766 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008767 case BO_Div:
8768 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00008769 // This is an implementation of complex division according to the
8770 // constraints laid out in C11 Annex G. The implemantion uses the
8771 // following naming scheme:
8772 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008773 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00008774 APFloat &A = LHS.getComplexFloatReal();
8775 APFloat &B = LHS.getComplexFloatImag();
8776 APFloat &C = RHS.getComplexFloatReal();
8777 APFloat &D = RHS.getComplexFloatImag();
8778 APFloat &ResR = Result.getComplexFloatReal();
8779 APFloat &ResI = Result.getComplexFloatImag();
8780 if (RHSReal) {
8781 ResR = A / C;
8782 ResI = B / C;
8783 } else {
8784 if (LHSReal) {
8785 // No real optimizations we can do here, stub out with zero.
8786 B = APFloat::getZero(A.getSemantics());
8787 }
8788 int DenomLogB = 0;
8789 APFloat MaxCD = maxnum(abs(C), abs(D));
8790 if (MaxCD.isFinite()) {
8791 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00008792 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
8793 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008794 }
8795 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00008796 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
8797 APFloat::rmNearestTiesToEven);
8798 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
8799 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00008800 if (ResR.isNaN() && ResI.isNaN()) {
8801 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
8802 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
8803 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
8804 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
8805 D.isFinite()) {
8806 A = APFloat::copySign(
8807 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
8808 B = APFloat::copySign(
8809 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
8810 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
8811 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
8812 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
8813 C = APFloat::copySign(
8814 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
8815 D = APFloat::copySign(
8816 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
8817 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
8818 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
8819 }
8820 }
8821 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008822 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008823 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
8824 return Error(E, diag::note_expr_divide_by_zero);
8825
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008826 ComplexValue LHS = Result;
8827 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
8828 RHS.getComplexIntImag() * RHS.getComplexIntImag();
8829 Result.getComplexIntReal() =
8830 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
8831 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
8832 Result.getComplexIntImag() =
8833 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
8834 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
8835 }
8836 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008837 }
8838
John McCall93d91dc2010-05-07 17:22:02 +00008839 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00008840}
8841
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008842bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
8843 // Get the operand value into 'Result'.
8844 if (!Visit(E->getSubExpr()))
8845 return false;
8846
8847 switch (E->getOpcode()) {
8848 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008849 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00008850 case UO_Extension:
8851 return true;
8852 case UO_Plus:
8853 // The result is always just the subexpr.
8854 return true;
8855 case UO_Minus:
8856 if (Result.isComplexFloat()) {
8857 Result.getComplexFloatReal().changeSign();
8858 Result.getComplexFloatImag().changeSign();
8859 }
8860 else {
8861 Result.getComplexIntReal() = -Result.getComplexIntReal();
8862 Result.getComplexIntImag() = -Result.getComplexIntImag();
8863 }
8864 return true;
8865 case UO_Not:
8866 if (Result.isComplexFloat())
8867 Result.getComplexFloatImag().changeSign();
8868 else
8869 Result.getComplexIntImag() = -Result.getComplexIntImag();
8870 return true;
8871 }
8872}
8873
Eli Friedmanc4b251d2012-01-10 04:58:17 +00008874bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
8875 if (E->getNumInits() == 2) {
8876 if (E->getType()->isComplexType()) {
8877 Result.makeComplexFloat();
8878 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
8879 return false;
8880 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
8881 return false;
8882 } else {
8883 Result.makeComplexInt();
8884 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
8885 return false;
8886 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
8887 return false;
8888 }
8889 return true;
8890 }
8891 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
8892}
8893
Anders Carlsson537969c2008-11-16 20:27:53 +00008894//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00008895// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
8896// implicit conversion.
8897//===----------------------------------------------------------------------===//
8898
8899namespace {
8900class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00008901 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smitha23ab512013-05-23 00:30:41 +00008902 APValue &Result;
8903public:
8904 AtomicExprEvaluator(EvalInfo &Info, APValue &Result)
8905 : ExprEvaluatorBaseTy(Info), Result(Result) {}
8906
8907 bool Success(const APValue &V, const Expr *E) {
8908 Result = V;
8909 return true;
8910 }
8911
8912 bool ZeroInitialization(const Expr *E) {
8913 ImplicitValueInitExpr VIE(
8914 E->getType()->castAs<AtomicType>()->getValueType());
8915 return Evaluate(Result, Info, &VIE);
8916 }
8917
8918 bool VisitCastExpr(const CastExpr *E) {
8919 switch (E->getCastKind()) {
8920 default:
8921 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8922 case CK_NonAtomicToAtomic:
8923 return Evaluate(Result, Info, E->getSubExpr());
8924 }
8925 }
8926};
8927} // end anonymous namespace
8928
8929static bool EvaluateAtomic(const Expr *E, APValue &Result, EvalInfo &Info) {
8930 assert(E->isRValue() && E->getType()->isAtomicType());
8931 return AtomicExprEvaluator(Info, Result).Visit(E);
8932}
8933
8934//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00008935// Void expression evaluation, primarily for a cast to void on the LHS of a
8936// comma operator
8937//===----------------------------------------------------------------------===//
8938
8939namespace {
8940class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00008941 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00008942public:
8943 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
8944
Richard Smith2e312c82012-03-03 22:46:17 +00008945 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00008946
8947 bool VisitCastExpr(const CastExpr *E) {
8948 switch (E->getCastKind()) {
8949 default:
8950 return ExprEvaluatorBaseTy::VisitCastExpr(E);
8951 case CK_ToVoid:
8952 VisitIgnoredValue(E->getSubExpr());
8953 return true;
8954 }
8955 }
Hal Finkela8443c32014-07-17 14:49:58 +00008956
8957 bool VisitCallExpr(const CallExpr *E) {
8958 switch (E->getBuiltinCallee()) {
8959 default:
8960 return ExprEvaluatorBaseTy::VisitCallExpr(E);
8961 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00008962 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00008963 // The argument is not evaluated!
8964 return true;
8965 }
8966 }
Richard Smith42d3af92011-12-07 00:43:50 +00008967};
8968} // end anonymous namespace
8969
8970static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
8971 assert(E->isRValue() && E->getType()->isVoidType());
8972 return VoidExprEvaluator(Info).Visit(E);
8973}
8974
8975//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00008976// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00008977//===----------------------------------------------------------------------===//
8978
Richard Smith2e312c82012-03-03 22:46:17 +00008979static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00008980 // In C, function designators are not lvalues, but we evaluate them as if they
8981 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00008982 QualType T = E->getType();
8983 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00008984 LValue LV;
8985 if (!EvaluateLValue(E, LV, Info))
8986 return false;
8987 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008988 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008989 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00008990 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008991 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00008992 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008993 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00008994 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00008995 LValue LV;
8996 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00008997 return false;
Richard Smith725810a2011-10-16 21:26:27 +00008998 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00008999 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009000 llvm::APFloat F(0.0);
9001 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009002 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009003 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009004 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009005 ComplexValue C;
9006 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009007 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009008 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009009 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009010 MemberPtr P;
9011 if (!EvaluateMemberPointer(E, P, Info))
9012 return false;
9013 P.moveInto(Result);
9014 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009015 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009016 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009017 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009018 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9019 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009020 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009021 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009022 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009023 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009024 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009025 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9026 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009027 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009028 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009029 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009030 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009031 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009032 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009033 if (!EvaluateVoid(E, Info))
9034 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009035 } else if (T->isAtomicType()) {
9036 if (!EvaluateAtomic(E, Result, Info))
9037 return false;
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009038 } else if (Info.getLangOpts().CPlusPlus11) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00009039 Info.Diag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009040 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009041 } else {
Richard Smithce1ec5e2012-03-15 04:53:45 +00009042 Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009043 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009044 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009045
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009046 return true;
9047}
9048
Richard Smithb228a862012-02-15 02:18:13 +00009049/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9050/// cases, the in-place evaluation is essential, since later initializers for
9051/// an object can indirectly refer to subobjects which were initialized earlier.
9052static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009053 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009054 assert(!E->isValueDependent());
9055
Richard Smith7525ff62013-05-09 07:14:00 +00009056 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009057 return false;
9058
9059 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009060 // Evaluate arrays and record types in-place, so that later initializers can
9061 // refer to earlier-initialized members of the object.
Richard Smithd62306a2011-11-10 06:34:14 +00009062 if (E->getType()->isArrayType())
9063 return EvaluateArray(E, This, Result, Info);
9064 else if (E->getType()->isRecordType())
9065 return EvaluateRecord(E, This, Result, Info);
Richard Smithed5165f2011-11-04 05:33:44 +00009066 }
9067
9068 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +00009069 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +00009070}
9071
Richard Smithf57d8cb2011-12-09 22:58:01 +00009072/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
9073/// lvalue-to-rvalue cast if it is an lvalue.
9074static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +00009075 if (E->getType().isNull())
9076 return false;
9077
Richard Smithfddd3842011-12-30 21:15:51 +00009078 if (!CheckLiteralType(Info, E))
9079 return false;
9080
Richard Smith2e312c82012-03-03 22:46:17 +00009081 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009082 return false;
9083
9084 if (E->isGLValue()) {
9085 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +00009086 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +00009087 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009088 return false;
9089 }
9090
Richard Smith2e312c82012-03-03 22:46:17 +00009091 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00009092 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009093}
Richard Smith11562c52011-10-28 17:51:58 +00009094
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009095static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
9096 const ASTContext &Ctx, bool &IsConst) {
9097 // Fast-path evaluations of integer literals, since we sometimes see files
9098 // containing vast quantities of these.
9099 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
9100 Result.Val = APValue(APSInt(L->getValue(),
9101 L->getType()->isUnsignedIntegerType()));
9102 IsConst = true;
9103 return true;
9104 }
James Dennett0492ef02014-03-14 17:44:10 +00009105
9106 // This case should be rare, but we need to check it before we check on
9107 // the type below.
9108 if (Exp->getType().isNull()) {
9109 IsConst = false;
9110 return true;
9111 }
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009112
9113 // FIXME: Evaluating values of large array and record types can cause
9114 // performance problems. Only do so in C++11 for now.
9115 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
9116 Exp->getType()->isRecordType()) &&
9117 !Ctx.getLangOpts().CPlusPlus11) {
9118 IsConst = false;
9119 return true;
9120 }
9121 return false;
9122}
9123
9124
Richard Smith7b553f12011-10-29 00:50:52 +00009125/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +00009126/// any crazy technique (that has nothing to do with language standards) that
9127/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +00009128/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
9129/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +00009130bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009131 bool IsConst;
9132 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
9133 return IsConst;
9134
Richard Smith6d4c6582013-11-05 22:18:15 +00009135 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009136 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +00009137}
9138
Jay Foad39c79802011-01-12 09:06:06 +00009139bool Expr::EvaluateAsBooleanCondition(bool &Result,
9140 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +00009141 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +00009142 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +00009143 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +00009144}
9145
Richard Smithce8eca52015-12-08 03:21:47 +00009146static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
9147 Expr::SideEffectsKind SEK) {
9148 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
9149 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
9150}
9151
Richard Smith5fab0c92011-12-28 19:48:30 +00009152bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
9153 SideEffectsKind AllowSideEffects) const {
9154 if (!getType()->isIntegralOrEnumerationType())
9155 return false;
9156
Richard Smith11562c52011-10-28 17:51:58 +00009157 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +00009158 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +00009159 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +00009160 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009161
Richard Smith11562c52011-10-28 17:51:58 +00009162 Result = ExprResult.Val.getInt();
9163 return true;
Richard Smithcaf33902011-10-10 18:28:20 +00009164}
9165
Richard Trieube234c32016-04-21 21:04:55 +00009166bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
9167 SideEffectsKind AllowSideEffects) const {
9168 if (!getType()->isRealFloatingType())
9169 return false;
9170
9171 EvalResult ExprResult;
9172 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
9173 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
9174 return false;
9175
9176 Result = ExprResult.Val.getFloat();
9177 return true;
9178}
9179
Jay Foad39c79802011-01-12 09:06:06 +00009180bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +00009181 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +00009182
John McCall45d55e42010-05-07 21:00:08 +00009183 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009184 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
9185 !CheckLValueConstantExpression(Info, getExprLoc(),
9186 Ctx.getLValueReferenceType(getType()), LV))
9187 return false;
9188
Richard Smith2e312c82012-03-03 22:46:17 +00009189 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +00009190 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +00009191}
9192
Richard Smithd0b4dd62011-12-19 06:19:21 +00009193bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
9194 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009195 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +00009196 // FIXME: Evaluating initializers for large array and record types can cause
9197 // performance problems. Only do so in C++11 for now.
9198 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009199 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +00009200 return false;
9201
Richard Smithd0b4dd62011-12-19 06:19:21 +00009202 Expr::EvalStatus EStatus;
9203 EStatus.Diag = &Notes;
9204
Richard Smith0c6124b2015-12-03 01:36:22 +00009205 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
9206 ? EvalInfo::EM_ConstantExpression
9207 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009208 InitInfo.setEvaluatingDecl(VD, Value);
9209
9210 LValue LVal;
9211 LVal.set(VD);
9212
Richard Smithfddd3842011-12-30 21:15:51 +00009213 // C++11 [basic.start.init]p2:
9214 // Variables with static storage duration or thread storage duration shall be
9215 // zero-initialized before any other initialization takes place.
9216 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009217 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +00009218 !VD->getType()->isReferenceType()) {
9219 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +00009220 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +00009221 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +00009222 return false;
9223 }
9224
Richard Smith7525ff62013-05-09 07:14:00 +00009225 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
9226 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +00009227 EStatus.HasSideEffects)
9228 return false;
9229
9230 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
9231 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +00009232}
9233
Richard Smith7b553f12011-10-29 00:50:52 +00009234/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
9235/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +00009236bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +00009237 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +00009238 return EvaluateAsRValue(Result, Ctx) &&
9239 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +00009240}
Anders Carlsson59689ed2008-11-22 21:04:56 +00009241
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009242APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009243 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009244 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +00009245 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +00009246 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +00009247 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +00009248 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009249 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +00009250
Anders Carlsson6736d1a22008-12-19 20:58:05 +00009251 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +00009252}
John McCall864e3962010-05-07 05:32:02 +00009253
Richard Smithe9ff7702013-11-05 22:23:30 +00009254void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009255 bool IsConst;
9256 EvalResult EvalResult;
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009257 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +00009258 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +00009259 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
9260 }
9261}
9262
Richard Smithe6c01442013-06-05 00:46:14 +00009263bool Expr::EvalResult::isGlobalLValue() const {
9264 assert(Val.isLValue());
9265 return IsGlobalLValue(Val.getLValueBase());
9266}
Abramo Bagnaraf8199452010-05-14 17:07:14 +00009267
9268
John McCall864e3962010-05-07 05:32:02 +00009269/// isIntegerConstantExpr - this recursive routine will test if an expression is
9270/// an integer constant expression.
9271
9272/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
9273/// comma, etc
John McCall864e3962010-05-07 05:32:02 +00009274
9275// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +00009276// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
9277// and a (possibly null) SourceLocation indicating the location of the problem.
9278//
John McCall864e3962010-05-07 05:32:02 +00009279// Note that to reduce code duplication, this helper does no evaluation
9280// itself; the caller checks whether the expression is evaluatable, and
9281// in the rare cases where CheckICE actually cares about the evaluated
9282// value, it calls into Evalute.
John McCall864e3962010-05-07 05:32:02 +00009283
Dan Gohman28ade552010-07-26 21:25:24 +00009284namespace {
9285
Richard Smith9e575da2012-12-28 13:25:52 +00009286enum ICEKind {
9287 /// This expression is an ICE.
9288 IK_ICE,
9289 /// This expression is not an ICE, but if it isn't evaluated, it's
9290 /// a legal subexpression for an ICE. This return value is used to handle
9291 /// the comma operator in C99 mode, and non-constant subexpressions.
9292 IK_ICEIfUnevaluated,
9293 /// This expression is not an ICE, and is not a legal subexpression for one.
9294 IK_NotICE
9295};
9296
John McCall864e3962010-05-07 05:32:02 +00009297struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +00009298 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +00009299 SourceLocation Loc;
9300
Richard Smith9e575da2012-12-28 13:25:52 +00009301 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +00009302};
9303
Alexander Kornienkoab9db512015-06-22 23:07:51 +00009304}
Dan Gohman28ade552010-07-26 21:25:24 +00009305
Richard Smith9e575da2012-12-28 13:25:52 +00009306static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
9307
9308static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +00009309
Craig Toppera31a8822013-08-22 07:09:37 +00009310static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009311 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +00009312 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +00009313 !EVResult.Val.isInt())
9314 return ICEDiag(IK_NotICE, E->getLocStart());
9315
John McCall864e3962010-05-07 05:32:02 +00009316 return NoDiag();
9317}
9318
Craig Toppera31a8822013-08-22 07:09:37 +00009319static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +00009320 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +00009321 if (!E->getType()->isIntegralOrEnumerationType())
9322 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009323
9324 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +00009325#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +00009326#define STMT(Node, Base) case Expr::Node##Class:
9327#define EXPR(Node, Base)
9328#include "clang/AST/StmtNodes.inc"
9329 case Expr::PredefinedExprClass:
9330 case Expr::FloatingLiteralClass:
9331 case Expr::ImaginaryLiteralClass:
9332 case Expr::StringLiteralClass:
9333 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +00009334 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +00009335 case Expr::MemberExprClass:
9336 case Expr::CompoundAssignOperatorClass:
9337 case Expr::CompoundLiteralExprClass:
9338 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +00009339 case Expr::DesignatedInitExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +00009340 case Expr::NoInitExprClass:
9341 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +00009342 case Expr::ImplicitValueInitExprClass:
9343 case Expr::ParenListExprClass:
9344 case Expr::VAArgExprClass:
9345 case Expr::AddrLabelExprClass:
9346 case Expr::StmtExprClass:
9347 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +00009348 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +00009349 case Expr::CXXDynamicCastExprClass:
9350 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +00009351 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +00009352 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +00009353 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009354 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +00009355 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009356 case Expr::CXXThisExprClass:
9357 case Expr::CXXThrowExprClass:
9358 case Expr::CXXNewExprClass:
9359 case Expr::CXXDeleteExprClass:
9360 case Expr::CXXPseudoDestructorExprClass:
9361 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +00009362 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +00009363 case Expr::DependentScopeDeclRefExprClass:
9364 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +00009365 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +00009366 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +00009367 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +00009368 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +00009369 case Expr::CXXTemporaryObjectExprClass:
9370 case Expr::CXXUnresolvedConstructExprClass:
9371 case Expr::CXXDependentScopeMemberExprClass:
9372 case Expr::UnresolvedMemberExprClass:
9373 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +00009374 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009375 case Expr::ObjCArrayLiteralClass:
9376 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +00009377 case Expr::ObjCEncodeExprClass:
9378 case Expr::ObjCMessageExprClass:
9379 case Expr::ObjCSelectorExprClass:
9380 case Expr::ObjCProtocolExprClass:
9381 case Expr::ObjCIvarRefExprClass:
9382 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009383 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +00009384 case Expr::ObjCIsaExprClass:
9385 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +00009386 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +00009387 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +00009388 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +00009389 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +00009390 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +00009391 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +00009392 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +00009393 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +00009394 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +00009395 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +00009396 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +00009397 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +00009398 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +00009399 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +00009400 case Expr::CoawaitExprClass:
9401 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +00009402 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +00009403
Richard Smithf137f932014-01-25 20:50:08 +00009404 case Expr::InitListExprClass: {
9405 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
9406 // form "T x = { a };" is equivalent to "T x = a;".
9407 // Unless we're initializing a reference, T is a scalar as it is known to be
9408 // of integral or enumeration type.
9409 if (E->isRValue())
9410 if (cast<InitListExpr>(E)->getNumInits() == 1)
9411 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
9412 return ICEDiag(IK_NotICE, E->getLocStart());
9413 }
9414
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009415 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +00009416 case Expr::GNUNullExprClass:
9417 // GCC considers the GNU __null value to be an integral constant expression.
9418 return NoDiag();
9419
John McCall7c454bb2011-07-15 05:09:51 +00009420 case Expr::SubstNonTypeTemplateParmExprClass:
9421 return
9422 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
9423
John McCall864e3962010-05-07 05:32:02 +00009424 case Expr::ParenExprClass:
9425 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +00009426 case Expr::GenericSelectionExprClass:
9427 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009428 case Expr::IntegerLiteralClass:
9429 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +00009430 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +00009431 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +00009432 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +00009433 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +00009434 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +00009435 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +00009436 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +00009437 return NoDiag();
9438 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +00009439 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +00009440 // C99 6.6/3 allows function calls within unevaluated subexpressions of
9441 // constant expressions, but they can never be ICEs because an ICE cannot
9442 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +00009443 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +00009444 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +00009445 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009446 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009447 }
Richard Smith6365c912012-02-24 22:12:32 +00009448 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009449 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
9450 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +00009451 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +00009452 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +00009453 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +00009454 // Parameter variables are never constants. Without this check,
9455 // getAnyInitializer() can find a default argument, which leads
9456 // to chaos.
9457 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +00009458 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009459
9460 // C++ 7.1.5.1p2
9461 // A variable of non-volatile const-qualified integral or enumeration
9462 // type initialized by an ICE can be used in ICEs.
9463 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +00009464 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +00009465 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +00009466
Richard Smithd0b4dd62011-12-19 06:19:21 +00009467 const VarDecl *VD;
9468 // Look for a declaration of this variable that has an initializer, and
9469 // check whether it is an ICE.
9470 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
9471 return NoDiag();
9472 else
Richard Smith9e575da2012-12-28 13:25:52 +00009473 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +00009474 }
9475 }
Richard Smith9e575da2012-12-28 13:25:52 +00009476 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +00009477 }
John McCall864e3962010-05-07 05:32:02 +00009478 case Expr::UnaryOperatorClass: {
9479 const UnaryOperator *Exp = cast<UnaryOperator>(E);
9480 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009481 case UO_PostInc:
9482 case UO_PostDec:
9483 case UO_PreInc:
9484 case UO_PreDec:
9485 case UO_AddrOf:
9486 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +00009487 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +00009488 // C99 6.6/3 allows increment and decrement within unevaluated
9489 // subexpressions of constant expressions, but they can never be ICEs
9490 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009491 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +00009492 case UO_Extension:
9493 case UO_LNot:
9494 case UO_Plus:
9495 case UO_Minus:
9496 case UO_Not:
9497 case UO_Real:
9498 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +00009499 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009500 }
Richard Smith9e575da2012-12-28 13:25:52 +00009501
John McCall864e3962010-05-07 05:32:02 +00009502 // OffsetOf falls through here.
9503 }
9504 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +00009505 // Note that per C99, offsetof must be an ICE. And AFAIK, using
9506 // EvaluateAsRValue matches the proposed gcc behavior for cases like
9507 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
9508 // compliance: we should warn earlier for offsetof expressions with
9509 // array subscripts that aren't ICEs, and if the array subscripts
9510 // are ICEs, the value of the offsetof must be an integer constant.
9511 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009512 }
Peter Collingbournee190dee2011-03-11 19:24:49 +00009513 case Expr::UnaryExprOrTypeTraitExprClass: {
9514 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
9515 if ((Exp->getKind() == UETT_SizeOf) &&
9516 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +00009517 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009518 return NoDiag();
9519 }
9520 case Expr::BinaryOperatorClass: {
9521 const BinaryOperator *Exp = cast<BinaryOperator>(E);
9522 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +00009523 case BO_PtrMemD:
9524 case BO_PtrMemI:
9525 case BO_Assign:
9526 case BO_MulAssign:
9527 case BO_DivAssign:
9528 case BO_RemAssign:
9529 case BO_AddAssign:
9530 case BO_SubAssign:
9531 case BO_ShlAssign:
9532 case BO_ShrAssign:
9533 case BO_AndAssign:
9534 case BO_XorAssign:
9535 case BO_OrAssign:
Richard Smith62f65952011-10-24 22:35:48 +00009536 // C99 6.6/3 allows assignments within unevaluated subexpressions of
9537 // constant expressions, but they can never be ICEs because an ICE cannot
9538 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +00009539 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009540
John McCalle3027922010-08-25 11:45:40 +00009541 case BO_Mul:
9542 case BO_Div:
9543 case BO_Rem:
9544 case BO_Add:
9545 case BO_Sub:
9546 case BO_Shl:
9547 case BO_Shr:
9548 case BO_LT:
9549 case BO_GT:
9550 case BO_LE:
9551 case BO_GE:
9552 case BO_EQ:
9553 case BO_NE:
9554 case BO_And:
9555 case BO_Xor:
9556 case BO_Or:
9557 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +00009558 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9559 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +00009560 if (Exp->getOpcode() == BO_Div ||
9561 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +00009562 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +00009563 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +00009564 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +00009565 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009566 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +00009567 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009568 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +00009569 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +00009570 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +00009571 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009572 }
9573 }
9574 }
John McCalle3027922010-08-25 11:45:40 +00009575 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +00009576 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +00009577 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
9578 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +00009579 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
9580 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009581 } else {
9582 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +00009583 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +00009584 }
9585 }
Richard Smith9e575da2012-12-28 13:25:52 +00009586 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009587 }
John McCalle3027922010-08-25 11:45:40 +00009588 case BO_LAnd:
9589 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +00009590 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
9591 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009592 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +00009593 // Rare case where the RHS has a comma "side-effect"; we need
9594 // to actually check the condition to see whether the side
9595 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +00009596 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +00009597 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +00009598 return RHSResult;
9599 return NoDiag();
9600 }
9601
Richard Smith9e575da2012-12-28 13:25:52 +00009602 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +00009603 }
9604 }
9605 }
9606 case Expr::ImplicitCastExprClass:
9607 case Expr::CStyleCastExprClass:
9608 case Expr::CXXFunctionalCastExprClass:
9609 case Expr::CXXStaticCastExprClass:
9610 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +00009611 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +00009612 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +00009613 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +00009614 if (isa<ExplicitCastExpr>(E)) {
9615 if (const FloatingLiteral *FL
9616 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
9617 unsigned DestWidth = Ctx.getIntWidth(E->getType());
9618 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
9619 APSInt IgnoredVal(DestWidth, !DestSigned);
9620 bool Ignored;
9621 // If the value does not fit in the destination type, the behavior is
9622 // undefined, so we are not required to treat it as a constant
9623 // expression.
9624 if (FL->getValue().convertToInteger(IgnoredVal,
9625 llvm::APFloat::rmTowardZero,
9626 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +00009627 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +00009628 return NoDiag();
9629 }
9630 }
Eli Friedman76d4e432011-09-29 21:49:34 +00009631 switch (cast<CastExpr>(E)->getCastKind()) {
9632 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009633 case CK_AtomicToNonAtomic:
9634 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +00009635 case CK_NoOp:
9636 case CK_IntegralToBoolean:
9637 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +00009638 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +00009639 default:
Richard Smith9e575da2012-12-28 13:25:52 +00009640 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +00009641 }
John McCall864e3962010-05-07 05:32:02 +00009642 }
John McCallc07a0c72011-02-17 10:25:35 +00009643 case Expr::BinaryConditionalOperatorClass: {
9644 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
9645 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009646 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +00009647 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009648 if (FalseResult.Kind == IK_NotICE) return FalseResult;
9649 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
9650 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +00009651 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +00009652 return FalseResult;
9653 }
John McCall864e3962010-05-07 05:32:02 +00009654 case Expr::ConditionalOperatorClass: {
9655 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
9656 // If the condition (ignoring parens) is a __builtin_constant_p call,
9657 // then only the true side is actually considered in an integer constant
9658 // expression, and it is fully evaluated. This is an important GNU
9659 // extension. See GCC PR38377 for discussion.
9660 if (const CallExpr *CallCE
9661 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00009662 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +00009663 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +00009664 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +00009665 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009666 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009667
Richard Smithf57d8cb2011-12-09 22:58:01 +00009668 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
9669 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +00009670
Richard Smith9e575da2012-12-28 13:25:52 +00009671 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009672 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009673 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +00009674 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009675 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +00009676 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +00009677 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +00009678 return NoDiag();
9679 // Rare case where the diagnostics depend on which side is evaluated
9680 // Note that if we get here, CondResult is 0, and at least one of
9681 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +00009682 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +00009683 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +00009684 return TrueResult;
9685 }
9686 case Expr::CXXDefaultArgExprClass:
9687 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +00009688 case Expr::CXXDefaultInitExprClass:
9689 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009690 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +00009691 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +00009692 }
9693 }
9694
David Blaikiee4d798f2012-01-20 21:50:17 +00009695 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +00009696}
9697
Richard Smithf57d8cb2011-12-09 22:58:01 +00009698/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +00009699static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009700 const Expr *E,
9701 llvm::APSInt *Value,
9702 SourceLocation *Loc) {
9703 if (!E->getType()->isIntegralOrEnumerationType()) {
9704 if (Loc) *Loc = E->getExprLoc();
9705 return false;
9706 }
9707
Richard Smith66e05fe2012-01-18 05:21:49 +00009708 APValue Result;
9709 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +00009710 return false;
9711
Richard Smith98710fc2014-11-13 23:03:19 +00009712 if (!Result.isInt()) {
9713 if (Loc) *Loc = E->getExprLoc();
9714 return false;
9715 }
9716
Richard Smith66e05fe2012-01-18 05:21:49 +00009717 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +00009718 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009719}
9720
Craig Toppera31a8822013-08-22 07:09:37 +00009721bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
9722 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009723 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +00009724 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +00009725
Richard Smith9e575da2012-12-28 13:25:52 +00009726 ICEDiag D = CheckICE(this, Ctx);
9727 if (D.Kind != IK_ICE) {
9728 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +00009729 return false;
9730 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00009731 return true;
9732}
9733
Craig Toppera31a8822013-08-22 07:09:37 +00009734bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +00009735 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009736 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +00009737 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
9738
9739 if (!isIntegerConstantExpr(Ctx, Loc))
9740 return false;
Richard Smith5c40f092015-12-04 03:00:44 +00009741 // The only possible side-effects here are due to UB discovered in the
9742 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
9743 // required to treat the expression as an ICE, so we produce the folded
9744 // value.
9745 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +00009746 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +00009747 return true;
9748}
Richard Smith66e05fe2012-01-18 05:21:49 +00009749
Craig Toppera31a8822013-08-22 07:09:37 +00009750bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +00009751 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +00009752}
9753
Craig Toppera31a8822013-08-22 07:09:37 +00009754bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +00009755 SourceLocation *Loc) const {
9756 // We support this checking in C++98 mode in order to diagnose compatibility
9757 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +00009758 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +00009759
Richard Smith98a0a492012-02-14 21:38:30 +00009760 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +00009761 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009762 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +00009763 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +00009764 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +00009765
9766 APValue Scratch;
9767 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
9768
9769 if (!Diags.empty()) {
9770 IsConstExpr = false;
9771 if (Loc) *Loc = Diags[0].first;
9772 } else if (!IsConstExpr) {
9773 // FIXME: This shouldn't happen.
9774 if (Loc) *Loc = getExprLoc();
9775 }
9776
9777 return IsConstExpr;
9778}
Richard Smith253c2a32012-01-27 01:14:48 +00009779
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009780bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
9781 const FunctionDecl *Callee,
Craig Topper00bbdcf2014-06-28 23:22:23 +00009782 ArrayRef<const Expr*> Args) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009783 Expr::EvalStatus Status;
9784 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
9785
9786 ArgVector ArgValues(Args.size());
9787 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
9788 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +00009789 if ((*I)->isValueDependent() ||
9790 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009791 // If evaluation fails, throw away the argument entirely.
9792 ArgValues[I - Args.begin()] = APValue();
9793 if (Info.EvalStatus.HasSideEffects)
9794 return false;
9795 }
9796
9797 // Build fake call to Callee.
Craig Topper36250ad2014-05-12 05:36:57 +00009798 CallStackFrame Frame(Info, Callee->getLocation(), Callee, /*This*/nullptr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009799 ArgValues.data());
9800 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
9801}
9802
Richard Smith253c2a32012-01-27 01:14:48 +00009803bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +00009804 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +00009805 PartialDiagnosticAt> &Diags) {
9806 // FIXME: It would be useful to check constexpr function templates, but at the
9807 // moment the constant expression evaluator cannot cope with the non-rigorous
9808 // ASTs which we build for dependent expressions.
9809 if (FD->isDependentContext())
9810 return true;
9811
9812 Expr::EvalStatus Status;
9813 Status.Diag = &Diags;
9814
Richard Smith6d4c6582013-11-05 22:18:15 +00009815 EvalInfo Info(FD->getASTContext(), Status,
9816 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +00009817
9818 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +00009819 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +00009820
Richard Smith7525ff62013-05-09 07:14:00 +00009821 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +00009822 // is a temporary being used as the 'this' pointer.
9823 LValue This;
9824 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +00009825 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +00009826
Richard Smith253c2a32012-01-27 01:14:48 +00009827 ArrayRef<const Expr*> Args;
9828
Richard Smith2e312c82012-03-03 22:46:17 +00009829 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +00009830 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
9831 // Evaluate the call as a constant initializer, to allow the construction
9832 // of objects of non-literal types.
9833 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +00009834 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
9835 } else {
9836 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +00009837 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +00009838 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +00009839 }
Richard Smith253c2a32012-01-27 01:14:48 +00009840
9841 return Diags.empty();
9842}
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009843
9844bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
9845 const FunctionDecl *FD,
9846 SmallVectorImpl<
9847 PartialDiagnosticAt> &Diags) {
9848 Expr::EvalStatus Status;
9849 Status.Diag = &Diags;
9850
9851 EvalInfo Info(FD->getASTContext(), Status,
9852 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
9853
9854 // Fabricate a call stack frame to give the arguments a plausible cover story.
9855 ArrayRef<const Expr*> Args;
9856 ArgVector ArgValues(0);
9857 bool Success = EvaluateArgs(Args, ArgValues, Info);
9858 (void)Success;
9859 assert(Success &&
9860 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +00009861 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +00009862
9863 APValue ResultScratch;
9864 Evaluate(ResultScratch, Info, E);
9865 return Diags.empty();
9866}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00009867
9868bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
9869 unsigned Type) const {
9870 if (!getType()->isPointerType())
9871 return false;
9872
9873 Expr::EvalStatus Status;
9874 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
9875 return ::tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
9876}