blob: 9c9eeb79b40a48d9d50efb0eb6366ed053964235 [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"
Benjamin Kramer444a1302012-12-01 17:12:56 +000047#include "llvm/Support/raw_ostream.h"
Mike Stump2346cd22009-05-30 03:56:50 +000048#include <cstring>
Richard Smithc8042322012-02-01 05:53:12 +000049#include <functional>
Mike Stump2346cd22009-05-30 03:56:50 +000050
Anders Carlsson7a241ba2008-07-03 04:20:39 +000051using namespace clang;
Chris Lattner05706e882008-07-11 18:11:29 +000052using llvm::APSInt;
Eli Friedman24c01542008-08-22 00:06:13 +000053using llvm::APFloat;
Anders Carlsson7a241ba2008-07-03 04:20:39 +000054
Richard Smithb228a862012-02-15 02:18:13 +000055static bool IsGlobalLValue(APValue::LValueBase B);
56
John McCall93d91dc2010-05-07 17:22:02 +000057namespace {
Richard Smithd62306a2011-11-10 06:34:14 +000058 struct LValue;
Richard Smith254a73d2011-10-28 22:34:42 +000059 struct CallStackFrame;
Richard Smith4e4c78ff2011-10-31 05:52:43 +000060 struct EvalInfo;
Richard Smith254a73d2011-10-28 22:34:42 +000061
Richard Smithb228a862012-02-15 02:18:13 +000062 static QualType getType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +000063 if (!B) return QualType();
64 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>())
Richard Smith6f4f0f12017-10-20 22:56:25 +000065 // FIXME: It's unclear where we're supposed to take the type from, and
66 // this actually matters for arrays of unknown bound. Using the type of
67 // the most recent declaration isn't clearly correct in general. Eg:
68 //
69 // extern int arr[]; void f() { extern int arr[3]; };
70 // constexpr int *p = &arr[1]; // valid?
71 return cast<ValueDecl>(D->getMostRecentDecl())->getType();
Richard Smith84401042013-06-03 05:03:02 +000072
73 const Expr *Base = B.get<const Expr*>();
74
75 // For a materialized temporary, the type of the temporary we materialized
76 // may not be the type of the expression.
77 if (const MaterializeTemporaryExpr *MTE =
78 dyn_cast<MaterializeTemporaryExpr>(Base)) {
79 SmallVector<const Expr *, 2> CommaLHSs;
80 SmallVector<SubobjectAdjustment, 2> Adjustments;
81 const Expr *Temp = MTE->GetTemporaryExpr();
82 const Expr *Inner = Temp->skipRValueSubobjectAdjustments(CommaLHSs,
83 Adjustments);
84 // Keep any cv-qualifiers from the reference if we generated a temporary
Richard Smithb8c0f552016-12-09 18:49:13 +000085 // for it directly. Otherwise use the type after adjustment.
86 if (!Adjustments.empty())
Richard Smith84401042013-06-03 05:03:02 +000087 return Inner->getType();
88 }
89
90 return Base->getType();
Richard Smithce40ad62011-11-12 22:28:03 +000091 }
92
Richard Smithd62306a2011-11-10 06:34:14 +000093 /// Get an LValue path entry, which is known to not be an array index, as a
Richard Smith84f6dcf2012-02-02 01:16:57 +000094 /// field or base class.
Richard Smithb228a862012-02-15 02:18:13 +000095 static
Richard Smith84f6dcf2012-02-02 01:16:57 +000096 APValue::BaseOrMemberType getAsBaseOrMember(APValue::LValuePathEntry E) {
Richard Smithd62306a2011-11-10 06:34:14 +000097 APValue::BaseOrMemberType Value;
98 Value.setFromOpaqueValue(E.BaseOrMember);
Richard Smith84f6dcf2012-02-02 01:16:57 +000099 return Value;
100 }
101
102 /// Get an LValue path entry, which is known to not be an array index, as a
103 /// field declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000104 static const FieldDecl *getAsField(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000105 return dyn_cast<FieldDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000106 }
107 /// Get an LValue path entry, which is known to not be an array index, as a
108 /// base class declaration.
Richard Smithb228a862012-02-15 02:18:13 +0000109 static const CXXRecordDecl *getAsBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000110 return dyn_cast<CXXRecordDecl>(getAsBaseOrMember(E).getPointer());
Richard Smithd62306a2011-11-10 06:34:14 +0000111 }
112 /// Determine whether this LValue path entry for a base class names a virtual
113 /// base class.
Richard Smithb228a862012-02-15 02:18:13 +0000114 static bool isVirtualBaseClass(APValue::LValuePathEntry E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +0000115 return getAsBaseOrMember(E).getInt();
Richard Smithd62306a2011-11-10 06:34:14 +0000116 }
117
George Burgess IVe3763372016-12-22 02:50:20 +0000118 /// Given a CallExpr, try to get the alloc_size attribute. May return null.
119 static const AllocSizeAttr *getAllocSizeAttr(const CallExpr *CE) {
120 const FunctionDecl *Callee = CE->getDirectCallee();
121 return Callee ? Callee->getAttr<AllocSizeAttr>() : nullptr;
122 }
123
124 /// Attempts to unwrap a CallExpr (with an alloc_size attribute) from an Expr.
125 /// This will look through a single cast.
126 ///
127 /// Returns null if we couldn't unwrap a function with alloc_size.
128 static const CallExpr *tryUnwrapAllocSizeCall(const Expr *E) {
129 if (!E->getType()->isPointerType())
130 return nullptr;
131
132 E = E->IgnoreParens();
133 // If we're doing a variable assignment from e.g. malloc(N), there will
134 // probably be a cast of some kind. Ignore it.
135 if (const auto *Cast = dyn_cast<CastExpr>(E))
136 E = Cast->getSubExpr()->IgnoreParens();
137
138 if (const auto *CE = dyn_cast<CallExpr>(E))
139 return getAllocSizeAttr(CE) ? CE : nullptr;
140 return nullptr;
141 }
142
143 /// Determines whether or not the given Base contains a call to a function
144 /// with the alloc_size attribute.
145 static bool isBaseAnAllocSizeCall(APValue::LValueBase Base) {
146 const auto *E = Base.dyn_cast<const Expr *>();
147 return E && E->getType()->isPointerType() && tryUnwrapAllocSizeCall(E);
148 }
149
Richard Smith6f4f0f12017-10-20 22:56:25 +0000150 /// The bound to claim that an array of unknown bound has.
151 /// The value in MostDerivedArraySize is undefined in this case. So, set it
152 /// to an arbitrary value that's likely to loudly break things if it's used.
153 static const uint64_t AssumedSizeForUnsizedArray =
154 std::numeric_limits<uint64_t>::max() / 2;
155
George Burgess IVe3763372016-12-22 02:50:20 +0000156 /// Determines if an LValue with the given LValueBase will have an unsized
157 /// array in its designator.
Richard Smitha8105bc2012-01-06 16:39:00 +0000158 /// Find the path length and type of the most-derived subobject in the given
159 /// path, and find the size of the containing array, if any.
George Burgess IVe3763372016-12-22 02:50:20 +0000160 static unsigned
161 findMostDerivedSubobject(ASTContext &Ctx, APValue::LValueBase Base,
162 ArrayRef<APValue::LValuePathEntry> Path,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000163 uint64_t &ArraySize, QualType &Type, bool &IsArray,
164 bool &FirstEntryIsUnsizedArray) {
George Burgess IVe3763372016-12-22 02:50:20 +0000165 // This only accepts LValueBases from APValues, and APValues don't support
166 // arrays that lack size info.
167 assert(!isBaseAnAllocSizeCall(Base) &&
168 "Unsized arrays shouldn't appear here");
Richard Smitha8105bc2012-01-06 16:39:00 +0000169 unsigned MostDerivedLength = 0;
George Burgess IVe3763372016-12-22 02:50:20 +0000170 Type = getType(Base);
171
Richard Smith80815602011-11-07 05:07:52 +0000172 for (unsigned I = 0, N = Path.size(); I != N; ++I) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000173 if (Type->isArrayType()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000174 const ArrayType *AT = Ctx.getAsArrayType(Type);
175 Type = AT->getElementType();
Richard Smitha8105bc2012-01-06 16:39:00 +0000176 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000177 IsArray = true;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000178
179 if (auto *CAT = dyn_cast<ConstantArrayType>(AT)) {
180 ArraySize = CAT->getSize().getZExtValue();
181 } else {
182 assert(I == 0 && "unexpected unsized array designator");
183 FirstEntryIsUnsizedArray = true;
184 ArraySize = AssumedSizeForUnsizedArray;
185 }
Richard Smith66c96992012-02-18 22:04:06 +0000186 } else if (Type->isAnyComplexType()) {
187 const ComplexType *CT = Type->castAs<ComplexType>();
188 Type = CT->getElementType();
189 ArraySize = 2;
190 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000191 IsArray = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000192 } else if (const FieldDecl *FD = getAsField(Path[I])) {
193 Type = FD->getType();
194 ArraySize = 0;
195 MostDerivedLength = I + 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000196 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000197 } else {
Richard Smith80815602011-11-07 05:07:52 +0000198 // Path[I] describes a base class.
Richard Smitha8105bc2012-01-06 16:39:00 +0000199 ArraySize = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +0000200 IsArray = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000201 }
Richard Smith80815602011-11-07 05:07:52 +0000202 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000203 return MostDerivedLength;
Richard Smith80815602011-11-07 05:07:52 +0000204 }
205
Richard Smitha8105bc2012-01-06 16:39:00 +0000206 // The order of this enum is important for diagnostics.
207 enum CheckSubobjectKind {
Richard Smith47b34932012-02-01 02:39:43 +0000208 CSK_Base, CSK_Derived, CSK_Field, CSK_ArrayToPointer, CSK_ArrayIndex,
Richard Smith66c96992012-02-18 22:04:06 +0000209 CSK_This, CSK_Real, CSK_Imag
Richard Smitha8105bc2012-01-06 16:39:00 +0000210 };
211
Richard Smith96e0c102011-11-04 02:25:55 +0000212 /// A path from a glvalue to a subobject of that glvalue.
213 struct SubobjectDesignator {
214 /// True if the subobject was named in a manner not supported by C++11. Such
215 /// lvalues can still be folded, but they are not core constant expressions
216 /// and we cannot perform lvalue-to-rvalue conversions on them.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000217 unsigned Invalid : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000218
Richard Smitha8105bc2012-01-06 16:39:00 +0000219 /// Is this a pointer one past the end of an object?
Akira Hatanaka3a944772016-06-30 00:07:17 +0000220 unsigned IsOnePastTheEnd : 1;
Richard Smith96e0c102011-11-04 02:25:55 +0000221
Daniel Jasperffdee092017-05-02 19:21:42 +0000222 /// Indicator of whether the first entry is an unsized array.
223 unsigned FirstEntryIsAnUnsizedArray : 1;
George Burgess IVe3763372016-12-22 02:50:20 +0000224
George Burgess IVa51c4072015-10-16 01:49:01 +0000225 /// Indicator of whether the most-derived object is an array element.
Akira Hatanaka3a944772016-06-30 00:07:17 +0000226 unsigned MostDerivedIsArrayElement : 1;
George Burgess IVa51c4072015-10-16 01:49:01 +0000227
Richard Smitha8105bc2012-01-06 16:39:00 +0000228 /// The length of the path to the most-derived object of which this is a
229 /// subobject.
George Burgess IVe3763372016-12-22 02:50:20 +0000230 unsigned MostDerivedPathLength : 28;
Richard Smitha8105bc2012-01-06 16:39:00 +0000231
George Burgess IVa51c4072015-10-16 01:49:01 +0000232 /// The size of the array of which the most-derived object is an element.
233 /// This will always be 0 if the most-derived object is not an array
234 /// element. 0 is not an indicator of whether or not the most-derived object
235 /// is an array, however, because 0-length arrays are allowed.
George Burgess IVe3763372016-12-22 02:50:20 +0000236 ///
237 /// If the current array is an unsized array, the value of this is
238 /// undefined.
Richard Smitha8105bc2012-01-06 16:39:00 +0000239 uint64_t MostDerivedArraySize;
240
241 /// The type of the most derived object referred to by this address.
242 QualType MostDerivedType;
Richard Smith96e0c102011-11-04 02:25:55 +0000243
Richard Smith80815602011-11-07 05:07:52 +0000244 typedef APValue::LValuePathEntry PathEntry;
245
Richard Smith96e0c102011-11-04 02:25:55 +0000246 /// The entries on the path from the glvalue to the designated subobject.
247 SmallVector<PathEntry, 8> Entries;
248
Richard Smitha8105bc2012-01-06 16:39:00 +0000249 SubobjectDesignator() : Invalid(true) {}
Richard Smith96e0c102011-11-04 02:25:55 +0000250
Richard Smitha8105bc2012-01-06 16:39:00 +0000251 explicit SubobjectDesignator(QualType T)
George Burgess IVa51c4072015-10-16 01:49:01 +0000252 : Invalid(false), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000253 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000254 MostDerivedPathLength(0), MostDerivedArraySize(0),
255 MostDerivedType(T) {}
Richard Smitha8105bc2012-01-06 16:39:00 +0000256
257 SubobjectDesignator(ASTContext &Ctx, const APValue &V)
George Burgess IVa51c4072015-10-16 01:49:01 +0000258 : Invalid(!V.isLValue() || !V.hasLValuePath()), IsOnePastTheEnd(false),
Daniel Jasperffdee092017-05-02 19:21:42 +0000259 FirstEntryIsAnUnsizedArray(false), MostDerivedIsArrayElement(false),
George Burgess IVe3763372016-12-22 02:50:20 +0000260 MostDerivedPathLength(0), MostDerivedArraySize(0) {
261 assert(V.isLValue() && "Non-LValue used to make an LValue designator?");
Richard Smith80815602011-11-07 05:07:52 +0000262 if (!Invalid) {
Richard Smitha8105bc2012-01-06 16:39:00 +0000263 IsOnePastTheEnd = V.isLValueOnePastTheEnd();
Richard Smith80815602011-11-07 05:07:52 +0000264 ArrayRef<PathEntry> VEntries = V.getLValuePath();
265 Entries.insert(Entries.end(), VEntries.begin(), VEntries.end());
Daniel Jasperffdee092017-05-02 19:21:42 +0000266 if (V.getLValueBase()) {
267 bool IsArray = false;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000268 bool FirstIsUnsizedArray = false;
George Burgess IVe3763372016-12-22 02:50:20 +0000269 MostDerivedPathLength = findMostDerivedSubobject(
Daniel Jasperffdee092017-05-02 19:21:42 +0000270 Ctx, V.getLValueBase(), V.getLValuePath(), MostDerivedArraySize,
Richard Smith6f4f0f12017-10-20 22:56:25 +0000271 MostDerivedType, IsArray, FirstIsUnsizedArray);
Daniel Jasperffdee092017-05-02 19:21:42 +0000272 MostDerivedIsArrayElement = IsArray;
Richard Smith6f4f0f12017-10-20 22:56:25 +0000273 FirstEntryIsAnUnsizedArray = FirstIsUnsizedArray;
George Burgess IVa51c4072015-10-16 01:49:01 +0000274 }
Richard Smith80815602011-11-07 05:07:52 +0000275 }
276 }
277
Richard Smith96e0c102011-11-04 02:25:55 +0000278 void setInvalid() {
279 Invalid = true;
280 Entries.clear();
281 }
Richard Smitha8105bc2012-01-06 16:39:00 +0000282
George Burgess IVe3763372016-12-22 02:50:20 +0000283 /// Determine whether the most derived subobject is an array without a
284 /// known bound.
285 bool isMostDerivedAnUnsizedArray() const {
286 assert(!Invalid && "Calling this makes no sense on invalid designators");
Daniel Jasperffdee092017-05-02 19:21:42 +0000287 return Entries.size() == 1 && FirstEntryIsAnUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000288 }
289
290 /// Determine what the most derived array's size is. Results in an assertion
291 /// failure if the most derived array lacks a size.
292 uint64_t getMostDerivedArraySize() const {
293 assert(!isMostDerivedAnUnsizedArray() && "Unsized array has no size");
294 return MostDerivedArraySize;
295 }
296
Richard Smitha8105bc2012-01-06 16:39:00 +0000297 /// Determine whether this is a one-past-the-end pointer.
298 bool isOnePastTheEnd() const {
Richard Smith33b44ab2014-07-23 23:50:25 +0000299 assert(!Invalid);
Richard Smitha8105bc2012-01-06 16:39:00 +0000300 if (IsOnePastTheEnd)
301 return true;
George Burgess IVe3763372016-12-22 02:50:20 +0000302 if (!isMostDerivedAnUnsizedArray() && MostDerivedIsArrayElement &&
Richard Smitha8105bc2012-01-06 16:39:00 +0000303 Entries[MostDerivedPathLength - 1].ArrayIndex == MostDerivedArraySize)
304 return true;
305 return false;
306 }
307
308 /// Check that this refers to a valid subobject.
309 bool isValidSubobject() const {
310 if (Invalid)
311 return false;
312 return !isOnePastTheEnd();
313 }
314 /// Check that this refers to a valid subobject, and if not, produce a
315 /// relevant diagnostic and set the designator as invalid.
316 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK);
317
318 /// Update this designator to refer to the first element within this array.
319 void addArrayUnchecked(const ConstantArrayType *CAT) {
Richard Smith96e0c102011-11-04 02:25:55 +0000320 PathEntry Entry;
Richard Smitha8105bc2012-01-06 16:39:00 +0000321 Entry.ArrayIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +0000322 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000323
324 // This is a most-derived object.
325 MostDerivedType = CAT->getElementType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000326 MostDerivedIsArrayElement = true;
Richard Smitha8105bc2012-01-06 16:39:00 +0000327 MostDerivedArraySize = CAT->getSize().getZExtValue();
328 MostDerivedPathLength = Entries.size();
Richard Smith96e0c102011-11-04 02:25:55 +0000329 }
George Burgess IVe3763372016-12-22 02:50:20 +0000330 /// Update this designator to refer to the first element within the array of
331 /// elements of type T. This is an array of unknown size.
332 void addUnsizedArrayUnchecked(QualType ElemTy) {
333 PathEntry Entry;
334 Entry.ArrayIndex = 0;
335 Entries.push_back(Entry);
336
337 MostDerivedType = ElemTy;
338 MostDerivedIsArrayElement = true;
339 // The value in MostDerivedArraySize is undefined in this case. So, set it
340 // to an arbitrary value that's likely to loudly break things if it's
341 // used.
Richard Smith6f4f0f12017-10-20 22:56:25 +0000342 MostDerivedArraySize = AssumedSizeForUnsizedArray;
George Burgess IVe3763372016-12-22 02:50:20 +0000343 MostDerivedPathLength = Entries.size();
344 }
Richard Smith96e0c102011-11-04 02:25:55 +0000345 /// Update this designator to refer to the given base or member of this
346 /// object.
Richard Smitha8105bc2012-01-06 16:39:00 +0000347 void addDeclUnchecked(const Decl *D, bool Virtual = false) {
Richard Smith96e0c102011-11-04 02:25:55 +0000348 PathEntry Entry;
Richard Smithd62306a2011-11-10 06:34:14 +0000349 APValue::BaseOrMemberType Value(D, Virtual);
350 Entry.BaseOrMember = Value.getOpaqueValue();
Richard Smith96e0c102011-11-04 02:25:55 +0000351 Entries.push_back(Entry);
Richard Smitha8105bc2012-01-06 16:39:00 +0000352
353 // If this isn't a base class, it's a new most-derived object.
354 if (const FieldDecl *FD = dyn_cast<FieldDecl>(D)) {
355 MostDerivedType = FD->getType();
George Burgess IVa51c4072015-10-16 01:49:01 +0000356 MostDerivedIsArrayElement = false;
Richard Smitha8105bc2012-01-06 16:39:00 +0000357 MostDerivedArraySize = 0;
358 MostDerivedPathLength = Entries.size();
359 }
Richard Smith96e0c102011-11-04 02:25:55 +0000360 }
Richard Smith66c96992012-02-18 22:04:06 +0000361 /// Update this designator to refer to the given complex component.
362 void addComplexUnchecked(QualType EltTy, bool Imag) {
363 PathEntry Entry;
364 Entry.ArrayIndex = Imag;
365 Entries.push_back(Entry);
366
367 // This is technically a most-derived object, though in practice this
368 // is unlikely to matter.
369 MostDerivedType = EltTy;
George Burgess IVa51c4072015-10-16 01:49:01 +0000370 MostDerivedIsArrayElement = true;
Richard Smith66c96992012-02-18 22:04:06 +0000371 MostDerivedArraySize = 2;
372 MostDerivedPathLength = Entries.size();
373 }
Richard Smith6f4f0f12017-10-20 22:56:25 +0000374 void diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info, const Expr *E);
Benjamin Kramerf6021ec2017-03-21 21:35:04 +0000375 void diagnosePointerArithmetic(EvalInfo &Info, const Expr *E,
376 const APSInt &N);
Richard Smith96e0c102011-11-04 02:25:55 +0000377 /// Add N to the address of this subobject.
Daniel Jasperffdee092017-05-02 19:21:42 +0000378 void adjustIndex(EvalInfo &Info, const Expr *E, APSInt N) {
379 if (Invalid || !N) return;
380 uint64_t TruncatedN = N.extOrTrunc(64).getZExtValue();
381 if (isMostDerivedAnUnsizedArray()) {
Richard Smith6f4f0f12017-10-20 22:56:25 +0000382 diagnoseUnsizedArrayPointerArithmetic(Info, E);
Daniel Jasperffdee092017-05-02 19:21:42 +0000383 // Can't verify -- trust that the user is doing the right thing (or if
384 // not, trust that the caller will catch the bad behavior).
385 // FIXME: Should we reject if this overflows, at least?
386 Entries.back().ArrayIndex += TruncatedN;
387 return;
388 }
389
390 // [expr.add]p4: For the purposes of these operators, a pointer to a
391 // nonarray object behaves the same as a pointer to the first element of
392 // an array of length one with the type of the object as its element type.
393 bool IsArray = MostDerivedPathLength == Entries.size() &&
394 MostDerivedIsArrayElement;
395 uint64_t ArrayIndex =
396 IsArray ? Entries.back().ArrayIndex : (uint64_t)IsOnePastTheEnd;
397 uint64_t ArraySize =
398 IsArray ? getMostDerivedArraySize() : (uint64_t)1;
399
400 if (N < -(int64_t)ArrayIndex || N > ArraySize - ArrayIndex) {
401 // Calculate the actual index in a wide enough type, so we can include
402 // it in the note.
403 N = N.extend(std::max<unsigned>(N.getBitWidth() + 1, 65));
404 (llvm::APInt&)N += ArrayIndex;
405 assert(N.ugt(ArraySize) && "bounds check failed for in-bounds index");
406 diagnosePointerArithmetic(Info, E, N);
407 setInvalid();
408 return;
409 }
410
411 ArrayIndex += TruncatedN;
412 assert(ArrayIndex <= ArraySize &&
413 "bounds check succeeded for out-of-bounds index");
414
415 if (IsArray)
416 Entries.back().ArrayIndex = ArrayIndex;
417 else
418 IsOnePastTheEnd = (ArrayIndex != 0);
419 }
Richard Smith96e0c102011-11-04 02:25:55 +0000420 };
421
Richard Smith254a73d2011-10-28 22:34:42 +0000422 /// A stack frame in the constexpr call stack.
423 struct CallStackFrame {
424 EvalInfo &Info;
425
426 /// Parent - The caller of this stack frame.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000427 CallStackFrame *Caller;
Richard Smith254a73d2011-10-28 22:34:42 +0000428
Richard Smithf6f003a2011-12-16 19:06:07 +0000429 /// Callee - The function which was called.
430 const FunctionDecl *Callee;
431
Richard Smithd62306a2011-11-10 06:34:14 +0000432 /// This - The binding for the this pointer in this call, if any.
433 const LValue *This;
434
Nick Lewyckye2b2caa2013-09-22 10:07:22 +0000435 /// Arguments - Parameter bindings for this function call, indexed by
Richard Smith254a73d2011-10-28 22:34:42 +0000436 /// parameters' function scope indices.
Richard Smith3da88fa2013-04-26 14:36:30 +0000437 APValue *Arguments;
Richard Smith254a73d2011-10-28 22:34:42 +0000438
Eli Friedman4830ec82012-06-25 21:21:08 +0000439 // Note that we intentionally use std::map here so that references to
440 // values are stable.
Richard Smithd9f663b2013-04-22 15:31:51 +0000441 typedef std::map<const void*, APValue> MapTy;
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000442 typedef MapTy::const_iterator temp_iterator;
443 /// Temporaries - Temporary lvalues materialized within this stack frame.
444 MapTy Temporaries;
445
Alexander Shaposhnikovfbcf29b2016-09-19 15:57:29 +0000446 /// CallLoc - The location of the call expression for this call.
447 SourceLocation CallLoc;
448
449 /// Index - The call index of this call.
450 unsigned Index;
451
Faisal Vali051e3a22017-02-16 04:12:21 +0000452 // FIXME: Adding this to every 'CallStackFrame' may have a nontrivial impact
453 // on the overall stack usage of deeply-recursing constexpr evaluataions.
454 // (We should cache this map rather than recomputing it repeatedly.)
455 // But let's try this and see how it goes; we can look into caching the map
456 // as a later change.
457
458 /// LambdaCaptureFields - Mapping from captured variables/this to
459 /// corresponding data members in the closure class.
460 llvm::DenseMap<const VarDecl *, FieldDecl *> LambdaCaptureFields;
461 FieldDecl *LambdaThisCaptureField;
462
Richard Smithf6f003a2011-12-16 19:06:07 +0000463 CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
464 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +0000465 APValue *Arguments);
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000466 ~CallStackFrame();
Richard Smith08d6a2c2013-07-24 07:11:57 +0000467
468 APValue *getTemporary(const void *Key) {
469 MapTy::iterator I = Temporaries.find(Key);
Craig Topper36250ad2014-05-12 05:36:57 +0000470 return I == Temporaries.end() ? nullptr : &I->second;
Richard Smith08d6a2c2013-07-24 07:11:57 +0000471 }
472 APValue &createTemporary(const void *Key, bool IsLifetimeExtended);
Richard Smith254a73d2011-10-28 22:34:42 +0000473 };
474
Richard Smith852c9db2013-04-20 22:23:05 +0000475 /// Temporarily override 'this'.
476 class ThisOverrideRAII {
477 public:
478 ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
479 : Frame(Frame), OldThis(Frame.This) {
480 if (Enable)
481 Frame.This = NewThis;
482 }
483 ~ThisOverrideRAII() {
484 Frame.This = OldThis;
485 }
486 private:
487 CallStackFrame &Frame;
488 const LValue *OldThis;
489 };
490
Richard Smith92b1ce02011-12-12 09:28:41 +0000491 /// A partial diagnostic which we might know in advance that we are not going
492 /// to emit.
493 class OptionalDiagnostic {
494 PartialDiagnostic *Diag;
495
496 public:
Craig Topper36250ad2014-05-12 05:36:57 +0000497 explicit OptionalDiagnostic(PartialDiagnostic *Diag = nullptr)
498 : Diag(Diag) {}
Richard Smith92b1ce02011-12-12 09:28:41 +0000499
500 template<typename T>
501 OptionalDiagnostic &operator<<(const T &v) {
502 if (Diag)
503 *Diag << v;
504 return *this;
505 }
Richard Smithfe800032012-01-31 04:08:20 +0000506
507 OptionalDiagnostic &operator<<(const APSInt &I) {
508 if (Diag) {
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000509 SmallVector<char, 32> Buffer;
Richard Smithfe800032012-01-31 04:08:20 +0000510 I.toString(Buffer);
511 *Diag << StringRef(Buffer.data(), Buffer.size());
512 }
513 return *this;
514 }
515
516 OptionalDiagnostic &operator<<(const APFloat &F) {
517 if (Diag) {
Eli Friedman07185912013-08-29 23:44:43 +0000518 // FIXME: Force the precision of the source value down so we don't
519 // print digits which are usually useless (we don't really care here if
520 // we truncate a digit by accident in edge cases). Ideally,
Daniel Jasperffdee092017-05-02 19:21:42 +0000521 // APFloat::toString would automatically print the shortest
Eli Friedman07185912013-08-29 23:44:43 +0000522 // representation which rounds to the correct value, but it's a bit
523 // tricky to implement.
524 unsigned precision =
525 llvm::APFloat::semanticsPrecision(F.getSemantics());
526 precision = (precision * 59 + 195) / 196;
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000527 SmallVector<char, 32> Buffer;
Eli Friedman07185912013-08-29 23:44:43 +0000528 F.toString(Buffer, precision);
Richard Smithfe800032012-01-31 04:08:20 +0000529 *Diag << StringRef(Buffer.data(), Buffer.size());
530 }
531 return *this;
532 }
Richard Smith92b1ce02011-12-12 09:28:41 +0000533 };
534
Richard Smith08d6a2c2013-07-24 07:11:57 +0000535 /// A cleanup, and a flag indicating whether it is lifetime-extended.
536 class Cleanup {
537 llvm::PointerIntPair<APValue*, 1, bool> Value;
538
539 public:
540 Cleanup(APValue *Val, bool IsLifetimeExtended)
541 : Value(Val, IsLifetimeExtended) {}
542
543 bool isLifetimeExtended() const { return Value.getInt(); }
544 void endLifetime() {
545 *Value.getPointer() = APValue();
546 }
547 };
548
Richard Smithb228a862012-02-15 02:18:13 +0000549 /// EvalInfo - This is a private struct used by the evaluator to capture
550 /// information about a subexpression as it is folded. It retains information
551 /// about the AST context, but also maintains information about the folded
552 /// expression.
553 ///
554 /// If an expression could be evaluated, it is still possible it is not a C
555 /// "integer constant expression" or constant expression. If not, this struct
556 /// captures information about how and why not.
557 ///
558 /// One bit of information passed *into* the request for constant folding
559 /// indicates whether the subexpression is "evaluated" or not according to C
560 /// rules. For example, the RHS of (0 && foo()) is not evaluated. We can
561 /// evaluate the expression regardless of what the RHS is, but C only allows
562 /// certain things in certain situations.
Reid Klecknerfdb3df62017-08-15 01:17:47 +0000563 struct EvalInfo {
Richard Smith92b1ce02011-12-12 09:28:41 +0000564 ASTContext &Ctx;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +0000565
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000566 /// EvalStatus - Contains information about the evaluation.
567 Expr::EvalStatus &EvalStatus;
568
569 /// CurrentCall - The top of the constexpr call stack.
570 CallStackFrame *CurrentCall;
571
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000572 /// CallStackDepth - The number of calls in the call stack right now.
573 unsigned CallStackDepth;
574
Richard Smithb228a862012-02-15 02:18:13 +0000575 /// NextCallIndex - The next call index to assign.
576 unsigned NextCallIndex;
577
Richard Smitha3d3bd22013-05-08 02:12:03 +0000578 /// StepsLeft - The remaining number of evaluation steps we're permitted
579 /// to perform. This is essentially a limit for the number of statements
580 /// we will evaluate.
581 unsigned StepsLeft;
582
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000583 /// BottomFrame - The frame in which evaluation started. This must be
Richard Smith253c2a32012-01-27 01:14:48 +0000584 /// initialized after CurrentCall and CallStackDepth.
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000585 CallStackFrame BottomFrame;
586
Richard Smith08d6a2c2013-07-24 07:11:57 +0000587 /// A stack of values whose lifetimes end at the end of some surrounding
588 /// evaluation frame.
589 llvm::SmallVector<Cleanup, 16> CleanupStack;
590
Richard Smithd62306a2011-11-10 06:34:14 +0000591 /// EvaluatingDecl - This is the declaration whose initializer is being
592 /// evaluated, if any.
Richard Smith7525ff62013-05-09 07:14:00 +0000593 APValue::LValueBase EvaluatingDecl;
Richard Smithd62306a2011-11-10 06:34:14 +0000594
595 /// EvaluatingDeclValue - This is the value being constructed for the
596 /// declaration whose initializer is being evaluated, if any.
597 APValue *EvaluatingDeclValue;
598
Erik Pilkington42925492017-10-04 00:18:55 +0000599 /// EvaluatingObject - Pair of the AST node that an lvalue represents and
600 /// the call index that that lvalue was allocated in.
601 typedef std::pair<APValue::LValueBase, unsigned> EvaluatingObject;
602
603 /// EvaluatingConstructors - Set of objects that are currently being
604 /// constructed.
605 llvm::DenseSet<EvaluatingObject> EvaluatingConstructors;
606
607 struct EvaluatingConstructorRAII {
608 EvalInfo &EI;
609 EvaluatingObject Object;
610 bool DidInsert;
611 EvaluatingConstructorRAII(EvalInfo &EI, EvaluatingObject Object)
612 : EI(EI), Object(Object) {
613 DidInsert = EI.EvaluatingConstructors.insert(Object).second;
614 }
615 ~EvaluatingConstructorRAII() {
616 if (DidInsert) EI.EvaluatingConstructors.erase(Object);
617 }
618 };
619
620 bool isEvaluatingConstructor(APValue::LValueBase Decl, unsigned CallIndex) {
621 return EvaluatingConstructors.count(EvaluatingObject(Decl, CallIndex));
622 }
623
Richard Smith410306b2016-12-12 02:53:20 +0000624 /// The current array initialization index, if we're performing array
625 /// initialization.
626 uint64_t ArrayInitIndex = -1;
627
Richard Smith357362d2011-12-13 06:39:58 +0000628 /// HasActiveDiagnostic - Was the previous diagnostic stored? If so, further
629 /// notes attached to it will also be stored, otherwise they will not be.
630 bool HasActiveDiagnostic;
631
Richard Smith0c6124b2015-12-03 01:36:22 +0000632 /// \brief Have we emitted a diagnostic explaining why we couldn't constant
633 /// fold (not just why it's not strictly a constant expression)?
634 bool HasFoldFailureDiagnostic;
635
George Burgess IV8c892b52016-05-25 22:31:54 +0000636 /// \brief Whether or not we're currently speculatively evaluating.
637 bool IsSpeculativelyEvaluating;
638
Richard Smith6d4c6582013-11-05 22:18:15 +0000639 enum EvaluationMode {
640 /// Evaluate as a constant expression. Stop if we find that the expression
641 /// is not a constant expression.
642 EM_ConstantExpression,
Richard Smith08d6a2c2013-07-24 07:11:57 +0000643
Richard Smith6d4c6582013-11-05 22:18:15 +0000644 /// Evaluate as a potential constant expression. Keep going if we hit a
645 /// construct that we can't evaluate yet (because we don't yet know the
646 /// value of something) but stop if we hit something that could never be
647 /// a constant expression.
648 EM_PotentialConstantExpression,
Richard Smith253c2a32012-01-27 01:14:48 +0000649
Richard Smith6d4c6582013-11-05 22:18:15 +0000650 /// Fold the expression to a constant. Stop if we hit a side-effect that
651 /// we can't model.
652 EM_ConstantFold,
653
654 /// Evaluate the expression looking for integer overflow and similar
655 /// issues. Don't worry about side-effects, and try to visit all
656 /// subexpressions.
657 EM_EvaluateForOverflow,
658
659 /// Evaluate in any way we know how. Don't worry about side-effects that
660 /// can't be modeled.
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000661 EM_IgnoreSideEffects,
662
663 /// Evaluate as a constant expression. Stop if we find that the expression
664 /// is not a constant expression. Some expressions can be retried in the
665 /// optimizer if we don't constant fold them here, but in an unevaluated
666 /// context we try to fold them immediately since the optimizer never
667 /// gets a chance to look at it.
668 EM_ConstantExpressionUnevaluated,
669
670 /// Evaluate as a potential constant expression. Keep going if we hit a
671 /// construct that we can't evaluate yet (because we don't yet know the
672 /// value of something) but stop if we hit something that could never be
673 /// a constant expression. Some expressions can be retried in the
674 /// optimizer if we don't constant fold them here, but in an unevaluated
675 /// context we try to fold them immediately since the optimizer never
676 /// gets a chance to look at it.
George Burgess IV3a03fab2015-09-04 21:28:13 +0000677 EM_PotentialConstantExpressionUnevaluated,
678
George Burgess IVf9013bf2017-02-10 22:52:29 +0000679 /// Evaluate as a constant expression. In certain scenarios, if:
680 /// - we find a MemberExpr with a base that can't be evaluated, or
681 /// - we find a variable initialized with a call to a function that has
682 /// the alloc_size attribute on it
683 /// then we may consider evaluation to have succeeded.
684 ///
George Burgess IVe3763372016-12-22 02:50:20 +0000685 /// In either case, the LValue returned shall have an invalid base; in the
686 /// former, the base will be the invalid MemberExpr, in the latter, the
687 /// base will be either the alloc_size CallExpr or a CastExpr wrapping
688 /// said CallExpr.
689 EM_OffsetFold,
Richard Smith6d4c6582013-11-05 22:18:15 +0000690 } EvalMode;
691
692 /// Are we checking whether the expression is a potential constant
693 /// expression?
694 bool checkingPotentialConstantExpression() const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000695 return EvalMode == EM_PotentialConstantExpression ||
696 EvalMode == EM_PotentialConstantExpressionUnevaluated;
Richard Smith6d4c6582013-11-05 22:18:15 +0000697 }
698
699 /// Are we checking an expression for overflow?
700 // FIXME: We should check for any kind of undefined or suspicious behavior
701 // in such constructs, not just overflow.
702 bool checkingForOverflow() { return EvalMode == EM_EvaluateForOverflow; }
703
704 EvalInfo(const ASTContext &C, Expr::EvalStatus &S, EvaluationMode Mode)
Craig Topper36250ad2014-05-12 05:36:57 +0000705 : Ctx(const_cast<ASTContext &>(C)), EvalStatus(S), CurrentCall(nullptr),
Richard Smithb228a862012-02-15 02:18:13 +0000706 CallStackDepth(0), NextCallIndex(1),
Richard Smitha3d3bd22013-05-08 02:12:03 +0000707 StepsLeft(getLangOpts().ConstexprStepLimit),
Craig Topper36250ad2014-05-12 05:36:57 +0000708 BottomFrame(*this, SourceLocation(), nullptr, nullptr, nullptr),
709 EvaluatingDecl((const ValueDecl *)nullptr),
710 EvaluatingDeclValue(nullptr), HasActiveDiagnostic(false),
George Burgess IV8c892b52016-05-25 22:31:54 +0000711 HasFoldFailureDiagnostic(false), IsSpeculativelyEvaluating(false),
712 EvalMode(Mode) {}
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000713
Richard Smith7525ff62013-05-09 07:14:00 +0000714 void setEvaluatingDecl(APValue::LValueBase Base, APValue &Value) {
715 EvaluatingDecl = Base;
Richard Smithd62306a2011-11-10 06:34:14 +0000716 EvaluatingDeclValue = &Value;
Erik Pilkington42925492017-10-04 00:18:55 +0000717 EvaluatingConstructors.insert({Base, 0});
Richard Smithd62306a2011-11-10 06:34:14 +0000718 }
719
David Blaikiebbafb8a2012-03-11 07:00:24 +0000720 const LangOptions &getLangOpts() const { return Ctx.getLangOpts(); }
Richard Smith9a568822011-11-21 19:36:32 +0000721
Richard Smith357362d2011-12-13 06:39:58 +0000722 bool CheckCallLimit(SourceLocation Loc) {
Richard Smith253c2a32012-01-27 01:14:48 +0000723 // Don't perform any constexpr calls (other than the call we're checking)
724 // when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000725 if (checkingPotentialConstantExpression() && CallStackDepth > 1)
Richard Smith253c2a32012-01-27 01:14:48 +0000726 return false;
Richard Smithb228a862012-02-15 02:18:13 +0000727 if (NextCallIndex == 0) {
728 // NextCallIndex has wrapped around.
Faisal Valie690b7a2016-07-02 22:34:24 +0000729 FFDiag(Loc, diag::note_constexpr_call_limit_exceeded);
Richard Smithb228a862012-02-15 02:18:13 +0000730 return false;
731 }
Richard Smith357362d2011-12-13 06:39:58 +0000732 if (CallStackDepth <= getLangOpts().ConstexprCallDepth)
733 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +0000734 FFDiag(Loc, diag::note_constexpr_depth_limit_exceeded)
Richard Smith357362d2011-12-13 06:39:58 +0000735 << getLangOpts().ConstexprCallDepth;
736 return false;
Richard Smith9a568822011-11-21 19:36:32 +0000737 }
Richard Smithf57d8cb2011-12-09 22:58:01 +0000738
Richard Smithb228a862012-02-15 02:18:13 +0000739 CallStackFrame *getCallFrame(unsigned CallIndex) {
740 assert(CallIndex && "no call index in getCallFrame");
741 // We will eventually hit BottomFrame, which has Index 1, so Frame can't
742 // be null in this loop.
743 CallStackFrame *Frame = CurrentCall;
744 while (Frame->Index > CallIndex)
745 Frame = Frame->Caller;
Craig Topper36250ad2014-05-12 05:36:57 +0000746 return (Frame->Index == CallIndex) ? Frame : nullptr;
Richard Smithb228a862012-02-15 02:18:13 +0000747 }
748
Richard Smitha3d3bd22013-05-08 02:12:03 +0000749 bool nextStep(const Stmt *S) {
750 if (!StepsLeft) {
Faisal Valie690b7a2016-07-02 22:34:24 +0000751 FFDiag(S->getLocStart(), diag::note_constexpr_step_limit_exceeded);
Richard Smitha3d3bd22013-05-08 02:12:03 +0000752 return false;
753 }
754 --StepsLeft;
755 return true;
756 }
757
Richard Smith357362d2011-12-13 06:39:58 +0000758 private:
759 /// Add a diagnostic to the diagnostics list.
760 PartialDiagnostic &addDiag(SourceLocation Loc, diag::kind DiagId) {
761 PartialDiagnostic PD(DiagId, Ctx.getDiagAllocator());
762 EvalStatus.Diag->push_back(std::make_pair(Loc, PD));
763 return EvalStatus.Diag->back().second;
764 }
765
Richard Smithf6f003a2011-12-16 19:06:07 +0000766 /// Add notes containing a call stack to the current point of evaluation.
767 void addCallStack(unsigned Limit);
768
Faisal Valie690b7a2016-07-02 22:34:24 +0000769 private:
770 OptionalDiagnostic Diag(SourceLocation Loc, diag::kind DiagId,
771 unsigned ExtraNotes, bool IsCCEDiag) {
Daniel Jasperffdee092017-05-02 19:21:42 +0000772
Richard Smith92b1ce02011-12-12 09:28:41 +0000773 if (EvalStatus.Diag) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000774 // If we have a prior diagnostic, it will be noting that the expression
775 // isn't a constant expression. This diagnostic is more important,
776 // unless we require this evaluation to produce a constant expression.
777 //
778 // FIXME: We might want to show both diagnostics to the user in
779 // EM_ConstantFold mode.
780 if (!EvalStatus.Diag->empty()) {
781 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000782 case EM_ConstantFold:
783 case EM_IgnoreSideEffects:
784 case EM_EvaluateForOverflow:
Richard Smith0c6124b2015-12-03 01:36:22 +0000785 if (!HasFoldFailureDiagnostic)
Richard Smith4e66f1f2013-11-06 02:19:10 +0000786 break;
Richard Smith0c6124b2015-12-03 01:36:22 +0000787 // We've already failed to fold something. Keep that diagnostic.
Galina Kistanovaf87496d2017-06-03 06:31:42 +0000788 LLVM_FALLTHROUGH;
Richard Smith6d4c6582013-11-05 22:18:15 +0000789 case EM_ConstantExpression:
790 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000791 case EM_ConstantExpressionUnevaluated:
792 case EM_PotentialConstantExpressionUnevaluated:
George Burgess IVe3763372016-12-22 02:50:20 +0000793 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000794 HasActiveDiagnostic = false;
795 return OptionalDiagnostic();
Richard Smith6d4c6582013-11-05 22:18:15 +0000796 }
797 }
798
Richard Smithf6f003a2011-12-16 19:06:07 +0000799 unsigned CallStackNotes = CallStackDepth - 1;
800 unsigned Limit = Ctx.getDiagnostics().getConstexprBacktraceLimit();
801 if (Limit)
802 CallStackNotes = std::min(CallStackNotes, Limit + 1);
Richard Smith6d4c6582013-11-05 22:18:15 +0000803 if (checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000804 CallStackNotes = 0;
Richard Smithf6f003a2011-12-16 19:06:07 +0000805
Richard Smith357362d2011-12-13 06:39:58 +0000806 HasActiveDiagnostic = true;
Richard Smith0c6124b2015-12-03 01:36:22 +0000807 HasFoldFailureDiagnostic = !IsCCEDiag;
Richard Smith92b1ce02011-12-12 09:28:41 +0000808 EvalStatus.Diag->clear();
Richard Smithf6f003a2011-12-16 19:06:07 +0000809 EvalStatus.Diag->reserve(1 + ExtraNotes + CallStackNotes);
810 addDiag(Loc, DiagId);
Richard Smith6d4c6582013-11-05 22:18:15 +0000811 if (!checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +0000812 addCallStack(Limit);
Richard Smithf6f003a2011-12-16 19:06:07 +0000813 return OptionalDiagnostic(&(*EvalStatus.Diag)[0].second);
Richard Smith92b1ce02011-12-12 09:28:41 +0000814 }
Richard Smith357362d2011-12-13 06:39:58 +0000815 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000816 return OptionalDiagnostic();
817 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000818 public:
819 // Diagnose that the evaluation could not be folded (FF => FoldFailure)
820 OptionalDiagnostic
821 FFDiag(SourceLocation Loc,
822 diag::kind DiagId = diag::note_invalid_subexpr_in_const_expr,
823 unsigned ExtraNotes = 0) {
824 return Diag(Loc, DiagId, ExtraNotes, false);
825 }
Daniel Jasperffdee092017-05-02 19:21:42 +0000826
Faisal Valie690b7a2016-07-02 22:34:24 +0000827 OptionalDiagnostic FFDiag(const Expr *E, diag::kind DiagId
Richard Smithce1ec5e2012-03-15 04:53:45 +0000828 = diag::note_invalid_subexpr_in_const_expr,
Faisal Valie690b7a2016-07-02 22:34:24 +0000829 unsigned ExtraNotes = 0) {
Richard Smithce1ec5e2012-03-15 04:53:45 +0000830 if (EvalStatus.Diag)
Faisal Valie690b7a2016-07-02 22:34:24 +0000831 return Diag(E->getExprLoc(), DiagId, ExtraNotes, /*IsCCEDiag*/false);
Richard Smithce1ec5e2012-03-15 04:53:45 +0000832 HasActiveDiagnostic = false;
833 return OptionalDiagnostic();
834 }
835
Richard Smith92b1ce02011-12-12 09:28:41 +0000836 /// Diagnose that the evaluation does not produce a C++11 core constant
837 /// expression.
Richard Smith6d4c6582013-11-05 22:18:15 +0000838 ///
839 /// FIXME: Stop evaluating if we're in EM_ConstantExpression or
840 /// EM_PotentialConstantExpression mode and we produce one of these.
Faisal Valie690b7a2016-07-02 22:34:24 +0000841 OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId
Richard Smithf2b681b2011-12-21 05:04:46 +0000842 = diag::note_invalid_subexpr_in_const_expr,
Richard Smith357362d2011-12-13 06:39:58 +0000843 unsigned ExtraNotes = 0) {
Richard Smith6d4c6582013-11-05 22:18:15 +0000844 // Don't override a previous diagnostic. Don't bother collecting
845 // diagnostics if we're evaluating for overflow.
Richard Smithe9ff7702013-11-05 22:23:30 +0000846 if (!EvalStatus.Diag || !EvalStatus.Diag->empty()) {
Eli Friedmanebea9af2012-02-21 22:41:33 +0000847 HasActiveDiagnostic = false;
Richard Smith92b1ce02011-12-12 09:28:41 +0000848 return OptionalDiagnostic();
Eli Friedmanebea9af2012-02-21 22:41:33 +0000849 }
Richard Smith0c6124b2015-12-03 01:36:22 +0000850 return Diag(Loc, DiagId, ExtraNotes, true);
Richard Smith357362d2011-12-13 06:39:58 +0000851 }
Faisal Valie690b7a2016-07-02 22:34:24 +0000852 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind DiagId
853 = diag::note_invalid_subexpr_in_const_expr,
854 unsigned ExtraNotes = 0) {
855 return CCEDiag(E->getExprLoc(), DiagId, ExtraNotes);
856 }
Richard Smith357362d2011-12-13 06:39:58 +0000857 /// Add a note to a prior diagnostic.
858 OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId) {
859 if (!HasActiveDiagnostic)
860 return OptionalDiagnostic();
861 return OptionalDiagnostic(&addDiag(Loc, DiagId));
Richard Smithf57d8cb2011-12-09 22:58:01 +0000862 }
Richard Smithd0b4dd62011-12-19 06:19:21 +0000863
864 /// Add a stack of notes to a prior diagnostic.
865 void addNotes(ArrayRef<PartialDiagnosticAt> Diags) {
866 if (HasActiveDiagnostic) {
867 EvalStatus.Diag->insert(EvalStatus.Diag->end(),
868 Diags.begin(), Diags.end());
869 }
870 }
Richard Smith253c2a32012-01-27 01:14:48 +0000871
Richard Smith6d4c6582013-11-05 22:18:15 +0000872 /// Should we continue evaluation after encountering a side-effect that we
873 /// couldn't model?
874 bool keepEvaluatingAfterSideEffect() {
875 switch (EvalMode) {
Richard Smith4e66f1f2013-11-06 02:19:10 +0000876 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000877 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000878 case EM_EvaluateForOverflow:
879 case EM_IgnoreSideEffects:
880 return true;
881
Richard Smith6d4c6582013-11-05 22:18:15 +0000882 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000883 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000884 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000885 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000886 return false;
887 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000888 llvm_unreachable("Missed EvalMode case");
Richard Smith6d4c6582013-11-05 22:18:15 +0000889 }
890
891 /// Note that we have had a side-effect, and determine whether we should
892 /// keep evaluating.
893 bool noteSideEffect() {
894 EvalStatus.HasSideEffects = true;
895 return keepEvaluatingAfterSideEffect();
896 }
897
Richard Smithce8eca52015-12-08 03:21:47 +0000898 /// Should we continue evaluation after encountering undefined behavior?
899 bool keepEvaluatingAfterUndefinedBehavior() {
900 switch (EvalMode) {
901 case EM_EvaluateForOverflow:
902 case EM_IgnoreSideEffects:
903 case EM_ConstantFold:
George Burgess IVe3763372016-12-22 02:50:20 +0000904 case EM_OffsetFold:
Richard Smithce8eca52015-12-08 03:21:47 +0000905 return true;
906
907 case EM_PotentialConstantExpression:
908 case EM_PotentialConstantExpressionUnevaluated:
909 case EM_ConstantExpression:
910 case EM_ConstantExpressionUnevaluated:
911 return false;
912 }
913 llvm_unreachable("Missed EvalMode case");
914 }
915
916 /// Note that we hit something that was technically undefined behavior, but
917 /// that we can evaluate past it (such as signed overflow or floating-point
918 /// division by zero.)
919 bool noteUndefinedBehavior() {
920 EvalStatus.HasUndefinedBehavior = true;
921 return keepEvaluatingAfterUndefinedBehavior();
922 }
923
Richard Smith253c2a32012-01-27 01:14:48 +0000924 /// Should we continue evaluation as much as possible after encountering a
Richard Smith6d4c6582013-11-05 22:18:15 +0000925 /// construct which can't be reduced to a value?
Richard Smith253c2a32012-01-27 01:14:48 +0000926 bool keepEvaluatingAfterFailure() {
Richard Smith6d4c6582013-11-05 22:18:15 +0000927 if (!StepsLeft)
928 return false;
929
930 switch (EvalMode) {
931 case EM_PotentialConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000932 case EM_PotentialConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000933 case EM_EvaluateForOverflow:
934 return true;
935
936 case EM_ConstantExpression:
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000937 case EM_ConstantExpressionUnevaluated:
Richard Smith6d4c6582013-11-05 22:18:15 +0000938 case EM_ConstantFold:
939 case EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +0000940 case EM_OffsetFold:
Richard Smith6d4c6582013-11-05 22:18:15 +0000941 return false;
942 }
Aaron Ballmanf682f532013-11-06 18:15:02 +0000943 llvm_unreachable("Missed EvalMode case");
Richard Smith253c2a32012-01-27 01:14:48 +0000944 }
George Burgess IV3a03fab2015-09-04 21:28:13 +0000945
George Burgess IV8c892b52016-05-25 22:31:54 +0000946 /// Notes that we failed to evaluate an expression that other expressions
947 /// directly depend on, and determine if we should keep evaluating. This
948 /// should only be called if we actually intend to keep evaluating.
949 ///
950 /// Call noteSideEffect() instead if we may be able to ignore the value that
951 /// we failed to evaluate, e.g. if we failed to evaluate Foo() in:
952 ///
953 /// (Foo(), 1) // use noteSideEffect
954 /// (Foo() || true) // use noteSideEffect
955 /// Foo() + 1 // use noteFailure
Justin Bognerfe183d72016-10-17 06:46:35 +0000956 LLVM_NODISCARD bool noteFailure() {
George Burgess IV8c892b52016-05-25 22:31:54 +0000957 // Failure when evaluating some expression often means there is some
958 // subexpression whose evaluation was skipped. Therefore, (because we
959 // don't track whether we skipped an expression when unwinding after an
960 // evaluation failure) every evaluation failure that bubbles up from a
961 // subexpression implies that a side-effect has potentially happened. We
962 // skip setting the HasSideEffects flag to true until we decide to
963 // continue evaluating after that point, which happens here.
964 bool KeepGoing = keepEvaluatingAfterFailure();
965 EvalStatus.HasSideEffects |= KeepGoing;
966 return KeepGoing;
967 }
968
Richard Smith410306b2016-12-12 02:53:20 +0000969 class ArrayInitLoopIndex {
970 EvalInfo &Info;
971 uint64_t OuterIndex;
972
973 public:
974 ArrayInitLoopIndex(EvalInfo &Info)
975 : Info(Info), OuterIndex(Info.ArrayInitIndex) {
976 Info.ArrayInitIndex = 0;
977 }
978 ~ArrayInitLoopIndex() { Info.ArrayInitIndex = OuterIndex; }
979
980 operator uint64_t&() { return Info.ArrayInitIndex; }
981 };
Richard Smith4e4c78ff2011-10-31 05:52:43 +0000982 };
Richard Smith84f6dcf2012-02-02 01:16:57 +0000983
984 /// Object used to treat all foldable expressions as constant expressions.
985 struct FoldConstant {
Richard Smith6d4c6582013-11-05 22:18:15 +0000986 EvalInfo &Info;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000987 bool Enabled;
Richard Smith6d4c6582013-11-05 22:18:15 +0000988 bool HadNoPriorDiags;
989 EvalInfo::EvaluationMode OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +0000990
Richard Smith6d4c6582013-11-05 22:18:15 +0000991 explicit FoldConstant(EvalInfo &Info, bool Enabled)
992 : Info(Info),
993 Enabled(Enabled),
994 HadNoPriorDiags(Info.EvalStatus.Diag &&
995 Info.EvalStatus.Diag->empty() &&
996 !Info.EvalStatus.HasSideEffects),
997 OldMode(Info.EvalMode) {
Nick Lewycky35a6ef42014-01-11 02:50:57 +0000998 if (Enabled &&
999 (Info.EvalMode == EvalInfo::EM_ConstantExpression ||
1000 Info.EvalMode == EvalInfo::EM_ConstantExpressionUnevaluated))
Richard Smith6d4c6582013-11-05 22:18:15 +00001001 Info.EvalMode = EvalInfo::EM_ConstantFold;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001002 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001003 void keepDiagnostics() { Enabled = false; }
1004 ~FoldConstant() {
1005 if (Enabled && HadNoPriorDiags && !Info.EvalStatus.Diag->empty() &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00001006 !Info.EvalStatus.HasSideEffects)
1007 Info.EvalStatus.Diag->clear();
Richard Smith6d4c6582013-11-05 22:18:15 +00001008 Info.EvalMode = OldMode;
Richard Smith84f6dcf2012-02-02 01:16:57 +00001009 }
1010 };
Richard Smith17100ba2012-02-16 02:46:34 +00001011
George Burgess IV3a03fab2015-09-04 21:28:13 +00001012 /// RAII object used to treat the current evaluation as the correct pointer
1013 /// offset fold for the current EvalMode
1014 struct FoldOffsetRAII {
1015 EvalInfo &Info;
1016 EvalInfo::EvaluationMode OldMode;
George Burgess IVe3763372016-12-22 02:50:20 +00001017 explicit FoldOffsetRAII(EvalInfo &Info)
George Burgess IV3a03fab2015-09-04 21:28:13 +00001018 : Info(Info), OldMode(Info.EvalMode) {
1019 if (!Info.checkingPotentialConstantExpression())
George Burgess IVe3763372016-12-22 02:50:20 +00001020 Info.EvalMode = EvalInfo::EM_OffsetFold;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001021 }
1022
1023 ~FoldOffsetRAII() { Info.EvalMode = OldMode; }
1024 };
1025
George Burgess IV8c892b52016-05-25 22:31:54 +00001026 /// RAII object used to optionally suppress diagnostics and side-effects from
1027 /// a speculative evaluation.
Richard Smith17100ba2012-02-16 02:46:34 +00001028 class SpeculativeEvaluationRAII {
Chandler Carruthbacb80d2017-08-16 07:22:49 +00001029 EvalInfo *Info = nullptr;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001030 Expr::EvalStatus OldStatus;
1031 bool OldIsSpeculativelyEvaluating;
Richard Smith17100ba2012-02-16 02:46:34 +00001032
George Burgess IV8c892b52016-05-25 22:31:54 +00001033 void moveFromAndCancel(SpeculativeEvaluationRAII &&Other) {
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001034 Info = Other.Info;
1035 OldStatus = Other.OldStatus;
Daniel Jaspera7e061f2017-08-17 06:33:46 +00001036 OldIsSpeculativelyEvaluating = Other.OldIsSpeculativelyEvaluating;
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001037 Other.Info = nullptr;
George Burgess IV8c892b52016-05-25 22:31:54 +00001038 }
1039
1040 void maybeRestoreState() {
George Burgess IV8c892b52016-05-25 22:31:54 +00001041 if (!Info)
1042 return;
1043
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001044 Info->EvalStatus = OldStatus;
1045 Info->IsSpeculativelyEvaluating = OldIsSpeculativelyEvaluating;
George Burgess IV8c892b52016-05-25 22:31:54 +00001046 }
1047
Richard Smith17100ba2012-02-16 02:46:34 +00001048 public:
George Burgess IV8c892b52016-05-25 22:31:54 +00001049 SpeculativeEvaluationRAII() = default;
1050
1051 SpeculativeEvaluationRAII(
1052 EvalInfo &Info, SmallVectorImpl<PartialDiagnosticAt> *NewDiag = nullptr)
Reid Klecknerfdb3df62017-08-15 01:17:47 +00001053 : Info(&Info), OldStatus(Info.EvalStatus),
1054 OldIsSpeculativelyEvaluating(Info.IsSpeculativelyEvaluating) {
Richard Smith17100ba2012-02-16 02:46:34 +00001055 Info.EvalStatus.Diag = NewDiag;
George Burgess IV8c892b52016-05-25 22:31:54 +00001056 Info.IsSpeculativelyEvaluating = true;
Richard Smith17100ba2012-02-16 02:46:34 +00001057 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001058
1059 SpeculativeEvaluationRAII(const SpeculativeEvaluationRAII &Other) = delete;
1060 SpeculativeEvaluationRAII(SpeculativeEvaluationRAII &&Other) {
1061 moveFromAndCancel(std::move(Other));
Richard Smith17100ba2012-02-16 02:46:34 +00001062 }
George Burgess IV8c892b52016-05-25 22:31:54 +00001063
1064 SpeculativeEvaluationRAII &operator=(SpeculativeEvaluationRAII &&Other) {
1065 maybeRestoreState();
1066 moveFromAndCancel(std::move(Other));
1067 return *this;
1068 }
1069
1070 ~SpeculativeEvaluationRAII() { maybeRestoreState(); }
Richard Smith17100ba2012-02-16 02:46:34 +00001071 };
Richard Smith08d6a2c2013-07-24 07:11:57 +00001072
1073 /// RAII object wrapping a full-expression or block scope, and handling
1074 /// the ending of the lifetime of temporaries created within it.
1075 template<bool IsFullExpression>
1076 class ScopeRAII {
1077 EvalInfo &Info;
1078 unsigned OldStackSize;
1079 public:
1080 ScopeRAII(EvalInfo &Info)
1081 : Info(Info), OldStackSize(Info.CleanupStack.size()) {}
1082 ~ScopeRAII() {
1083 // Body moved to a static method to encourage the compiler to inline away
1084 // instances of this class.
1085 cleanup(Info, OldStackSize);
1086 }
1087 private:
1088 static void cleanup(EvalInfo &Info, unsigned OldStackSize) {
1089 unsigned NewEnd = OldStackSize;
1090 for (unsigned I = OldStackSize, N = Info.CleanupStack.size();
1091 I != N; ++I) {
1092 if (IsFullExpression && Info.CleanupStack[I].isLifetimeExtended()) {
1093 // Full-expression cleanup of a lifetime-extended temporary: nothing
1094 // to do, just move this cleanup to the right place in the stack.
1095 std::swap(Info.CleanupStack[I], Info.CleanupStack[NewEnd]);
1096 ++NewEnd;
1097 } else {
1098 // End the lifetime of the object.
1099 Info.CleanupStack[I].endLifetime();
1100 }
1101 }
1102 Info.CleanupStack.erase(Info.CleanupStack.begin() + NewEnd,
1103 Info.CleanupStack.end());
1104 }
1105 };
1106 typedef ScopeRAII<false> BlockScopeRAII;
1107 typedef ScopeRAII<true> FullExpressionRAII;
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001108}
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001109
Richard Smitha8105bc2012-01-06 16:39:00 +00001110bool SubobjectDesignator::checkSubobject(EvalInfo &Info, const Expr *E,
1111 CheckSubobjectKind CSK) {
1112 if (Invalid)
1113 return false;
1114 if (isOnePastTheEnd()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001115 Info.CCEDiag(E, diag::note_constexpr_past_end_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001116 << CSK;
1117 setInvalid();
1118 return false;
1119 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001120 // Note, we do not diagnose if isMostDerivedAnUnsizedArray(), because there
1121 // must actually be at least one array element; even a VLA cannot have a
1122 // bound of zero. And if our index is nonzero, we already had a CCEDiag.
Richard Smitha8105bc2012-01-06 16:39:00 +00001123 return true;
1124}
1125
Richard Smith6f4f0f12017-10-20 22:56:25 +00001126void SubobjectDesignator::diagnoseUnsizedArrayPointerArithmetic(EvalInfo &Info,
1127 const Expr *E) {
1128 Info.CCEDiag(E, diag::note_constexpr_unsized_array_indexed);
1129 // Do not set the designator as invalid: we can represent this situation,
1130 // and correct handling of __builtin_object_size requires us to do so.
1131}
1132
Richard Smitha8105bc2012-01-06 16:39:00 +00001133void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001134 const Expr *E,
1135 const APSInt &N) {
George Burgess IVe3763372016-12-22 02:50:20 +00001136 // If we're complaining, we must be able to statically determine the size of
1137 // the most derived array.
George Burgess IVa51c4072015-10-16 01:49:01 +00001138 if (MostDerivedPathLength == Entries.size() && MostDerivedIsArrayElement)
Richard Smithce1ec5e2012-03-15 04:53:45 +00001139 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001140 << N << /*array*/ 0
George Burgess IVe3763372016-12-22 02:50:20 +00001141 << static_cast<unsigned>(getMostDerivedArraySize());
Richard Smitha8105bc2012-01-06 16:39:00 +00001142 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00001143 Info.CCEDiag(E, diag::note_constexpr_array_index)
Richard Smithd6cc1982017-01-31 02:23:02 +00001144 << N << /*non-array*/ 1;
Richard Smitha8105bc2012-01-06 16:39:00 +00001145 setInvalid();
1146}
1147
Richard Smithf6f003a2011-12-16 19:06:07 +00001148CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
1149 const FunctionDecl *Callee, const LValue *This,
Richard Smith3da88fa2013-04-26 14:36:30 +00001150 APValue *Arguments)
Samuel Antao1197a162016-09-19 18:13:13 +00001151 : Info(Info), Caller(Info.CurrentCall), Callee(Callee), This(This),
1152 Arguments(Arguments), CallLoc(CallLoc), Index(Info.NextCallIndex++) {
Richard Smithf6f003a2011-12-16 19:06:07 +00001153 Info.CurrentCall = this;
1154 ++Info.CallStackDepth;
1155}
1156
1157CallStackFrame::~CallStackFrame() {
1158 assert(Info.CurrentCall == this && "calls retired out of order");
1159 --Info.CallStackDepth;
1160 Info.CurrentCall = Caller;
1161}
1162
Richard Smith08d6a2c2013-07-24 07:11:57 +00001163APValue &CallStackFrame::createTemporary(const void *Key,
1164 bool IsLifetimeExtended) {
1165 APValue &Result = Temporaries[Key];
1166 assert(Result.isUninit() && "temporary created multiple times");
1167 Info.CleanupStack.push_back(Cleanup(&Result, IsLifetimeExtended));
1168 return Result;
1169}
1170
Richard Smith84401042013-06-03 05:03:02 +00001171static void describeCall(CallStackFrame *Frame, raw_ostream &Out);
Richard Smithf6f003a2011-12-16 19:06:07 +00001172
1173void EvalInfo::addCallStack(unsigned Limit) {
1174 // Determine which calls to skip, if any.
1175 unsigned ActiveCalls = CallStackDepth - 1;
1176 unsigned SkipStart = ActiveCalls, SkipEnd = SkipStart;
1177 if (Limit && Limit < ActiveCalls) {
1178 SkipStart = Limit / 2 + Limit % 2;
1179 SkipEnd = ActiveCalls - Limit / 2;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00001180 }
1181
Richard Smithf6f003a2011-12-16 19:06:07 +00001182 // Walk the call stack and add the diagnostics.
1183 unsigned CallIdx = 0;
1184 for (CallStackFrame *Frame = CurrentCall; Frame != &BottomFrame;
1185 Frame = Frame->Caller, ++CallIdx) {
1186 // Skip this call?
1187 if (CallIdx >= SkipStart && CallIdx < SkipEnd) {
1188 if (CallIdx == SkipStart) {
1189 // Note that we're skipping calls.
1190 addDiag(Frame->CallLoc, diag::note_constexpr_calls_suppressed)
1191 << unsigned(ActiveCalls - Limit);
1192 }
1193 continue;
1194 }
1195
Richard Smith5179eb72016-06-28 19:03:57 +00001196 // Use a different note for an inheriting constructor, because from the
1197 // user's perspective it's not really a function at all.
1198 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Frame->Callee)) {
1199 if (CD->isInheritingConstructor()) {
1200 addDiag(Frame->CallLoc, diag::note_constexpr_inherited_ctor_call_here)
1201 << CD->getParent();
1202 continue;
1203 }
1204 }
1205
Dmitri Gribenkof8579502013-01-12 19:30:44 +00001206 SmallVector<char, 128> Buffer;
Richard Smithf6f003a2011-12-16 19:06:07 +00001207 llvm::raw_svector_ostream Out(Buffer);
1208 describeCall(Frame, Out);
1209 addDiag(Frame->CallLoc, diag::note_constexpr_call_here) << Out.str();
1210 }
1211}
1212
1213namespace {
John McCall93d91dc2010-05-07 17:22:02 +00001214 struct ComplexValue {
1215 private:
1216 bool IsInt;
1217
1218 public:
1219 APSInt IntReal, IntImag;
1220 APFloat FloatReal, FloatImag;
1221
Stephan Bergmann17c7f702016-12-14 11:57:17 +00001222 ComplexValue() : FloatReal(APFloat::Bogus()), FloatImag(APFloat::Bogus()) {}
John McCall93d91dc2010-05-07 17:22:02 +00001223
1224 void makeComplexFloat() { IsInt = false; }
1225 bool isComplexFloat() const { return !IsInt; }
1226 APFloat &getComplexFloatReal() { return FloatReal; }
1227 APFloat &getComplexFloatImag() { return FloatImag; }
1228
1229 void makeComplexInt() { IsInt = true; }
1230 bool isComplexInt() const { return IsInt; }
1231 APSInt &getComplexIntReal() { return IntReal; }
1232 APSInt &getComplexIntImag() { return IntImag; }
1233
Richard Smith2e312c82012-03-03 22:46:17 +00001234 void moveInto(APValue &v) const {
John McCall93d91dc2010-05-07 17:22:02 +00001235 if (isComplexFloat())
Richard Smith2e312c82012-03-03 22:46:17 +00001236 v = APValue(FloatReal, FloatImag);
John McCall93d91dc2010-05-07 17:22:02 +00001237 else
Richard Smith2e312c82012-03-03 22:46:17 +00001238 v = APValue(IntReal, IntImag);
John McCall93d91dc2010-05-07 17:22:02 +00001239 }
Richard Smith2e312c82012-03-03 22:46:17 +00001240 void setFrom(const APValue &v) {
John McCallc07a0c72011-02-17 10:25:35 +00001241 assert(v.isComplexFloat() || v.isComplexInt());
1242 if (v.isComplexFloat()) {
1243 makeComplexFloat();
1244 FloatReal = v.getComplexFloatReal();
1245 FloatImag = v.getComplexFloatImag();
1246 } else {
1247 makeComplexInt();
1248 IntReal = v.getComplexIntReal();
1249 IntImag = v.getComplexIntImag();
1250 }
1251 }
John McCall93d91dc2010-05-07 17:22:02 +00001252 };
John McCall45d55e42010-05-07 21:00:08 +00001253
1254 struct LValue {
Richard Smithce40ad62011-11-12 22:28:03 +00001255 APValue::LValueBase Base;
John McCall45d55e42010-05-07 21:00:08 +00001256 CharUnits Offset;
Akira Hatanaka3a944772016-06-30 00:07:17 +00001257 unsigned InvalidBase : 1;
George Burgess IV3a03fab2015-09-04 21:28:13 +00001258 unsigned CallIndex : 31;
Richard Smith96e0c102011-11-04 02:25:55 +00001259 SubobjectDesignator Designator;
Yaxun Liu402804b2016-12-15 08:09:08 +00001260 bool IsNullPtr;
John McCall45d55e42010-05-07 21:00:08 +00001261
Richard Smithce40ad62011-11-12 22:28:03 +00001262 const APValue::LValueBase getLValueBase() const { return Base; }
Richard Smith0b0a0b62011-10-29 20:57:55 +00001263 CharUnits &getLValueOffset() { return Offset; }
Richard Smith8b3497e2011-10-31 01:37:14 +00001264 const CharUnits &getLValueOffset() const { return Offset; }
Richard Smithb228a862012-02-15 02:18:13 +00001265 unsigned getLValueCallIndex() const { return CallIndex; }
Richard Smith96e0c102011-11-04 02:25:55 +00001266 SubobjectDesignator &getLValueDesignator() { return Designator; }
1267 const SubobjectDesignator &getLValueDesignator() const { return Designator;}
Yaxun Liu402804b2016-12-15 08:09:08 +00001268 bool isNullPointer() const { return IsNullPtr;}
John McCall45d55e42010-05-07 21:00:08 +00001269
Richard Smith2e312c82012-03-03 22:46:17 +00001270 void moveInto(APValue &V) const {
1271 if (Designator.Invalid)
Yaxun Liu402804b2016-12-15 08:09:08 +00001272 V = APValue(Base, Offset, APValue::NoLValuePath(), CallIndex,
1273 IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001274 else {
1275 assert(!InvalidBase && "APValues can't handle invalid LValue bases");
Richard Smith2e312c82012-03-03 22:46:17 +00001276 V = APValue(Base, Offset, Designator.Entries,
Yaxun Liu402804b2016-12-15 08:09:08 +00001277 Designator.IsOnePastTheEnd, CallIndex, IsNullPtr);
George Burgess IVe3763372016-12-22 02:50:20 +00001278 }
John McCall45d55e42010-05-07 21:00:08 +00001279 }
Richard Smith2e312c82012-03-03 22:46:17 +00001280 void setFrom(ASTContext &Ctx, const APValue &V) {
George Burgess IVe3763372016-12-22 02:50:20 +00001281 assert(V.isLValue() && "Setting LValue from a non-LValue?");
Richard Smith0b0a0b62011-10-29 20:57:55 +00001282 Base = V.getLValueBase();
1283 Offset = V.getLValueOffset();
George Burgess IV3a03fab2015-09-04 21:28:13 +00001284 InvalidBase = false;
Richard Smithb228a862012-02-15 02:18:13 +00001285 CallIndex = V.getLValueCallIndex();
Richard Smith2e312c82012-03-03 22:46:17 +00001286 Designator = SubobjectDesignator(Ctx, V);
Yaxun Liu402804b2016-12-15 08:09:08 +00001287 IsNullPtr = V.isNullPointer();
Richard Smith96e0c102011-11-04 02:25:55 +00001288 }
1289
Tim Northover01503332017-05-26 02:16:00 +00001290 void set(APValue::LValueBase B, unsigned I = 0, bool BInvalid = false) {
George Burgess IVe3763372016-12-22 02:50:20 +00001291#ifndef NDEBUG
1292 // We only allow a few types of invalid bases. Enforce that here.
1293 if (BInvalid) {
1294 const auto *E = B.get<const Expr *>();
1295 assert((isa<MemberExpr>(E) || tryUnwrapAllocSizeCall(E)) &&
1296 "Unexpected type of invalid base");
1297 }
1298#endif
1299
Richard Smithce40ad62011-11-12 22:28:03 +00001300 Base = B;
Tim Northover01503332017-05-26 02:16:00 +00001301 Offset = CharUnits::fromQuantity(0);
George Burgess IV3a03fab2015-09-04 21:28:13 +00001302 InvalidBase = BInvalid;
Richard Smithb228a862012-02-15 02:18:13 +00001303 CallIndex = I;
Richard Smitha8105bc2012-01-06 16:39:00 +00001304 Designator = SubobjectDesignator(getType(B));
Tim Northover01503332017-05-26 02:16:00 +00001305 IsNullPtr = false;
1306 }
1307
1308 void setNull(QualType PointerTy, uint64_t TargetVal) {
1309 Base = (Expr *)nullptr;
1310 Offset = CharUnits::fromQuantity(TargetVal);
1311 InvalidBase = false;
1312 CallIndex = 0;
1313 Designator = SubobjectDesignator(PointerTy->getPointeeType());
1314 IsNullPtr = true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001315 }
1316
George Burgess IV3a03fab2015-09-04 21:28:13 +00001317 void setInvalid(APValue::LValueBase B, unsigned I = 0) {
1318 set(B, I, true);
1319 }
1320
Richard Smitha8105bc2012-01-06 16:39:00 +00001321 // Check that this LValue is not based on a null pointer. If it is, produce
1322 // a diagnostic and mark the designator as invalid.
1323 bool checkNullPointer(EvalInfo &Info, const Expr *E,
1324 CheckSubobjectKind CSK) {
1325 if (Designator.Invalid)
1326 return false;
Yaxun Liu402804b2016-12-15 08:09:08 +00001327 if (IsNullPtr) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001328 Info.CCEDiag(E, diag::note_constexpr_null_subobject)
Richard Smitha8105bc2012-01-06 16:39:00 +00001329 << CSK;
1330 Designator.setInvalid();
1331 return false;
1332 }
1333 return true;
1334 }
1335
1336 // Check this LValue refers to an object. If not, set the designator to be
1337 // invalid and emit a diagnostic.
1338 bool checkSubobject(EvalInfo &Info, const Expr *E, CheckSubobjectKind CSK) {
Richard Smith6c6bbfa2014-04-08 12:19:28 +00001339 return (CSK == CSK_ArrayToPointer || checkNullPointer(Info, E, CSK)) &&
Richard Smitha8105bc2012-01-06 16:39:00 +00001340 Designator.checkSubobject(Info, E, CSK);
1341 }
1342
1343 void addDecl(EvalInfo &Info, const Expr *E,
1344 const Decl *D, bool Virtual = false) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001345 if (checkSubobject(Info, E, isa<FieldDecl>(D) ? CSK_Field : CSK_Base))
1346 Designator.addDeclUnchecked(D, Virtual);
Richard Smitha8105bc2012-01-06 16:39:00 +00001347 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00001348 void addUnsizedArray(EvalInfo &Info, const Expr *E, QualType ElemTy) {
1349 if (!Designator.Entries.empty()) {
1350 Info.CCEDiag(E, diag::note_constexpr_unsupported_unsized_array);
1351 Designator.setInvalid();
1352 return;
1353 }
Richard Smithefdb5032017-11-15 03:03:56 +00001354 if (checkSubobject(Info, E, CSK_ArrayToPointer)) {
1355 assert(getType(Base)->isPointerType() || getType(Base)->isArrayType());
1356 Designator.FirstEntryIsAnUnsizedArray = true;
1357 Designator.addUnsizedArrayUnchecked(ElemTy);
1358 }
George Burgess IVe3763372016-12-22 02:50:20 +00001359 }
Richard Smitha8105bc2012-01-06 16:39:00 +00001360 void addArray(EvalInfo &Info, const Expr *E, const ConstantArrayType *CAT) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001361 if (checkSubobject(Info, E, CSK_ArrayToPointer))
1362 Designator.addArrayUnchecked(CAT);
Richard Smitha8105bc2012-01-06 16:39:00 +00001363 }
Richard Smith66c96992012-02-18 22:04:06 +00001364 void addComplex(EvalInfo &Info, const Expr *E, QualType EltTy, bool Imag) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00001365 if (checkSubobject(Info, E, Imag ? CSK_Imag : CSK_Real))
1366 Designator.addComplexUnchecked(EltTy, Imag);
Richard Smith66c96992012-02-18 22:04:06 +00001367 }
Yaxun Liu402804b2016-12-15 08:09:08 +00001368 void clearIsNullPointer() {
1369 IsNullPtr = false;
1370 }
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00001371 void adjustOffsetAndIndex(EvalInfo &Info, const Expr *E,
1372 const APSInt &Index, CharUnits ElementSize) {
Richard Smithd6cc1982017-01-31 02:23:02 +00001373 // An index of 0 has no effect. (In C, adding 0 to a null pointer is UB,
1374 // but we're not required to diagnose it and it's valid in C++.)
1375 if (!Index)
1376 return;
1377
1378 // Compute the new offset in the appropriate width, wrapping at 64 bits.
1379 // FIXME: When compiling for a 32-bit target, we should use 32-bit
1380 // offsets.
1381 uint64_t Offset64 = Offset.getQuantity();
1382 uint64_t ElemSize64 = ElementSize.getQuantity();
1383 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
1384 Offset = CharUnits::fromQuantity(Offset64 + ElemSize64 * Index64);
1385
1386 if (checkNullPointer(Info, E, CSK_ArrayIndex))
Yaxun Liu402804b2016-12-15 08:09:08 +00001387 Designator.adjustIndex(Info, E, Index);
Richard Smithd6cc1982017-01-31 02:23:02 +00001388 clearIsNullPointer();
Yaxun Liu402804b2016-12-15 08:09:08 +00001389 }
1390 void adjustOffset(CharUnits N) {
1391 Offset += N;
1392 if (N.getQuantity())
1393 clearIsNullPointer();
John McCallc07a0c72011-02-17 10:25:35 +00001394 }
John McCall45d55e42010-05-07 21:00:08 +00001395 };
Richard Smith027bf112011-11-17 22:56:20 +00001396
1397 struct MemberPtr {
1398 MemberPtr() {}
1399 explicit MemberPtr(const ValueDecl *Decl) :
1400 DeclAndIsDerivedMember(Decl, false), Path() {}
1401
1402 /// The member or (direct or indirect) field referred to by this member
1403 /// pointer, or 0 if this is a null member pointer.
1404 const ValueDecl *getDecl() const {
1405 return DeclAndIsDerivedMember.getPointer();
1406 }
1407 /// Is this actually a member of some type derived from the relevant class?
1408 bool isDerivedMember() const {
1409 return DeclAndIsDerivedMember.getInt();
1410 }
1411 /// Get the class which the declaration actually lives in.
1412 const CXXRecordDecl *getContainingRecord() const {
1413 return cast<CXXRecordDecl>(
1414 DeclAndIsDerivedMember.getPointer()->getDeclContext());
1415 }
1416
Richard Smith2e312c82012-03-03 22:46:17 +00001417 void moveInto(APValue &V) const {
1418 V = APValue(getDecl(), isDerivedMember(), Path);
Richard Smith027bf112011-11-17 22:56:20 +00001419 }
Richard Smith2e312c82012-03-03 22:46:17 +00001420 void setFrom(const APValue &V) {
Richard Smith027bf112011-11-17 22:56:20 +00001421 assert(V.isMemberPointer());
1422 DeclAndIsDerivedMember.setPointer(V.getMemberPointerDecl());
1423 DeclAndIsDerivedMember.setInt(V.isMemberPointerToDerivedMember());
1424 Path.clear();
1425 ArrayRef<const CXXRecordDecl*> P = V.getMemberPointerPath();
1426 Path.insert(Path.end(), P.begin(), P.end());
1427 }
1428
1429 /// DeclAndIsDerivedMember - The member declaration, and a flag indicating
1430 /// whether the member is a member of some class derived from the class type
1431 /// of the member pointer.
1432 llvm::PointerIntPair<const ValueDecl*, 1, bool> DeclAndIsDerivedMember;
1433 /// Path - The path of base/derived classes from the member declaration's
1434 /// class (exclusive) to the class type of the member pointer (inclusive).
1435 SmallVector<const CXXRecordDecl*, 4> Path;
1436
1437 /// Perform a cast towards the class of the Decl (either up or down the
1438 /// hierarchy).
1439 bool castBack(const CXXRecordDecl *Class) {
1440 assert(!Path.empty());
1441 const CXXRecordDecl *Expected;
1442 if (Path.size() >= 2)
1443 Expected = Path[Path.size() - 2];
1444 else
1445 Expected = getContainingRecord();
1446 if (Expected->getCanonicalDecl() != Class->getCanonicalDecl()) {
1447 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
1448 // if B does not contain the original member and is not a base or
1449 // derived class of the class containing the original member, the result
1450 // of the cast is undefined.
1451 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
1452 // (D::*). We consider that to be a language defect.
1453 return false;
1454 }
1455 Path.pop_back();
1456 return true;
1457 }
1458 /// Perform a base-to-derived member pointer cast.
1459 bool castToDerived(const CXXRecordDecl *Derived) {
1460 if (!getDecl())
1461 return true;
1462 if (!isDerivedMember()) {
1463 Path.push_back(Derived);
1464 return true;
1465 }
1466 if (!castBack(Derived))
1467 return false;
1468 if (Path.empty())
1469 DeclAndIsDerivedMember.setInt(false);
1470 return true;
1471 }
1472 /// Perform a derived-to-base member pointer cast.
1473 bool castToBase(const CXXRecordDecl *Base) {
1474 if (!getDecl())
1475 return true;
1476 if (Path.empty())
1477 DeclAndIsDerivedMember.setInt(true);
1478 if (isDerivedMember()) {
1479 Path.push_back(Base);
1480 return true;
1481 }
1482 return castBack(Base);
1483 }
1484 };
Richard Smith357362d2011-12-13 06:39:58 +00001485
Richard Smith7bb00672012-02-01 01:42:44 +00001486 /// Compare two member pointers, which are assumed to be of the same type.
1487 static bool operator==(const MemberPtr &LHS, const MemberPtr &RHS) {
1488 if (!LHS.getDecl() || !RHS.getDecl())
1489 return !LHS.getDecl() && !RHS.getDecl();
1490 if (LHS.getDecl()->getCanonicalDecl() != RHS.getDecl()->getCanonicalDecl())
1491 return false;
1492 return LHS.Path == RHS.Path;
1493 }
Alexander Kornienkoab9db512015-06-22 23:07:51 +00001494}
Chris Lattnercdf34e72008-07-11 22:52:41 +00001495
Richard Smith2e312c82012-03-03 22:46:17 +00001496static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E);
Richard Smithb228a862012-02-15 02:18:13 +00001497static bool EvaluateInPlace(APValue &Result, EvalInfo &Info,
1498 const LValue &This, const Expr *E,
Richard Smithb228a862012-02-15 02:18:13 +00001499 bool AllowNonLiteralTypes = false);
George Burgess IVf9013bf2017-02-10 22:52:29 +00001500static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
1501 bool InvalidBaseOK = false);
1502static bool EvaluatePointer(const Expr *E, LValue &Result, EvalInfo &Info,
1503 bool InvalidBaseOK = false);
Richard Smith027bf112011-11-17 22:56:20 +00001504static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
1505 EvalInfo &Info);
1506static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info);
George Burgess IV533ff002015-12-11 00:23:35 +00001507static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info);
Richard Smith2e312c82012-03-03 22:46:17 +00001508static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Chris Lattner6c4d2552009-10-28 23:59:40 +00001509 EvalInfo &Info);
Eli Friedman24c01542008-08-22 00:06:13 +00001510static bool EvaluateFloat(const Expr *E, APFloat &Result, EvalInfo &Info);
John McCall93d91dc2010-05-07 17:22:02 +00001511static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00001512static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
1513 EvalInfo &Info);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00001514static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result);
Chris Lattner05706e882008-07-11 18:11:29 +00001515
1516//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00001517// Misc utilities
1518//===----------------------------------------------------------------------===//
1519
Richard Smithd6cc1982017-01-31 02:23:02 +00001520/// Negate an APSInt in place, converting it to a signed form if necessary, and
1521/// preserving its value (by extending by up to one bit as needed).
1522static void negateAsSigned(APSInt &Int) {
1523 if (Int.isUnsigned() || Int.isMinSignedValue()) {
1524 Int = Int.extend(Int.getBitWidth() + 1);
1525 Int.setIsSigned(true);
1526 }
1527 Int = -Int;
1528}
1529
Richard Smith84401042013-06-03 05:03:02 +00001530/// Produce a string describing the given constexpr call.
1531static void describeCall(CallStackFrame *Frame, raw_ostream &Out) {
1532 unsigned ArgIndex = 0;
1533 bool IsMemberCall = isa<CXXMethodDecl>(Frame->Callee) &&
1534 !isa<CXXConstructorDecl>(Frame->Callee) &&
1535 cast<CXXMethodDecl>(Frame->Callee)->isInstance();
1536
1537 if (!IsMemberCall)
1538 Out << *Frame->Callee << '(';
1539
1540 if (Frame->This && IsMemberCall) {
1541 APValue Val;
1542 Frame->This->moveInto(Val);
1543 Val.printPretty(Out, Frame->Info.Ctx,
1544 Frame->This->Designator.MostDerivedType);
1545 // FIXME: Add parens around Val if needed.
1546 Out << "->" << *Frame->Callee << '(';
1547 IsMemberCall = false;
1548 }
1549
1550 for (FunctionDecl::param_const_iterator I = Frame->Callee->param_begin(),
1551 E = Frame->Callee->param_end(); I != E; ++I, ++ArgIndex) {
1552 if (ArgIndex > (unsigned)IsMemberCall)
1553 Out << ", ";
1554
1555 const ParmVarDecl *Param = *I;
1556 const APValue &Arg = Frame->Arguments[ArgIndex];
1557 Arg.printPretty(Out, Frame->Info.Ctx, Param->getType());
1558
1559 if (ArgIndex == 0 && IsMemberCall)
1560 Out << "->" << *Frame->Callee << '(';
1561 }
1562
1563 Out << ')';
1564}
1565
Richard Smithd9f663b2013-04-22 15:31:51 +00001566/// Evaluate an expression to see if it had side-effects, and discard its
1567/// result.
Richard Smith4e18ca52013-05-06 05:56:11 +00001568/// \return \c true if the caller should keep evaluating.
1569static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001570 APValue Scratch;
Richard Smith4e66f1f2013-11-06 02:19:10 +00001571 if (!Evaluate(Scratch, Info, E))
1572 // We don't need the value, but we might have skipped a side effect here.
1573 return Info.noteSideEffect();
Richard Smith4e18ca52013-05-06 05:56:11 +00001574 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00001575}
1576
Richard Smithd62306a2011-11-10 06:34:14 +00001577/// Should this call expression be treated as a string literal?
1578static bool IsStringLiteralCall(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00001579 unsigned Builtin = E->getBuiltinCallee();
Richard Smithd62306a2011-11-10 06:34:14 +00001580 return (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
1581 Builtin == Builtin::BI__builtin___NSStringMakeConstantString);
1582}
1583
Richard Smithce40ad62011-11-12 22:28:03 +00001584static bool IsGlobalLValue(APValue::LValueBase B) {
Richard Smithd62306a2011-11-10 06:34:14 +00001585 // C++11 [expr.const]p3 An address constant expression is a prvalue core
1586 // constant expression of pointer type that evaluates to...
1587
1588 // ... a null pointer value, or a prvalue core constant expression of type
1589 // std::nullptr_t.
Richard Smithce40ad62011-11-12 22:28:03 +00001590 if (!B) return true;
John McCall95007602010-05-10 23:27:23 +00001591
Richard Smithce40ad62011-11-12 22:28:03 +00001592 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
1593 // ... the address of an object with static storage duration,
1594 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1595 return VD->hasGlobalStorage();
1596 // ... the address of a function,
1597 return isa<FunctionDecl>(D);
1598 }
1599
1600 const Expr *E = B.get<const Expr*>();
Richard Smithd62306a2011-11-10 06:34:14 +00001601 switch (E->getStmtClass()) {
1602 default:
1603 return false;
Richard Smith0dea49e2012-02-18 04:58:18 +00001604 case Expr::CompoundLiteralExprClass: {
1605 const CompoundLiteralExpr *CLE = cast<CompoundLiteralExpr>(E);
1606 return CLE->isFileScope() && CLE->isLValue();
1607 }
Richard Smithe6c01442013-06-05 00:46:14 +00001608 case Expr::MaterializeTemporaryExprClass:
1609 // A materialized temporary might have been lifetime-extended to static
1610 // storage duration.
1611 return cast<MaterializeTemporaryExpr>(E)->getStorageDuration() == SD_Static;
Richard Smithd62306a2011-11-10 06:34:14 +00001612 // A string literal has static storage duration.
1613 case Expr::StringLiteralClass:
1614 case Expr::PredefinedExprClass:
1615 case Expr::ObjCStringLiteralClass:
1616 case Expr::ObjCEncodeExprClass:
Richard Smith6e525142011-12-27 12:18:28 +00001617 case Expr::CXXTypeidExprClass:
Francois Pichet0066db92012-04-16 04:08:35 +00001618 case Expr::CXXUuidofExprClass:
Richard Smithd62306a2011-11-10 06:34:14 +00001619 return true;
1620 case Expr::CallExprClass:
1621 return IsStringLiteralCall(cast<CallExpr>(E));
1622 // For GCC compatibility, &&label has static storage duration.
1623 case Expr::AddrLabelExprClass:
1624 return true;
1625 // A Block literal expression may be used as the initialization value for
1626 // Block variables at global or local static scope.
1627 case Expr::BlockExprClass:
1628 return !cast<BlockExpr>(E)->getBlockDecl()->hasCaptures();
Richard Smith253c2a32012-01-27 01:14:48 +00001629 case Expr::ImplicitValueInitExprClass:
1630 // FIXME:
1631 // We can never form an lvalue with an implicit value initialization as its
1632 // base through expression evaluation, so these only appear in one case: the
1633 // implicit variable declaration we invent when checking whether a constexpr
1634 // constructor can produce a constant expression. We must assume that such
1635 // an expression might be a global lvalue.
1636 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00001637 }
John McCall95007602010-05-10 23:27:23 +00001638}
1639
Richard Smithb228a862012-02-15 02:18:13 +00001640static void NoteLValueLocation(EvalInfo &Info, APValue::LValueBase Base) {
1641 assert(Base && "no location for a null lvalue");
1642 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
1643 if (VD)
1644 Info.Note(VD->getLocation(), diag::note_declared_at);
1645 else
Ted Kremenek28831752012-08-23 20:46:57 +00001646 Info.Note(Base.get<const Expr*>()->getExprLoc(),
Richard Smithb228a862012-02-15 02:18:13 +00001647 diag::note_constexpr_temporary_here);
1648}
1649
Richard Smith80815602011-11-07 05:07:52 +00001650/// Check that this reference or pointer core constant expression is a valid
Richard Smith2e312c82012-03-03 22:46:17 +00001651/// value for an address or reference constant expression. Return true if we
1652/// can fold this expression, whether or not it's a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +00001653static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
1654 QualType Type, const LValue &LVal) {
1655 bool IsReferenceType = Type->isReferenceType();
1656
Richard Smith357362d2011-12-13 06:39:58 +00001657 APValue::LValueBase Base = LVal.getLValueBase();
1658 const SubobjectDesignator &Designator = LVal.getLValueDesignator();
1659
Richard Smith0dea49e2012-02-18 04:58:18 +00001660 // Check that the object is a global. Note that the fake 'this' object we
1661 // manufacture when checking potential constant expressions is conservatively
1662 // assumed to be global here.
Richard Smith357362d2011-12-13 06:39:58 +00001663 if (!IsGlobalLValue(Base)) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001664 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00001665 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001666 Info.FFDiag(Loc, diag::note_constexpr_non_global, 1)
Richard Smithb228a862012-02-15 02:18:13 +00001667 << IsReferenceType << !Designator.Entries.empty()
1668 << !!VD << VD;
1669 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001670 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00001671 Info.FFDiag(Loc);
Richard Smith357362d2011-12-13 06:39:58 +00001672 }
Richard Smith02ab9c22012-01-12 06:08:57 +00001673 // Don't allow references to temporaries to escape.
Richard Smith80815602011-11-07 05:07:52 +00001674 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00001675 }
Richard Smith6d4c6582013-11-05 22:18:15 +00001676 assert((Info.checkingPotentialConstantExpression() ||
Richard Smithb228a862012-02-15 02:18:13 +00001677 LVal.getLValueCallIndex() == 0) &&
1678 "have call index for global lvalue");
Richard Smitha8105bc2012-01-06 16:39:00 +00001679
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001680 if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
1681 if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
David Majnemer0c43d802014-06-25 08:15:07 +00001682 // Check if this is a thread-local variable.
Richard Smithfd3834f2013-04-13 02:43:54 +00001683 if (Var->getTLSKind())
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001684 return false;
David Majnemer0c43d802014-06-25 08:15:07 +00001685
Hans Wennborg82dd8772014-06-25 22:19:48 +00001686 // A dllimport variable never acts like a constant.
1687 if (Var->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001688 return false;
1689 }
1690 if (const auto *FD = dyn_cast<const FunctionDecl>(VD)) {
1691 // __declspec(dllimport) must be handled very carefully:
1692 // We must never initialize an expression with the thunk in C++.
1693 // Doing otherwise would allow the same id-expression to yield
1694 // different addresses for the same function in different translation
1695 // units. However, this means that we must dynamically initialize the
1696 // expression with the contents of the import address table at runtime.
1697 //
1698 // The C language has no notion of ODR; furthermore, it has no notion of
1699 // dynamic initialization. This means that we are permitted to
1700 // perform initialization with the address of the thunk.
Hans Wennborg82dd8772014-06-25 22:19:48 +00001701 if (Info.getLangOpts().CPlusPlus && FD->hasAttr<DLLImportAttr>())
David Majnemer0c43d802014-06-25 08:15:07 +00001702 return false;
Hans Wennborgcb9ad992012-08-29 18:27:29 +00001703 }
1704 }
1705
Richard Smitha8105bc2012-01-06 16:39:00 +00001706 // Allow address constant expressions to be past-the-end pointers. This is
1707 // an extension: the standard requires them to point to an object.
1708 if (!IsReferenceType)
1709 return true;
1710
1711 // A reference constant expression must refer to an object.
1712 if (!Base) {
1713 // FIXME: diagnostic
Richard Smithb228a862012-02-15 02:18:13 +00001714 Info.CCEDiag(Loc);
Richard Smith02ab9c22012-01-12 06:08:57 +00001715 return true;
Richard Smitha8105bc2012-01-06 16:39:00 +00001716 }
1717
Richard Smith357362d2011-12-13 06:39:58 +00001718 // Does this refer one past the end of some object?
Richard Smith33b44ab2014-07-23 23:50:25 +00001719 if (!Designator.Invalid && Designator.isOnePastTheEnd()) {
Richard Smith357362d2011-12-13 06:39:58 +00001720 const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>();
Faisal Valie690b7a2016-07-02 22:34:24 +00001721 Info.FFDiag(Loc, diag::note_constexpr_past_end, 1)
Richard Smith357362d2011-12-13 06:39:58 +00001722 << !Designator.Entries.empty() << !!VD << VD;
Richard Smithb228a862012-02-15 02:18:13 +00001723 NoteLValueLocation(Info, Base);
Richard Smith357362d2011-12-13 06:39:58 +00001724 }
1725
Richard Smith80815602011-11-07 05:07:52 +00001726 return true;
1727}
1728
Reid Klecknercd016d82017-07-07 22:04:29 +00001729/// Member pointers are constant expressions unless they point to a
1730/// non-virtual dllimport member function.
1731static bool CheckMemberPointerConstantExpression(EvalInfo &Info,
1732 SourceLocation Loc,
1733 QualType Type,
1734 const APValue &Value) {
1735 const ValueDecl *Member = Value.getMemberPointerDecl();
1736 const auto *FD = dyn_cast_or_null<CXXMethodDecl>(Member);
1737 if (!FD)
1738 return true;
1739 return FD->isVirtual() || !FD->hasAttr<DLLImportAttr>();
1740}
1741
Richard Smithfddd3842011-12-30 21:15:51 +00001742/// Check that this core constant expression is of literal type, and if not,
1743/// produce an appropriate diagnostic.
Richard Smith7525ff62013-05-09 07:14:00 +00001744static bool CheckLiteralType(EvalInfo &Info, const Expr *E,
Craig Topper36250ad2014-05-12 05:36:57 +00001745 const LValue *This = nullptr) {
Richard Smithd9f663b2013-04-22 15:31:51 +00001746 if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
Richard Smithfddd3842011-12-30 21:15:51 +00001747 return true;
1748
Richard Smith7525ff62013-05-09 07:14:00 +00001749 // C++1y: A constant initializer for an object o [...] may also invoke
1750 // constexpr constructors for o and its subobjects even if those objects
1751 // are of non-literal class types.
David L. Jonesf55ce362017-01-09 21:38:07 +00001752 //
1753 // C++11 missed this detail for aggregates, so classes like this:
1754 // struct foo_t { union { int i; volatile int j; } u; };
1755 // are not (obviously) initializable like so:
1756 // __attribute__((__require_constant_initialization__))
1757 // static const foo_t x = {{0}};
1758 // because "i" is a subobject with non-literal initialization (due to the
1759 // volatile member of the union). See:
1760 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1761 // Therefore, we use the C++1y behavior.
1762 if (This && Info.EvaluatingDecl == This->getLValueBase())
Richard Smith7525ff62013-05-09 07:14:00 +00001763 return true;
1764
Richard Smithfddd3842011-12-30 21:15:51 +00001765 // Prvalue constant expressions must be of literal types.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00001766 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00001767 Info.FFDiag(E, diag::note_constexpr_nonliteral)
Richard Smithfddd3842011-12-30 21:15:51 +00001768 << E->getType();
1769 else
Faisal Valie690b7a2016-07-02 22:34:24 +00001770 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfddd3842011-12-30 21:15:51 +00001771 return false;
1772}
1773
Richard Smith0b0a0b62011-10-29 20:57:55 +00001774/// Check that this core constant expression value is a valid value for a
Richard Smithb228a862012-02-15 02:18:13 +00001775/// constant expression. If not, report an appropriate diagnostic. Does not
1776/// check that the expression is of literal type.
1777static bool CheckConstantExpression(EvalInfo &Info, SourceLocation DiagLoc,
1778 QualType Type, const APValue &Value) {
Richard Smith1a90f592013-06-18 17:51:51 +00001779 if (Value.isUninit()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00001780 Info.FFDiag(DiagLoc, diag::note_constexpr_uninitialized)
Richard Smith51f03172013-06-20 03:00:05 +00001781 << true << Type;
Richard Smith1a90f592013-06-18 17:51:51 +00001782 return false;
1783 }
1784
Richard Smith77be48a2014-07-31 06:31:19 +00001785 // We allow _Atomic(T) to be initialized from anything that T can be
1786 // initialized from.
1787 if (const AtomicType *AT = Type->getAs<AtomicType>())
1788 Type = AT->getValueType();
1789
Richard Smithb228a862012-02-15 02:18:13 +00001790 // Core issue 1454: For a literal constant expression of array or class type,
1791 // each subobject of its value shall have been initialized by a constant
1792 // expression.
1793 if (Value.isArray()) {
1794 QualType EltTy = Type->castAsArrayTypeUnsafe()->getElementType();
1795 for (unsigned I = 0, N = Value.getArrayInitializedElts(); I != N; ++I) {
1796 if (!CheckConstantExpression(Info, DiagLoc, EltTy,
1797 Value.getArrayInitializedElt(I)))
1798 return false;
1799 }
1800 if (!Value.hasArrayFiller())
1801 return true;
1802 return CheckConstantExpression(Info, DiagLoc, EltTy,
1803 Value.getArrayFiller());
Richard Smith80815602011-11-07 05:07:52 +00001804 }
Richard Smithb228a862012-02-15 02:18:13 +00001805 if (Value.isUnion() && Value.getUnionField()) {
1806 return CheckConstantExpression(Info, DiagLoc,
1807 Value.getUnionField()->getType(),
1808 Value.getUnionValue());
1809 }
1810 if (Value.isStruct()) {
1811 RecordDecl *RD = Type->castAs<RecordType>()->getDecl();
1812 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) {
1813 unsigned BaseIndex = 0;
1814 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
1815 End = CD->bases_end(); I != End; ++I, ++BaseIndex) {
1816 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1817 Value.getStructBase(BaseIndex)))
1818 return false;
1819 }
1820 }
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00001821 for (const auto *I : RD->fields()) {
Jordan Rosed4503da2017-10-24 02:17:07 +00001822 if (I->isUnnamedBitfield())
1823 continue;
1824
David Blaikie2d7c57e2012-04-30 02:36:29 +00001825 if (!CheckConstantExpression(Info, DiagLoc, I->getType(),
1826 Value.getStructField(I->getFieldIndex())))
Richard Smithb228a862012-02-15 02:18:13 +00001827 return false;
1828 }
1829 }
1830
1831 if (Value.isLValue()) {
Richard Smithb228a862012-02-15 02:18:13 +00001832 LValue LVal;
Richard Smith2e312c82012-03-03 22:46:17 +00001833 LVal.setFrom(Info.Ctx, Value);
Richard Smithb228a862012-02-15 02:18:13 +00001834 return CheckLValueConstantExpression(Info, DiagLoc, Type, LVal);
1835 }
1836
Reid Klecknercd016d82017-07-07 22:04:29 +00001837 if (Value.isMemberPointer())
1838 return CheckMemberPointerConstantExpression(Info, DiagLoc, Type, Value);
1839
Richard Smithb228a862012-02-15 02:18:13 +00001840 // Everything else is fine.
1841 return true;
Richard Smith0b0a0b62011-10-29 20:57:55 +00001842}
1843
Benjamin Kramer8407df72015-03-09 16:47:52 +00001844static const ValueDecl *GetLValueBaseDecl(const LValue &LVal) {
Richard Smithce40ad62011-11-12 22:28:03 +00001845 return LVal.Base.dyn_cast<const ValueDecl*>();
Richard Smith83c68212011-10-31 05:11:32 +00001846}
1847
1848static bool IsLiteralLValue(const LValue &Value) {
Richard Smithe6c01442013-06-05 00:46:14 +00001849 if (Value.CallIndex)
1850 return false;
1851 const Expr *E = Value.Base.dyn_cast<const Expr*>();
1852 return E && !isa<MaterializeTemporaryExpr>(E);
Richard Smith83c68212011-10-31 05:11:32 +00001853}
1854
Richard Smithcecf1842011-11-01 21:06:14 +00001855static bool IsWeakLValue(const LValue &Value) {
1856 const ValueDecl *Decl = GetLValueBaseDecl(Value);
Lang Hamesd42bb472011-12-05 20:16:26 +00001857 return Decl && Decl->isWeak();
Richard Smithcecf1842011-11-01 21:06:14 +00001858}
1859
David Majnemerb5116032014-12-09 23:32:34 +00001860static bool isZeroSized(const LValue &Value) {
1861 const ValueDecl *Decl = GetLValueBaseDecl(Value);
David Majnemer27db3582014-12-11 19:36:24 +00001862 if (Decl && isa<VarDecl>(Decl)) {
1863 QualType Ty = Decl->getType();
David Majnemer8c92b872014-12-14 08:40:47 +00001864 if (Ty->isArrayType())
1865 return Ty->isIncompleteType() ||
1866 Decl->getASTContext().getTypeSize(Ty) == 0;
David Majnemer27db3582014-12-11 19:36:24 +00001867 }
1868 return false;
David Majnemerb5116032014-12-09 23:32:34 +00001869}
1870
Richard Smith2e312c82012-03-03 22:46:17 +00001871static bool EvalPointerValueAsBool(const APValue &Value, bool &Result) {
John McCalleb3e4f32010-05-07 21:34:32 +00001872 // A null base expression indicates a null pointer. These are always
1873 // evaluatable, and they are false unless the offset is zero.
Richard Smith027bf112011-11-17 22:56:20 +00001874 if (!Value.getLValueBase()) {
1875 Result = !Value.getLValueOffset().isZero();
John McCalleb3e4f32010-05-07 21:34:32 +00001876 return true;
1877 }
Rafael Espindolaa1f9cc12010-05-07 15:18:43 +00001878
Richard Smith027bf112011-11-17 22:56:20 +00001879 // We have a non-null base. These are generally known to be true, but if it's
1880 // a weak declaration it can be null at runtime.
John McCalleb3e4f32010-05-07 21:34:32 +00001881 Result = true;
Richard Smith027bf112011-11-17 22:56:20 +00001882 const ValueDecl *Decl = Value.getLValueBase().dyn_cast<const ValueDecl*>();
Lang Hamesd42bb472011-12-05 20:16:26 +00001883 return !Decl || !Decl->isWeak();
Eli Friedman334046a2009-06-14 02:17:33 +00001884}
1885
Richard Smith2e312c82012-03-03 22:46:17 +00001886static bool HandleConversionToBool(const APValue &Val, bool &Result) {
Richard Smith11562c52011-10-28 17:51:58 +00001887 switch (Val.getKind()) {
1888 case APValue::Uninitialized:
1889 return false;
1890 case APValue::Int:
1891 Result = Val.getInt().getBoolValue();
Eli Friedman9a156e52008-11-12 09:44:48 +00001892 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001893 case APValue::Float:
1894 Result = !Val.getFloat().isZero();
Eli Friedman9a156e52008-11-12 09:44:48 +00001895 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001896 case APValue::ComplexInt:
1897 Result = Val.getComplexIntReal().getBoolValue() ||
1898 Val.getComplexIntImag().getBoolValue();
1899 return true;
1900 case APValue::ComplexFloat:
1901 Result = !Val.getComplexFloatReal().isZero() ||
1902 !Val.getComplexFloatImag().isZero();
1903 return true;
Richard Smith027bf112011-11-17 22:56:20 +00001904 case APValue::LValue:
1905 return EvalPointerValueAsBool(Val, Result);
1906 case APValue::MemberPointer:
1907 Result = Val.getMemberPointerDecl();
1908 return true;
Richard Smith11562c52011-10-28 17:51:58 +00001909 case APValue::Vector:
Richard Smithf3e9e432011-11-07 09:22:26 +00001910 case APValue::Array:
Richard Smithd62306a2011-11-10 06:34:14 +00001911 case APValue::Struct:
1912 case APValue::Union:
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00001913 case APValue::AddrLabelDiff:
Richard Smith11562c52011-10-28 17:51:58 +00001914 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00001915 }
1916
Richard Smith11562c52011-10-28 17:51:58 +00001917 llvm_unreachable("unknown APValue kind");
1918}
1919
1920static bool EvaluateAsBooleanCondition(const Expr *E, bool &Result,
1921 EvalInfo &Info) {
1922 assert(E->isRValue() && "missing lvalue-to-rvalue conv in bool condition");
Richard Smith2e312c82012-03-03 22:46:17 +00001923 APValue Val;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001924 if (!Evaluate(Val, Info, E))
Richard Smith11562c52011-10-28 17:51:58 +00001925 return false;
Argyrios Kyrtzidis91d00982012-02-27 20:21:34 +00001926 return HandleConversionToBool(Val, Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00001927}
1928
Richard Smith357362d2011-12-13 06:39:58 +00001929template<typename T>
Richard Smith0c6124b2015-12-03 01:36:22 +00001930static bool HandleOverflow(EvalInfo &Info, const Expr *E,
Richard Smith357362d2011-12-13 06:39:58 +00001931 const T &SrcValue, QualType DestType) {
Eli Friedman4eafb6b2012-07-17 21:03:05 +00001932 Info.CCEDiag(E, diag::note_constexpr_overflow)
Richard Smithfe800032012-01-31 04:08:20 +00001933 << SrcValue << DestType;
Richard Smithce8eca52015-12-08 03:21:47 +00001934 return Info.noteUndefinedBehavior();
Richard Smith357362d2011-12-13 06:39:58 +00001935}
1936
1937static bool HandleFloatToIntCast(EvalInfo &Info, const Expr *E,
1938 QualType SrcType, const APFloat &Value,
1939 QualType DestType, APSInt &Result) {
1940 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001941 // Determine whether we are converting to unsigned or signed.
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001942 bool DestSigned = DestType->isSignedIntegerOrEnumerationType();
Mike Stump11289f42009-09-09 15:08:12 +00001943
Richard Smith357362d2011-12-13 06:39:58 +00001944 Result = APSInt(DestWidth, !DestSigned);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001945 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001946 if (Value.convertToInteger(Result, llvm::APFloat::rmTowardZero, &ignored)
1947 & APFloat::opInvalidOp)
Richard Smith0c6124b2015-12-03 01:36:22 +00001948 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001949 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001950}
1951
Richard Smith357362d2011-12-13 06:39:58 +00001952static bool HandleFloatToFloatCast(EvalInfo &Info, const Expr *E,
1953 QualType SrcType, QualType DestType,
1954 APFloat &Result) {
1955 APFloat Value = Result;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001956 bool ignored;
Richard Smith357362d2011-12-13 06:39:58 +00001957 if (Result.convert(Info.Ctx.getFloatTypeSemantics(DestType),
1958 APFloat::rmNearestTiesToEven, &ignored)
1959 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001960 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001961 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001962}
1963
Richard Smith911e1422012-01-30 22:27:01 +00001964static APSInt HandleIntToIntCast(EvalInfo &Info, const Expr *E,
1965 QualType DestType, QualType SrcType,
George Burgess IV533ff002015-12-11 00:23:35 +00001966 const APSInt &Value) {
Richard Smith911e1422012-01-30 22:27:01 +00001967 unsigned DestWidth = Info.Ctx.getIntWidth(DestType);
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001968 APSInt Result = Value;
1969 // Figure out if this is a truncate, extend or noop cast.
1970 // If the input is signed, do a sign extend, noop, or truncate.
Jay Foad6d4db0c2010-12-07 08:25:34 +00001971 Result = Result.extOrTrunc(DestWidth);
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00001972 Result.setIsUnsigned(DestType->isUnsignedIntegerOrEnumerationType());
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001973 return Result;
1974}
1975
Richard Smith357362d2011-12-13 06:39:58 +00001976static bool HandleIntToFloatCast(EvalInfo &Info, const Expr *E,
1977 QualType SrcType, const APSInt &Value,
1978 QualType DestType, APFloat &Result) {
1979 Result = APFloat(Info.Ctx.getFloatTypeSemantics(DestType), 1);
1980 if (Result.convertFromAPInt(Value, Value.isSigned(),
1981 APFloat::rmNearestTiesToEven)
1982 & APFloat::opOverflow)
Richard Smith0c6124b2015-12-03 01:36:22 +00001983 return HandleOverflow(Info, E, Value, DestType);
Richard Smith357362d2011-12-13 06:39:58 +00001984 return true;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00001985}
1986
Richard Smith49ca8aa2013-08-06 07:09:20 +00001987static bool truncateBitfieldValue(EvalInfo &Info, const Expr *E,
1988 APValue &Value, const FieldDecl *FD) {
1989 assert(FD->isBitField() && "truncateBitfieldValue on non-bitfield");
1990
1991 if (!Value.isInt()) {
1992 // Trying to store a pointer-cast-to-integer into a bitfield.
1993 // FIXME: In this case, we should provide the diagnostic for casting
1994 // a pointer to an integer.
1995 assert(Value.isLValue() && "integral value neither int nor lvalue?");
Faisal Valie690b7a2016-07-02 22:34:24 +00001996 Info.FFDiag(E);
Richard Smith49ca8aa2013-08-06 07:09:20 +00001997 return false;
1998 }
1999
2000 APSInt &Int = Value.getInt();
2001 unsigned OldBitWidth = Int.getBitWidth();
2002 unsigned NewBitWidth = FD->getBitWidthValue(Info.Ctx);
2003 if (NewBitWidth < OldBitWidth)
2004 Int = Int.trunc(NewBitWidth).extend(OldBitWidth);
2005 return true;
2006}
2007
Eli Friedman803acb32011-12-22 03:51:45 +00002008static bool EvalAndBitcastToAPInt(EvalInfo &Info, const Expr *E,
2009 llvm::APInt &Res) {
Richard Smith2e312c82012-03-03 22:46:17 +00002010 APValue SVal;
Eli Friedman803acb32011-12-22 03:51:45 +00002011 if (!Evaluate(SVal, Info, E))
2012 return false;
2013 if (SVal.isInt()) {
2014 Res = SVal.getInt();
2015 return true;
2016 }
2017 if (SVal.isFloat()) {
2018 Res = SVal.getFloat().bitcastToAPInt();
2019 return true;
2020 }
2021 if (SVal.isVector()) {
2022 QualType VecTy = E->getType();
2023 unsigned VecSize = Info.Ctx.getTypeSize(VecTy);
2024 QualType EltTy = VecTy->castAs<VectorType>()->getElementType();
2025 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
2026 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
2027 Res = llvm::APInt::getNullValue(VecSize);
2028 for (unsigned i = 0; i < SVal.getVectorLength(); i++) {
2029 APValue &Elt = SVal.getVectorElt(i);
2030 llvm::APInt EltAsInt;
2031 if (Elt.isInt()) {
2032 EltAsInt = Elt.getInt();
2033 } else if (Elt.isFloat()) {
2034 EltAsInt = Elt.getFloat().bitcastToAPInt();
2035 } else {
2036 // Don't try to handle vectors of anything other than int or float
2037 // (not sure if it's possible to hit this case).
Faisal Valie690b7a2016-07-02 22:34:24 +00002038 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002039 return false;
2040 }
2041 unsigned BaseEltSize = EltAsInt.getBitWidth();
2042 if (BigEndian)
2043 Res |= EltAsInt.zextOrTrunc(VecSize).rotr(i*EltSize+BaseEltSize);
2044 else
2045 Res |= EltAsInt.zextOrTrunc(VecSize).rotl(i*EltSize);
2046 }
2047 return true;
2048 }
2049 // Give up if the input isn't an int, float, or vector. For example, we
2050 // reject "(v4i16)(intptr_t)&a".
Faisal Valie690b7a2016-07-02 22:34:24 +00002051 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Eli Friedman803acb32011-12-22 03:51:45 +00002052 return false;
2053}
2054
Richard Smith43e77732013-05-07 04:50:00 +00002055/// Perform the given integer operation, which is known to need at most BitWidth
2056/// bits, and check for overflow in the original type (if that type was not an
2057/// unsigned type).
2058template<typename Operation>
Richard Smith0c6124b2015-12-03 01:36:22 +00002059static bool CheckedIntArithmetic(EvalInfo &Info, const Expr *E,
2060 const APSInt &LHS, const APSInt &RHS,
2061 unsigned BitWidth, Operation Op,
2062 APSInt &Result) {
2063 if (LHS.isUnsigned()) {
2064 Result = Op(LHS, RHS);
2065 return true;
2066 }
Richard Smith43e77732013-05-07 04:50:00 +00002067
2068 APSInt Value(Op(LHS.extend(BitWidth), RHS.extend(BitWidth)), false);
Richard Smith0c6124b2015-12-03 01:36:22 +00002069 Result = Value.trunc(LHS.getBitWidth());
Richard Smith43e77732013-05-07 04:50:00 +00002070 if (Result.extend(BitWidth) != Value) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002071 if (Info.checkingForOverflow())
Richard Smith43e77732013-05-07 04:50:00 +00002072 Info.Ctx.getDiagnostics().Report(E->getExprLoc(),
Richard Smith0c6124b2015-12-03 01:36:22 +00002073 diag::warn_integer_constant_overflow)
Richard Smith43e77732013-05-07 04:50:00 +00002074 << Result.toString(10) << E->getType();
2075 else
Richard Smith0c6124b2015-12-03 01:36:22 +00002076 return HandleOverflow(Info, E, Value, E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002077 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002078 return true;
Richard Smith43e77732013-05-07 04:50:00 +00002079}
2080
2081/// Perform the given binary integer operation.
2082static bool handleIntIntBinOp(EvalInfo &Info, const Expr *E, const APSInt &LHS,
2083 BinaryOperatorKind Opcode, APSInt RHS,
2084 APSInt &Result) {
2085 switch (Opcode) {
2086 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002087 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00002088 return false;
2089 case BO_Mul:
Richard Smith0c6124b2015-12-03 01:36:22 +00002090 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() * 2,
2091 std::multiplies<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002092 case BO_Add:
Richard Smith0c6124b2015-12-03 01:36:22 +00002093 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2094 std::plus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002095 case BO_Sub:
Richard Smith0c6124b2015-12-03 01:36:22 +00002096 return CheckedIntArithmetic(Info, E, LHS, RHS, LHS.getBitWidth() + 1,
2097 std::minus<APSInt>(), Result);
Richard Smith43e77732013-05-07 04:50:00 +00002098 case BO_And: Result = LHS & RHS; return true;
2099 case BO_Xor: Result = LHS ^ RHS; return true;
2100 case BO_Or: Result = LHS | RHS; return true;
2101 case BO_Div:
2102 case BO_Rem:
2103 if (RHS == 0) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002104 Info.FFDiag(E, diag::note_expr_divide_by_zero);
Richard Smith43e77732013-05-07 04:50:00 +00002105 return false;
2106 }
Richard Smith0c6124b2015-12-03 01:36:22 +00002107 Result = (Opcode == BO_Rem ? LHS % RHS : LHS / RHS);
2108 // Check for overflow case: INT_MIN / -1 or INT_MIN % -1. APSInt supports
2109 // this operation and gives the two's complement result.
Richard Smith43e77732013-05-07 04:50:00 +00002110 if (RHS.isNegative() && RHS.isAllOnesValue() &&
2111 LHS.isSigned() && LHS.isMinSignedValue())
Richard Smith0c6124b2015-12-03 01:36:22 +00002112 return HandleOverflow(Info, E, -LHS.extend(LHS.getBitWidth() + 1),
2113 E->getType());
Richard Smith43e77732013-05-07 04:50:00 +00002114 return true;
2115 case BO_Shl: {
2116 if (Info.getLangOpts().OpenCL)
2117 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2118 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2119 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2120 RHS.isUnsigned());
2121 else if (RHS.isSigned() && RHS.isNegative()) {
2122 // During constant-folding, a negative shift is an opposite shift. Such
2123 // a shift is not a constant expression.
2124 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2125 RHS = -RHS;
2126 goto shift_right;
2127 }
2128 shift_left:
2129 // C++11 [expr.shift]p1: Shift width must be less than the bit width of
2130 // the shifted type.
2131 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2132 if (SA != RHS) {
2133 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2134 << RHS << E->getType() << LHS.getBitWidth();
2135 } else if (LHS.isSigned()) {
2136 // C++11 [expr.shift]p2: A signed left shift must have a non-negative
2137 // operand, and must not overflow the corresponding unsigned type.
2138 if (LHS.isNegative())
2139 Info.CCEDiag(E, diag::note_constexpr_lshift_of_negative) << LHS;
2140 else if (LHS.countLeadingZeros() < SA)
2141 Info.CCEDiag(E, diag::note_constexpr_lshift_discards);
2142 }
2143 Result = LHS << SA;
2144 return true;
2145 }
2146 case BO_Shr: {
2147 if (Info.getLangOpts().OpenCL)
2148 // OpenCL 6.3j: shift values are effectively % word size of LHS.
2149 RHS &= APSInt(llvm::APInt(RHS.getBitWidth(),
2150 static_cast<uint64_t>(LHS.getBitWidth() - 1)),
2151 RHS.isUnsigned());
2152 else if (RHS.isSigned() && RHS.isNegative()) {
2153 // During constant-folding, a negative shift is an opposite shift. Such a
2154 // shift is not a constant expression.
2155 Info.CCEDiag(E, diag::note_constexpr_negative_shift) << RHS;
2156 RHS = -RHS;
2157 goto shift_left;
2158 }
2159 shift_right:
2160 // C++11 [expr.shift]p1: Shift width must be less than the bit width of the
2161 // shifted type.
2162 unsigned SA = (unsigned) RHS.getLimitedValue(LHS.getBitWidth()-1);
2163 if (SA != RHS)
2164 Info.CCEDiag(E, diag::note_constexpr_large_shift)
2165 << RHS << E->getType() << LHS.getBitWidth();
2166 Result = LHS >> SA;
2167 return true;
2168 }
2169
2170 case BO_LT: Result = LHS < RHS; return true;
2171 case BO_GT: Result = LHS > RHS; return true;
2172 case BO_LE: Result = LHS <= RHS; return true;
2173 case BO_GE: Result = LHS >= RHS; return true;
2174 case BO_EQ: Result = LHS == RHS; return true;
2175 case BO_NE: Result = LHS != RHS; return true;
2176 }
2177}
2178
Richard Smith861b5b52013-05-07 23:34:45 +00002179/// Perform the given binary floating-point operation, in-place, on LHS.
2180static bool handleFloatFloatBinOp(EvalInfo &Info, const Expr *E,
2181 APFloat &LHS, BinaryOperatorKind Opcode,
2182 const APFloat &RHS) {
2183 switch (Opcode) {
2184 default:
Faisal Valie690b7a2016-07-02 22:34:24 +00002185 Info.FFDiag(E);
Richard Smith861b5b52013-05-07 23:34:45 +00002186 return false;
2187 case BO_Mul:
2188 LHS.multiply(RHS, APFloat::rmNearestTiesToEven);
2189 break;
2190 case BO_Add:
2191 LHS.add(RHS, APFloat::rmNearestTiesToEven);
2192 break;
2193 case BO_Sub:
2194 LHS.subtract(RHS, APFloat::rmNearestTiesToEven);
2195 break;
2196 case BO_Div:
2197 LHS.divide(RHS, APFloat::rmNearestTiesToEven);
2198 break;
2199 }
2200
Richard Smith0c6124b2015-12-03 01:36:22 +00002201 if (LHS.isInfinity() || LHS.isNaN()) {
Richard Smith861b5b52013-05-07 23:34:45 +00002202 Info.CCEDiag(E, diag::note_constexpr_float_arithmetic) << LHS.isNaN();
Richard Smithce8eca52015-12-08 03:21:47 +00002203 return Info.noteUndefinedBehavior();
Richard Smith0c6124b2015-12-03 01:36:22 +00002204 }
Richard Smith861b5b52013-05-07 23:34:45 +00002205 return true;
2206}
2207
Richard Smitha8105bc2012-01-06 16:39:00 +00002208/// Cast an lvalue referring to a base subobject to a derived class, by
2209/// truncating the lvalue's path to the given length.
2210static bool CastToDerivedClass(EvalInfo &Info, const Expr *E, LValue &Result,
2211 const RecordDecl *TruncatedType,
2212 unsigned TruncatedElements) {
Richard Smith027bf112011-11-17 22:56:20 +00002213 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00002214
2215 // Check we actually point to a derived class object.
2216 if (TruncatedElements == D.Entries.size())
2217 return true;
2218 assert(TruncatedElements >= D.MostDerivedPathLength &&
2219 "not casting to a derived class");
2220 if (!Result.checkSubobject(Info, E, CSK_Derived))
2221 return false;
2222
2223 // Truncate the path to the subobject, and remove any derived-to-base offsets.
Richard Smith027bf112011-11-17 22:56:20 +00002224 const RecordDecl *RD = TruncatedType;
2225 for (unsigned I = TruncatedElements, N = D.Entries.size(); I != N; ++I) {
John McCalld7bca762012-05-01 00:38:49 +00002226 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002227 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
2228 const CXXRecordDecl *Base = getAsBaseClass(D.Entries[I]);
Richard Smith027bf112011-11-17 22:56:20 +00002229 if (isVirtualBaseClass(D.Entries[I]))
Richard Smithd62306a2011-11-10 06:34:14 +00002230 Result.Offset -= Layout.getVBaseClassOffset(Base);
Richard Smith027bf112011-11-17 22:56:20 +00002231 else
Richard Smithd62306a2011-11-10 06:34:14 +00002232 Result.Offset -= Layout.getBaseClassOffset(Base);
2233 RD = Base;
2234 }
Richard Smith027bf112011-11-17 22:56:20 +00002235 D.Entries.resize(TruncatedElements);
Richard Smithd62306a2011-11-10 06:34:14 +00002236 return true;
2237}
2238
John McCalld7bca762012-05-01 00:38:49 +00002239static bool HandleLValueDirectBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002240 const CXXRecordDecl *Derived,
2241 const CXXRecordDecl *Base,
Craig Topper36250ad2014-05-12 05:36:57 +00002242 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002243 if (!RL) {
2244 if (Derived->isInvalidDecl()) return false;
2245 RL = &Info.Ctx.getASTRecordLayout(Derived);
2246 }
2247
Richard Smithd62306a2011-11-10 06:34:14 +00002248 Obj.getLValueOffset() += RL->getBaseClassOffset(Base);
Richard Smitha8105bc2012-01-06 16:39:00 +00002249 Obj.addDecl(Info, E, Base, /*Virtual*/ false);
John McCalld7bca762012-05-01 00:38:49 +00002250 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002251}
2252
Richard Smitha8105bc2012-01-06 16:39:00 +00002253static bool HandleLValueBase(EvalInfo &Info, const Expr *E, LValue &Obj,
Richard Smithd62306a2011-11-10 06:34:14 +00002254 const CXXRecordDecl *DerivedDecl,
2255 const CXXBaseSpecifier *Base) {
2256 const CXXRecordDecl *BaseDecl = Base->getType()->getAsCXXRecordDecl();
2257
John McCalld7bca762012-05-01 00:38:49 +00002258 if (!Base->isVirtual())
2259 return HandleLValueDirectBase(Info, E, Obj, DerivedDecl, BaseDecl);
Richard Smithd62306a2011-11-10 06:34:14 +00002260
Richard Smitha8105bc2012-01-06 16:39:00 +00002261 SubobjectDesignator &D = Obj.Designator;
2262 if (D.Invalid)
Richard Smithd62306a2011-11-10 06:34:14 +00002263 return false;
2264
Richard Smitha8105bc2012-01-06 16:39:00 +00002265 // Extract most-derived object and corresponding type.
2266 DerivedDecl = D.MostDerivedType->getAsCXXRecordDecl();
2267 if (!CastToDerivedClass(Info, E, Obj, DerivedDecl, D.MostDerivedPathLength))
2268 return false;
2269
2270 // Find the virtual base class.
John McCalld7bca762012-05-01 00:38:49 +00002271 if (DerivedDecl->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002272 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(DerivedDecl);
2273 Obj.getLValueOffset() += Layout.getVBaseClassOffset(BaseDecl);
Richard Smitha8105bc2012-01-06 16:39:00 +00002274 Obj.addDecl(Info, E, BaseDecl, /*Virtual*/ true);
Richard Smithd62306a2011-11-10 06:34:14 +00002275 return true;
2276}
2277
Richard Smith84401042013-06-03 05:03:02 +00002278static bool HandleLValueBasePath(EvalInfo &Info, const CastExpr *E,
2279 QualType Type, LValue &Result) {
2280 for (CastExpr::path_const_iterator PathI = E->path_begin(),
2281 PathE = E->path_end();
2282 PathI != PathE; ++PathI) {
2283 if (!HandleLValueBase(Info, E, Result, Type->getAsCXXRecordDecl(),
2284 *PathI))
2285 return false;
2286 Type = (*PathI)->getType();
2287 }
2288 return true;
2289}
2290
Richard Smithd62306a2011-11-10 06:34:14 +00002291/// Update LVal to refer to the given field, which must be a member of the type
2292/// currently described by LVal.
John McCalld7bca762012-05-01 00:38:49 +00002293static bool HandleLValueMember(EvalInfo &Info, const Expr *E, LValue &LVal,
Richard Smithd62306a2011-11-10 06:34:14 +00002294 const FieldDecl *FD,
Craig Topper36250ad2014-05-12 05:36:57 +00002295 const ASTRecordLayout *RL = nullptr) {
John McCalld7bca762012-05-01 00:38:49 +00002296 if (!RL) {
2297 if (FD->getParent()->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00002298 RL = &Info.Ctx.getASTRecordLayout(FD->getParent());
John McCalld7bca762012-05-01 00:38:49 +00002299 }
Richard Smithd62306a2011-11-10 06:34:14 +00002300
2301 unsigned I = FD->getFieldIndex();
Yaxun Liu402804b2016-12-15 08:09:08 +00002302 LVal.adjustOffset(Info.Ctx.toCharUnitsFromBits(RL->getFieldOffset(I)));
Richard Smitha8105bc2012-01-06 16:39:00 +00002303 LVal.addDecl(Info, E, FD);
John McCalld7bca762012-05-01 00:38:49 +00002304 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002305}
2306
Richard Smith1b78b3d2012-01-25 22:15:11 +00002307/// Update LVal to refer to the given indirect field.
John McCalld7bca762012-05-01 00:38:49 +00002308static bool HandleLValueIndirectMember(EvalInfo &Info, const Expr *E,
Richard Smith1b78b3d2012-01-25 22:15:11 +00002309 LValue &LVal,
2310 const IndirectFieldDecl *IFD) {
Aaron Ballman29c94602014-03-07 18:36:15 +00002311 for (const auto *C : IFD->chain())
Aaron Ballman13916082014-03-07 18:11:58 +00002312 if (!HandleLValueMember(Info, E, LVal, cast<FieldDecl>(C)))
John McCalld7bca762012-05-01 00:38:49 +00002313 return false;
2314 return true;
Richard Smith1b78b3d2012-01-25 22:15:11 +00002315}
2316
Richard Smithd62306a2011-11-10 06:34:14 +00002317/// Get the size of the given type in char units.
Richard Smith17100ba2012-02-16 02:46:34 +00002318static bool HandleSizeof(EvalInfo &Info, SourceLocation Loc,
2319 QualType Type, CharUnits &Size) {
Richard Smithd62306a2011-11-10 06:34:14 +00002320 // sizeof(void), __alignof__(void), sizeof(function) = 1 as a gcc
2321 // extension.
2322 if (Type->isVoidType() || Type->isFunctionType()) {
2323 Size = CharUnits::One();
2324 return true;
2325 }
2326
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002327 if (Type->isDependentType()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002328 Info.FFDiag(Loc);
Saleem Abdulrasoolada78fe2016-06-04 03:16:21 +00002329 return false;
2330 }
2331
Richard Smithd62306a2011-11-10 06:34:14 +00002332 if (!Type->isConstantSizeType()) {
2333 // sizeof(vla) is not a constantexpr: C99 6.5.3.4p2.
Richard Smith17100ba2012-02-16 02:46:34 +00002334 // FIXME: Better diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00002335 Info.FFDiag(Loc);
Richard Smithd62306a2011-11-10 06:34:14 +00002336 return false;
2337 }
2338
2339 Size = Info.Ctx.getTypeSizeInChars(Type);
2340 return true;
2341}
2342
2343/// Update a pointer value to model pointer arithmetic.
2344/// \param Info - Information about the ongoing evaluation.
Richard Smitha8105bc2012-01-06 16:39:00 +00002345/// \param E - The expression being evaluated, for diagnostic purposes.
Richard Smithd62306a2011-11-10 06:34:14 +00002346/// \param LVal - The pointer value to be updated.
2347/// \param EltTy - The pointee type represented by LVal.
2348/// \param Adjustment - The adjustment, in objects of type EltTy, to add.
Richard Smitha8105bc2012-01-06 16:39:00 +00002349static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2350 LValue &LVal, QualType EltTy,
Richard Smithd6cc1982017-01-31 02:23:02 +00002351 APSInt Adjustment) {
Richard Smithd62306a2011-11-10 06:34:14 +00002352 CharUnits SizeOfPointee;
Richard Smith17100ba2012-02-16 02:46:34 +00002353 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfPointee))
Richard Smithd62306a2011-11-10 06:34:14 +00002354 return false;
2355
Yaxun Liu402804b2016-12-15 08:09:08 +00002356 LVal.adjustOffsetAndIndex(Info, E, Adjustment, SizeOfPointee);
Richard Smithd62306a2011-11-10 06:34:14 +00002357 return true;
2358}
2359
Richard Smithd6cc1982017-01-31 02:23:02 +00002360static bool HandleLValueArrayAdjustment(EvalInfo &Info, const Expr *E,
2361 LValue &LVal, QualType EltTy,
2362 int64_t Adjustment) {
2363 return HandleLValueArrayAdjustment(Info, E, LVal, EltTy,
2364 APSInt::get(Adjustment));
2365}
2366
Richard Smith66c96992012-02-18 22:04:06 +00002367/// Update an lvalue to refer to a component of a complex number.
2368/// \param Info - Information about the ongoing evaluation.
2369/// \param LVal - The lvalue to be updated.
2370/// \param EltTy - The complex number's component type.
2371/// \param Imag - False for the real component, true for the imaginary.
2372static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
2373 LValue &LVal, QualType EltTy,
2374 bool Imag) {
2375 if (Imag) {
2376 CharUnits SizeOfComponent;
2377 if (!HandleSizeof(Info, E->getExprLoc(), EltTy, SizeOfComponent))
2378 return false;
2379 LVal.Offset += SizeOfComponent;
2380 }
2381 LVal.addComplex(Info, E, EltTy, Imag);
2382 return true;
2383}
2384
Faisal Vali051e3a22017-02-16 04:12:21 +00002385static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
2386 QualType Type, const LValue &LVal,
2387 APValue &RVal);
2388
Richard Smith27908702011-10-24 17:54:18 +00002389/// Try to evaluate the initializer for a variable declaration.
Richard Smith3229b742013-05-05 21:17:10 +00002390///
2391/// \param Info Information about the ongoing evaluation.
2392/// \param E An expression to be used when printing diagnostics.
2393/// \param VD The variable whose initializer should be obtained.
2394/// \param Frame The frame in which the variable was created. Must be null
2395/// if this variable is not local to the evaluation.
2396/// \param Result Filled in with a pointer to the value of the variable.
2397static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
2398 const VarDecl *VD, CallStackFrame *Frame,
2399 APValue *&Result) {
Faisal Vali051e3a22017-02-16 04:12:21 +00002400
Richard Smith254a73d2011-10-28 22:34:42 +00002401 // If this is a parameter to an active constexpr function call, perform
2402 // argument substitution.
2403 if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
Richard Smith253c2a32012-01-27 01:14:48 +00002404 // Assume arguments of a potential constant expression are unknown
2405 // constant expressions.
Richard Smith6d4c6582013-11-05 22:18:15 +00002406 if (Info.checkingPotentialConstantExpression())
Richard Smith253c2a32012-01-27 01:14:48 +00002407 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002408 if (!Frame || !Frame->Arguments) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002409 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithfec09922011-11-01 16:57:24 +00002410 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002411 }
Richard Smith3229b742013-05-05 21:17:10 +00002412 Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
Richard Smithfec09922011-11-01 16:57:24 +00002413 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00002414 }
Richard Smith27908702011-10-24 17:54:18 +00002415
Richard Smithd9f663b2013-04-22 15:31:51 +00002416 // If this is a local variable, dig out its value.
Richard Smith3229b742013-05-05 21:17:10 +00002417 if (Frame) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00002418 Result = Frame->getTemporary(VD);
Faisal Valia734ab92016-03-26 16:11:37 +00002419 if (!Result) {
2420 // Assume variables referenced within a lambda's call operator that were
2421 // not declared within the call operator are captures and during checking
2422 // of a potential constant expression, assume they are unknown constant
2423 // expressions.
2424 assert(isLambdaCallOperator(Frame->Callee) &&
2425 (VD->getDeclContext() != Frame->Callee || VD->isInitCapture()) &&
2426 "missing value for local variable");
2427 if (Info.checkingPotentialConstantExpression())
2428 return false;
2429 // FIXME: implement capture evaluation during constant expr evaluation.
Faisal Valie690b7a2016-07-02 22:34:24 +00002430 Info.FFDiag(E->getLocStart(),
Faisal Valia734ab92016-03-26 16:11:37 +00002431 diag::note_unimplemented_constexpr_lambda_feature_ast)
2432 << "captures not currently allowed";
2433 return false;
2434 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00002435 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00002436 }
2437
Richard Smithd0b4dd62011-12-19 06:19:21 +00002438 // Dig out the initializer, and use the declaration which it's attached to.
2439 const Expr *Init = VD->getAnyInitializer(VD);
2440 if (!Init || Init->isValueDependent()) {
Richard Smith253c2a32012-01-27 01:14:48 +00002441 // If we're checking a potential constant expression, the variable could be
2442 // initialized later.
Richard Smith6d4c6582013-11-05 22:18:15 +00002443 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002444 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithd0b4dd62011-12-19 06:19:21 +00002445 return false;
2446 }
2447
Richard Smithd62306a2011-11-10 06:34:14 +00002448 // If we're currently evaluating the initializer of this declaration, use that
2449 // in-flight value.
Richard Smith7525ff62013-05-09 07:14:00 +00002450 if (Info.EvaluatingDecl.dyn_cast<const ValueDecl*>() == VD) {
Richard Smith3229b742013-05-05 21:17:10 +00002451 Result = Info.EvaluatingDeclValue;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002452 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00002453 }
2454
Richard Smithcecf1842011-11-01 21:06:14 +00002455 // Never evaluate the initializer of a weak variable. We can't be sure that
2456 // this is the definition which will be used.
Richard Smithf57d8cb2011-12-09 22:58:01 +00002457 if (VD->isWeak()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002458 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithcecf1842011-11-01 21:06:14 +00002459 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002460 }
Richard Smithcecf1842011-11-01 21:06:14 +00002461
Richard Smithd0b4dd62011-12-19 06:19:21 +00002462 // Check that we can fold the initializer. In C++, we will have already done
2463 // this in the cases where it matters for conformance.
Dmitri Gribenkof8579502013-01-12 19:30:44 +00002464 SmallVector<PartialDiagnosticAt, 8> Notes;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002465 if (!VD->evaluateValue(Notes)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002466 Info.FFDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002467 Notes.size() + 1) << VD;
2468 Info.Note(VD->getLocation(), diag::note_declared_at);
2469 Info.addNotes(Notes);
Richard Smith0b0a0b62011-10-29 20:57:55 +00002470 return false;
Richard Smithd0b4dd62011-12-19 06:19:21 +00002471 } else if (!VD->checkInitIsICE()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00002472 Info.CCEDiag(E, diag::note_constexpr_var_init_non_constant,
Richard Smithd0b4dd62011-12-19 06:19:21 +00002473 Notes.size() + 1) << VD;
2474 Info.Note(VD->getLocation(), diag::note_declared_at);
2475 Info.addNotes(Notes);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002476 }
Richard Smith27908702011-10-24 17:54:18 +00002477
Richard Smith3229b742013-05-05 21:17:10 +00002478 Result = VD->getEvaluatedValue();
Richard Smith0b0a0b62011-10-29 20:57:55 +00002479 return true;
Richard Smith27908702011-10-24 17:54:18 +00002480}
2481
Richard Smith11562c52011-10-28 17:51:58 +00002482static bool IsConstNonVolatile(QualType T) {
Richard Smith27908702011-10-24 17:54:18 +00002483 Qualifiers Quals = T.getQualifiers();
2484 return Quals.hasConst() && !Quals.hasVolatile();
2485}
2486
Richard Smithe97cbd72011-11-11 04:05:33 +00002487/// Get the base index of the given base class within an APValue representing
2488/// the given derived class.
2489static unsigned getBaseIndex(const CXXRecordDecl *Derived,
2490 const CXXRecordDecl *Base) {
2491 Base = Base->getCanonicalDecl();
2492 unsigned Index = 0;
2493 for (CXXRecordDecl::base_class_const_iterator I = Derived->bases_begin(),
2494 E = Derived->bases_end(); I != E; ++I, ++Index) {
2495 if (I->getType()->getAsCXXRecordDecl()->getCanonicalDecl() == Base)
2496 return Index;
2497 }
2498
2499 llvm_unreachable("base class missing from derived class's bases list");
2500}
2501
Richard Smith3da88fa2013-04-26 14:36:30 +00002502/// Extract the value of a character from a string literal.
2503static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
2504 uint64_t Index) {
Akira Hatanakabc332642017-01-31 02:31:39 +00002505 // FIXME: Support MakeStringConstant
2506 if (const auto *ObjCEnc = dyn_cast<ObjCEncodeExpr>(Lit)) {
2507 std::string Str;
2508 Info.Ctx.getObjCEncodingForType(ObjCEnc->getEncodedType(), Str);
2509 assert(Index <= Str.size() && "Index too large");
2510 return APSInt::getUnsigned(Str.c_str()[Index]);
2511 }
2512
Alexey Bataevec474782014-10-09 08:45:04 +00002513 if (auto PE = dyn_cast<PredefinedExpr>(Lit))
2514 Lit = PE->getFunctionName();
Richard Smith3da88fa2013-04-26 14:36:30 +00002515 const StringLiteral *S = cast<StringLiteral>(Lit);
2516 const ConstantArrayType *CAT =
2517 Info.Ctx.getAsConstantArrayType(S->getType());
2518 assert(CAT && "string literal isn't an array");
2519 QualType CharType = CAT->getElementType();
Richard Smith9ec1e482012-04-15 02:50:59 +00002520 assert(CharType->isIntegerType() && "unexpected character type");
Richard Smith14a94132012-02-17 03:35:37 +00002521
2522 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
Richard Smith9ec1e482012-04-15 02:50:59 +00002523 CharType->isUnsignedIntegerType());
Richard Smith14a94132012-02-17 03:35:37 +00002524 if (Index < S->getLength())
2525 Value = S->getCodeUnit(Index);
2526 return Value;
2527}
2528
Richard Smith3da88fa2013-04-26 14:36:30 +00002529// Expand a string literal into an array of characters.
2530static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
2531 APValue &Result) {
2532 const StringLiteral *S = cast<StringLiteral>(Lit);
2533 const ConstantArrayType *CAT =
2534 Info.Ctx.getAsConstantArrayType(S->getType());
2535 assert(CAT && "string literal isn't an array");
2536 QualType CharType = CAT->getElementType();
2537 assert(CharType->isIntegerType() && "unexpected character type");
2538
2539 unsigned Elts = CAT->getSize().getZExtValue();
2540 Result = APValue(APValue::UninitArray(),
2541 std::min(S->getLength(), Elts), Elts);
2542 APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
2543 CharType->isUnsignedIntegerType());
2544 if (Result.hasArrayFiller())
2545 Result.getArrayFiller() = APValue(Value);
2546 for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
2547 Value = S->getCodeUnit(I);
2548 Result.getArrayInitializedElt(I) = APValue(Value);
2549 }
2550}
2551
2552// Expand an array so that it has more than Index filled elements.
2553static void expandArray(APValue &Array, unsigned Index) {
2554 unsigned Size = Array.getArraySize();
2555 assert(Index < Size);
2556
2557 // Always at least double the number of elements for which we store a value.
2558 unsigned OldElts = Array.getArrayInitializedElts();
2559 unsigned NewElts = std::max(Index+1, OldElts * 2);
2560 NewElts = std::min(Size, std::max(NewElts, 8u));
2561
2562 // Copy the data across.
2563 APValue NewValue(APValue::UninitArray(), NewElts, Size);
2564 for (unsigned I = 0; I != OldElts; ++I)
2565 NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
2566 for (unsigned I = OldElts; I != NewElts; ++I)
2567 NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
2568 if (NewValue.hasArrayFiller())
2569 NewValue.getArrayFiller() = Array.getArrayFiller();
2570 Array.swap(NewValue);
2571}
2572
Richard Smithb01fe402014-09-16 01:24:02 +00002573/// Determine whether a type would actually be read by an lvalue-to-rvalue
2574/// conversion. If it's of class type, we may assume that the copy operation
2575/// is trivial. Note that this is never true for a union type with fields
2576/// (because the copy always "reads" the active member) and always true for
2577/// a non-class type.
2578static bool isReadByLvalueToRvalueConversion(QualType T) {
2579 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2580 if (!RD || (RD->isUnion() && !RD->field_empty()))
2581 return true;
2582 if (RD->isEmpty())
2583 return false;
2584
2585 for (auto *Field : RD->fields())
2586 if (isReadByLvalueToRvalueConversion(Field->getType()))
2587 return true;
2588
2589 for (auto &BaseSpec : RD->bases())
2590 if (isReadByLvalueToRvalueConversion(BaseSpec.getType()))
2591 return true;
2592
2593 return false;
2594}
2595
2596/// Diagnose an attempt to read from any unreadable field within the specified
2597/// type, which might be a class type.
2598static bool diagnoseUnreadableFields(EvalInfo &Info, const Expr *E,
2599 QualType T) {
2600 CXXRecordDecl *RD = T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
2601 if (!RD)
2602 return false;
2603
2604 if (!RD->hasMutableFields())
2605 return false;
2606
2607 for (auto *Field : RD->fields()) {
2608 // If we're actually going to read this field in some way, then it can't
2609 // be mutable. If we're in a union, then assigning to a mutable field
2610 // (even an empty one) can change the active member, so that's not OK.
2611 // FIXME: Add core issue number for the union case.
2612 if (Field->isMutable() &&
2613 (RD->isUnion() || isReadByLvalueToRvalueConversion(Field->getType()))) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002614 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1) << Field;
Richard Smithb01fe402014-09-16 01:24:02 +00002615 Info.Note(Field->getLocation(), diag::note_declared_at);
2616 return true;
2617 }
2618
2619 if (diagnoseUnreadableFields(Info, E, Field->getType()))
2620 return true;
2621 }
2622
2623 for (auto &BaseSpec : RD->bases())
2624 if (diagnoseUnreadableFields(Info, E, BaseSpec.getType()))
2625 return true;
2626
2627 // All mutable fields were empty, and thus not actually read.
2628 return false;
2629}
2630
Richard Smith861b5b52013-05-07 23:34:45 +00002631/// Kinds of access we can perform on an object, for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00002632enum AccessKinds {
2633 AK_Read,
Richard Smith243ef902013-05-05 23:31:59 +00002634 AK_Assign,
2635 AK_Increment,
2636 AK_Decrement
Richard Smith3da88fa2013-04-26 14:36:30 +00002637};
2638
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002639namespace {
Richard Smith3229b742013-05-05 21:17:10 +00002640/// A handle to a complete object (an object that is not a subobject of
2641/// another object).
2642struct CompleteObject {
2643 /// The value of the complete object.
2644 APValue *Value;
2645 /// The type of the complete object.
2646 QualType Type;
2647
Craig Topper36250ad2014-05-12 05:36:57 +00002648 CompleteObject() : Value(nullptr) {}
Richard Smith3229b742013-05-05 21:17:10 +00002649 CompleteObject(APValue *Value, QualType Type)
2650 : Value(Value), Type(Type) {
2651 assert(Value && "missing value for complete object");
2652 }
2653
Aaron Ballman67347662015-02-15 22:00:28 +00002654 explicit operator bool() const { return Value; }
Richard Smith3229b742013-05-05 21:17:10 +00002655};
Benjamin Kramer5b4296a2015-10-28 17:16:26 +00002656} // end anonymous namespace
Richard Smith3229b742013-05-05 21:17:10 +00002657
Richard Smith3da88fa2013-04-26 14:36:30 +00002658/// Find the designated sub-object of an rvalue.
2659template<typename SubobjectHandler>
2660typename SubobjectHandler::result_type
Richard Smith3229b742013-05-05 21:17:10 +00002661findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002662 const SubobjectDesignator &Sub, SubobjectHandler &handler) {
Richard Smitha8105bc2012-01-06 16:39:00 +00002663 if (Sub.Invalid)
2664 // A diagnostic will have already been produced.
Richard Smith3da88fa2013-04-26 14:36:30 +00002665 return handler.failed();
Richard Smith6f4f0f12017-10-20 22:56:25 +00002666 if (Sub.isOnePastTheEnd() || Sub.isMostDerivedAnUnsizedArray()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002667 if (Info.getLangOpts().CPlusPlus11)
Richard Smith6f4f0f12017-10-20 22:56:25 +00002668 Info.FFDiag(E, Sub.isOnePastTheEnd()
2669 ? diag::note_constexpr_access_past_end
2670 : diag::note_constexpr_access_unsized_array)
2671 << handler.AccessKind;
Richard Smith3da88fa2013-04-26 14:36:30 +00002672 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002673 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002674 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002675 }
Richard Smithf3e9e432011-11-07 09:22:26 +00002676
Richard Smith3229b742013-05-05 21:17:10 +00002677 APValue *O = Obj.Value;
2678 QualType ObjType = Obj.Type;
Craig Topper36250ad2014-05-12 05:36:57 +00002679 const FieldDecl *LastField = nullptr;
Richard Smith49ca8aa2013-08-06 07:09:20 +00002680
Richard Smithd62306a2011-11-10 06:34:14 +00002681 // Walk the designator's path to find the subobject.
Richard Smith08d6a2c2013-07-24 07:11:57 +00002682 for (unsigned I = 0, N = Sub.Entries.size(); /**/; ++I) {
2683 if (O->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00002684 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00002685 Info.FFDiag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002686 return handler.failed();
2687 }
2688
Richard Smith49ca8aa2013-08-06 07:09:20 +00002689 if (I == N) {
Richard Smithb01fe402014-09-16 01:24:02 +00002690 // If we are reading an object of class type, there may still be more
2691 // things we need to check: if there are any mutable subobjects, we
2692 // cannot perform this read. (This only happens when performing a trivial
2693 // copy or assignment.)
2694 if (ObjType->isRecordType() && handler.AccessKind == AK_Read &&
2695 diagnoseUnreadableFields(Info, E, ObjType))
2696 return handler.failed();
2697
Richard Smith49ca8aa2013-08-06 07:09:20 +00002698 if (!handler.found(*O, ObjType))
2699 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00002700
Richard Smith49ca8aa2013-08-06 07:09:20 +00002701 // If we modified a bit-field, truncate it to the right width.
2702 if (handler.AccessKind != AK_Read &&
2703 LastField && LastField->isBitField() &&
2704 !truncateBitfieldValue(Info, E, *O, LastField))
2705 return false;
2706
2707 return true;
2708 }
2709
Craig Topper36250ad2014-05-12 05:36:57 +00002710 LastField = nullptr;
Richard Smithf3e9e432011-11-07 09:22:26 +00002711 if (ObjType->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00002712 // Next subobject is an array element.
Richard Smithf3e9e432011-11-07 09:22:26 +00002713 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(ObjType);
Richard Smithf57d8cb2011-12-09 22:58:01 +00002714 assert(CAT && "vla in literal type?");
Richard Smithf3e9e432011-11-07 09:22:26 +00002715 uint64_t Index = Sub.Entries[I].ArrayIndex;
Richard Smithf57d8cb2011-12-09 22:58:01 +00002716 if (CAT->getSize().ule(Index)) {
Richard Smithf2b681b2011-12-21 05:04:46 +00002717 // Note, it should not be possible to form a pointer with a valid
2718 // designator which points more than one past the end of the array.
Richard Smith3da88fa2013-04-26 14:36:30 +00002719 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002720 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002721 << handler.AccessKind;
2722 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002723 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002724 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002725 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002726
2727 ObjType = CAT->getElementType();
2728
Richard Smith14a94132012-02-17 03:35:37 +00002729 // An array object is represented as either an Array APValue or as an
2730 // LValue which refers to a string literal.
2731 if (O->isLValue()) {
2732 assert(I == N - 1 && "extracting subobject of character?");
2733 assert(!O->hasLValuePath() || O->getLValuePath().empty());
Richard Smith3da88fa2013-04-26 14:36:30 +00002734 if (handler.AccessKind != AK_Read)
2735 expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
2736 *O);
2737 else
2738 return handler.foundString(*O, ObjType, Index);
2739 }
2740
2741 if (O->getArrayInitializedElts() > Index)
Richard Smithf3e9e432011-11-07 09:22:26 +00002742 O = &O->getArrayInitializedElt(Index);
Richard Smith3da88fa2013-04-26 14:36:30 +00002743 else if (handler.AccessKind != AK_Read) {
2744 expandArray(*O, Index);
2745 O = &O->getArrayInitializedElt(Index);
2746 } else
Richard Smithf3e9e432011-11-07 09:22:26 +00002747 O = &O->getArrayFiller();
Richard Smith66c96992012-02-18 22:04:06 +00002748 } else if (ObjType->isAnyComplexType()) {
2749 // Next subobject is a complex number.
2750 uint64_t Index = Sub.Entries[I].ArrayIndex;
2751 if (Index > 1) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002752 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00002753 Info.FFDiag(E, diag::note_constexpr_access_past_end)
Richard Smith3da88fa2013-04-26 14:36:30 +00002754 << handler.AccessKind;
2755 else
Faisal Valie690b7a2016-07-02 22:34:24 +00002756 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002757 return handler.failed();
Richard Smith66c96992012-02-18 22:04:06 +00002758 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002759
2760 bool WasConstQualified = ObjType.isConstQualified();
2761 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2762 if (WasConstQualified)
2763 ObjType.addConst();
2764
Richard Smith66c96992012-02-18 22:04:06 +00002765 assert(I == N - 1 && "extracting subobject of scalar?");
2766 if (O->isComplexInt()) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002767 return handler.found(Index ? O->getComplexIntImag()
2768 : O->getComplexIntReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002769 } else {
2770 assert(O->isComplexFloat());
Richard Smith3da88fa2013-04-26 14:36:30 +00002771 return handler.found(Index ? O->getComplexFloatImag()
2772 : O->getComplexFloatReal(), ObjType);
Richard Smith66c96992012-02-18 22:04:06 +00002773 }
Richard Smithd62306a2011-11-10 06:34:14 +00002774 } else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
Richard Smith3da88fa2013-04-26 14:36:30 +00002775 if (Field->isMutable() && handler.AccessKind == AK_Read) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002776 Info.FFDiag(E, diag::note_constexpr_ltor_mutable, 1)
Richard Smith5a294e62012-02-09 03:29:58 +00002777 << Field;
2778 Info.Note(Field->getLocation(), diag::note_declared_at);
Richard Smith3da88fa2013-04-26 14:36:30 +00002779 return handler.failed();
Richard Smith5a294e62012-02-09 03:29:58 +00002780 }
2781
Richard Smithd62306a2011-11-10 06:34:14 +00002782 // Next subobject is a class, struct or union field.
2783 RecordDecl *RD = ObjType->castAs<RecordType>()->getDecl();
2784 if (RD->isUnion()) {
2785 const FieldDecl *UnionField = O->getUnionField();
2786 if (!UnionField ||
Richard Smithf57d8cb2011-12-09 22:58:01 +00002787 UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002788 Info.FFDiag(E, diag::note_constexpr_access_inactive_union_member)
Richard Smith3da88fa2013-04-26 14:36:30 +00002789 << handler.AccessKind << Field << !UnionField << UnionField;
2790 return handler.failed();
Richard Smithf57d8cb2011-12-09 22:58:01 +00002791 }
Richard Smithd62306a2011-11-10 06:34:14 +00002792 O = &O->getUnionValue();
2793 } else
2794 O = &O->getStructField(Field->getFieldIndex());
Richard Smith3da88fa2013-04-26 14:36:30 +00002795
2796 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithd62306a2011-11-10 06:34:14 +00002797 ObjType = Field->getType();
Richard Smith3da88fa2013-04-26 14:36:30 +00002798 if (WasConstQualified && !Field->isMutable())
2799 ObjType.addConst();
Richard Smithf2b681b2011-12-21 05:04:46 +00002800
2801 if (ObjType.isVolatileQualified()) {
2802 if (Info.getLangOpts().CPlusPlus) {
2803 // FIXME: Include a description of the path to the volatile subobject.
Faisal Valie690b7a2016-07-02 22:34:24 +00002804 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3da88fa2013-04-26 14:36:30 +00002805 << handler.AccessKind << 2 << Field;
Richard Smithf2b681b2011-12-21 05:04:46 +00002806 Info.Note(Field->getLocation(), diag::note_declared_at);
2807 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00002808 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf2b681b2011-12-21 05:04:46 +00002809 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002810 return handler.failed();
Richard Smithf2b681b2011-12-21 05:04:46 +00002811 }
Richard Smith49ca8aa2013-08-06 07:09:20 +00002812
2813 LastField = Field;
Richard Smithf3e9e432011-11-07 09:22:26 +00002814 } else {
Richard Smithd62306a2011-11-10 06:34:14 +00002815 // Next subobject is a base class.
Richard Smithe97cbd72011-11-11 04:05:33 +00002816 const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
2817 const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
2818 O = &O->getStructBase(getBaseIndex(Derived, Base));
Richard Smith3da88fa2013-04-26 14:36:30 +00002819
2820 bool WasConstQualified = ObjType.isConstQualified();
Richard Smithe97cbd72011-11-11 04:05:33 +00002821 ObjType = Info.Ctx.getRecordType(Base);
Richard Smith3da88fa2013-04-26 14:36:30 +00002822 if (WasConstQualified)
2823 ObjType.addConst();
Richard Smithf3e9e432011-11-07 09:22:26 +00002824 }
2825 }
Richard Smith3da88fa2013-04-26 14:36:30 +00002826}
2827
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002828namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002829struct ExtractSubobjectHandler {
2830 EvalInfo &Info;
Richard Smith3229b742013-05-05 21:17:10 +00002831 APValue &Result;
Richard Smith3da88fa2013-04-26 14:36:30 +00002832
2833 static const AccessKinds AccessKind = AK_Read;
2834
2835 typedef bool result_type;
2836 bool failed() { return false; }
2837 bool found(APValue &Subobj, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002838 Result = Subobj;
Richard Smith3da88fa2013-04-26 14:36:30 +00002839 return true;
2840 }
2841 bool found(APSInt &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002842 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002843 return true;
2844 }
2845 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith3229b742013-05-05 21:17:10 +00002846 Result = APValue(Value);
Richard Smith3da88fa2013-04-26 14:36:30 +00002847 return true;
2848 }
2849 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
Richard Smith3229b742013-05-05 21:17:10 +00002850 Result = APValue(extractStringLiteralCharacter(
Richard Smith3da88fa2013-04-26 14:36:30 +00002851 Info, Subobj.getLValueBase().get<const Expr *>(), Character));
2852 return true;
2853 }
2854};
Richard Smith3229b742013-05-05 21:17:10 +00002855} // end anonymous namespace
2856
Richard Smith3da88fa2013-04-26 14:36:30 +00002857const AccessKinds ExtractSubobjectHandler::AccessKind;
2858
2859/// Extract the designated sub-object of an rvalue.
2860static bool extractSubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002861 const CompleteObject &Obj,
2862 const SubobjectDesignator &Sub,
2863 APValue &Result) {
2864 ExtractSubobjectHandler Handler = { Info, Result };
2865 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smith3da88fa2013-04-26 14:36:30 +00002866}
2867
Richard Smith3229b742013-05-05 21:17:10 +00002868namespace {
Richard Smith3da88fa2013-04-26 14:36:30 +00002869struct ModifySubobjectHandler {
2870 EvalInfo &Info;
2871 APValue &NewVal;
2872 const Expr *E;
2873
2874 typedef bool result_type;
2875 static const AccessKinds AccessKind = AK_Assign;
2876
2877 bool checkConst(QualType QT) {
2878 // Assigning to a const object has undefined behavior.
2879 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002880 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith3da88fa2013-04-26 14:36:30 +00002881 return false;
2882 }
2883 return true;
2884 }
2885
2886 bool failed() { return false; }
2887 bool found(APValue &Subobj, QualType SubobjType) {
2888 if (!checkConst(SubobjType))
2889 return false;
2890 // We've been given ownership of NewVal, so just swap it in.
2891 Subobj.swap(NewVal);
2892 return true;
2893 }
2894 bool found(APSInt &Value, QualType SubobjType) {
2895 if (!checkConst(SubobjType))
2896 return false;
2897 if (!NewVal.isInt()) {
2898 // Maybe trying to write a cast pointer value into a complex?
Faisal Valie690b7a2016-07-02 22:34:24 +00002899 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00002900 return false;
2901 }
2902 Value = NewVal.getInt();
2903 return true;
2904 }
2905 bool found(APFloat &Value, QualType SubobjType) {
2906 if (!checkConst(SubobjType))
2907 return false;
2908 Value = NewVal.getFloat();
2909 return true;
2910 }
2911 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
2912 llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
2913 }
2914};
Benjamin Kramer62498ab2013-04-26 22:01:47 +00002915} // end anonymous namespace
Richard Smith3da88fa2013-04-26 14:36:30 +00002916
Richard Smith3229b742013-05-05 21:17:10 +00002917const AccessKinds ModifySubobjectHandler::AccessKind;
2918
Richard Smith3da88fa2013-04-26 14:36:30 +00002919/// Update the designated sub-object of an rvalue to the given value.
2920static bool modifySubobject(EvalInfo &Info, const Expr *E,
Richard Smith3229b742013-05-05 21:17:10 +00002921 const CompleteObject &Obj,
Richard Smith3da88fa2013-04-26 14:36:30 +00002922 const SubobjectDesignator &Sub,
2923 APValue &NewVal) {
2924 ModifySubobjectHandler Handler = { Info, NewVal, E };
Richard Smith3229b742013-05-05 21:17:10 +00002925 return findSubobject(Info, E, Obj, Sub, Handler);
Richard Smithf3e9e432011-11-07 09:22:26 +00002926}
2927
Richard Smith84f6dcf2012-02-02 01:16:57 +00002928/// Find the position where two subobject designators diverge, or equivalently
2929/// the length of the common initial subsequence.
2930static unsigned FindDesignatorMismatch(QualType ObjType,
2931 const SubobjectDesignator &A,
2932 const SubobjectDesignator &B,
2933 bool &WasArrayIndex) {
2934 unsigned I = 0, N = std::min(A.Entries.size(), B.Entries.size());
2935 for (/**/; I != N; ++I) {
Richard Smith66c96992012-02-18 22:04:06 +00002936 if (!ObjType.isNull() &&
2937 (ObjType->isArrayType() || ObjType->isAnyComplexType())) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00002938 // Next subobject is an array element.
2939 if (A.Entries[I].ArrayIndex != B.Entries[I].ArrayIndex) {
2940 WasArrayIndex = true;
2941 return I;
2942 }
Richard Smith66c96992012-02-18 22:04:06 +00002943 if (ObjType->isAnyComplexType())
2944 ObjType = ObjType->castAs<ComplexType>()->getElementType();
2945 else
2946 ObjType = ObjType->castAsArrayTypeUnsafe()->getElementType();
Richard Smith84f6dcf2012-02-02 01:16:57 +00002947 } else {
2948 if (A.Entries[I].BaseOrMember != B.Entries[I].BaseOrMember) {
2949 WasArrayIndex = false;
2950 return I;
2951 }
2952 if (const FieldDecl *FD = getAsField(A.Entries[I]))
2953 // Next subobject is a field.
2954 ObjType = FD->getType();
2955 else
2956 // Next subobject is a base class.
2957 ObjType = QualType();
2958 }
2959 }
2960 WasArrayIndex = false;
2961 return I;
2962}
2963
2964/// Determine whether the given subobject designators refer to elements of the
2965/// same array object.
2966static bool AreElementsOfSameArray(QualType ObjType,
2967 const SubobjectDesignator &A,
2968 const SubobjectDesignator &B) {
2969 if (A.Entries.size() != B.Entries.size())
2970 return false;
2971
George Burgess IVa51c4072015-10-16 01:49:01 +00002972 bool IsArray = A.MostDerivedIsArrayElement;
Richard Smith84f6dcf2012-02-02 01:16:57 +00002973 if (IsArray && A.MostDerivedPathLength != A.Entries.size())
2974 // A is a subobject of the array element.
2975 return false;
2976
2977 // If A (and B) designates an array element, the last entry will be the array
2978 // index. That doesn't have to match. Otherwise, we're in the 'implicit array
2979 // of length 1' case, and the entire path must match.
2980 bool WasArrayIndex;
2981 unsigned CommonLength = FindDesignatorMismatch(ObjType, A, B, WasArrayIndex);
2982 return CommonLength >= A.Entries.size() - IsArray;
2983}
2984
Richard Smith3229b742013-05-05 21:17:10 +00002985/// Find the complete object to which an LValue refers.
Benjamin Kramer8407df72015-03-09 16:47:52 +00002986static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
2987 AccessKinds AK, const LValue &LVal,
2988 QualType LValType) {
Richard Smith3229b742013-05-05 21:17:10 +00002989 if (!LVal.Base) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002990 Info.FFDiag(E, diag::note_constexpr_access_null) << AK;
Richard Smith3229b742013-05-05 21:17:10 +00002991 return CompleteObject();
2992 }
2993
Craig Topper36250ad2014-05-12 05:36:57 +00002994 CallStackFrame *Frame = nullptr;
Richard Smith3229b742013-05-05 21:17:10 +00002995 if (LVal.CallIndex) {
2996 Frame = Info.getCallFrame(LVal.CallIndex);
2997 if (!Frame) {
Faisal Valie690b7a2016-07-02 22:34:24 +00002998 Info.FFDiag(E, diag::note_constexpr_lifetime_ended, 1)
Richard Smith3229b742013-05-05 21:17:10 +00002999 << AK << LVal.Base.is<const ValueDecl*>();
3000 NoteLValueLocation(Info, LVal.Base);
3001 return CompleteObject();
3002 }
Richard Smith3229b742013-05-05 21:17:10 +00003003 }
3004
3005 // C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
3006 // is not a constant expression (even if the object is non-volatile). We also
3007 // apply this rule to C++98, in order to conform to the expected 'volatile'
3008 // semantics.
3009 if (LValType.isVolatileQualified()) {
3010 if (Info.getLangOpts().CPlusPlus)
Faisal Valie690b7a2016-07-02 22:34:24 +00003011 Info.FFDiag(E, diag::note_constexpr_access_volatile_type)
Richard Smith3229b742013-05-05 21:17:10 +00003012 << AK << LValType;
3013 else
Faisal Valie690b7a2016-07-02 22:34:24 +00003014 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003015 return CompleteObject();
3016 }
3017
3018 // Compute value storage location and type of base object.
Craig Topper36250ad2014-05-12 05:36:57 +00003019 APValue *BaseVal = nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003020 QualType BaseType = getType(LVal.Base);
Richard Smith3229b742013-05-05 21:17:10 +00003021
3022 if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
3023 // In C++98, const, non-volatile integers initialized with ICEs are ICEs.
3024 // In C++11, constexpr, non-volatile variables initialized with constant
3025 // expressions are constant expressions too. Inside constexpr functions,
3026 // parameters are constant expressions even if they're non-const.
3027 // In C++1y, objects local to a constant expression (those with a Frame) are
3028 // both readable and writable inside constant expressions.
3029 // In C, such things can also be folded, although they are not ICEs.
3030 const VarDecl *VD = dyn_cast<VarDecl>(D);
3031 if (VD) {
3032 if (const VarDecl *VDef = VD->getDefinition(Info.Ctx))
3033 VD = VDef;
3034 }
3035 if (!VD || VD->isInvalidDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003036 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003037 return CompleteObject();
3038 }
3039
3040 // Accesses of volatile-qualified objects are not allowed.
Richard Smith3229b742013-05-05 21:17:10 +00003041 if (BaseType.isVolatileQualified()) {
3042 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003043 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003044 << AK << 1 << VD;
3045 Info.Note(VD->getLocation(), diag::note_declared_at);
3046 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003047 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003048 }
3049 return CompleteObject();
3050 }
3051
3052 // Unless we're looking at a local variable or argument in a constexpr call,
3053 // the variable we're reading must be const.
3054 if (!Frame) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003055 if (Info.getLangOpts().CPlusPlus14 &&
Richard Smith7525ff62013-05-09 07:14:00 +00003056 VD == Info.EvaluatingDecl.dyn_cast<const ValueDecl *>()) {
3057 // OK, we can read and modify an object if we're in the process of
3058 // evaluating its initializer, because its lifetime began in this
3059 // evaluation.
3060 } else if (AK != AK_Read) {
3061 // All the remaining cases only permit reading.
Faisal Valie690b7a2016-07-02 22:34:24 +00003062 Info.FFDiag(E, diag::note_constexpr_modify_global);
Richard Smith7525ff62013-05-09 07:14:00 +00003063 return CompleteObject();
George Burgess IVb5316982016-12-27 05:33:20 +00003064 } else if (VD->isConstexpr()) {
Richard Smith3229b742013-05-05 21:17:10 +00003065 // OK, we can read this variable.
3066 } else if (BaseType->isIntegralOrEnumerationType()) {
Xiuli Pan244e3f62016-06-07 04:34:00 +00003067 // In OpenCL if a variable is in constant address space it is a const value.
3068 if (!(BaseType.isConstQualified() ||
3069 (Info.getLangOpts().OpenCL &&
3070 BaseType.getAddressSpace() == LangAS::opencl_constant))) {
Richard Smith3229b742013-05-05 21:17:10 +00003071 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003072 Info.FFDiag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003073 Info.Note(VD->getLocation(), diag::note_declared_at);
3074 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003075 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003076 }
3077 return CompleteObject();
3078 }
3079 } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
3080 // We support folding of const floating-point types, in order to make
3081 // static const data members of such types (supported as an extension)
3082 // more useful.
3083 if (Info.getLangOpts().CPlusPlus11) {
3084 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
3085 Info.Note(VD->getLocation(), diag::note_declared_at);
3086 } else {
3087 Info.CCEDiag(E);
3088 }
George Burgess IVb5316982016-12-27 05:33:20 +00003089 } else if (BaseType.isConstQualified() && VD->hasDefinition(Info.Ctx)) {
3090 Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr) << VD;
3091 // Keep evaluating to see what we can do.
Richard Smith3229b742013-05-05 21:17:10 +00003092 } else {
3093 // FIXME: Allow folding of values of any literal type in all languages.
Richard Smithc0d04a22016-05-25 22:06:25 +00003094 if (Info.checkingPotentialConstantExpression() &&
3095 VD->getType().isConstQualified() && !VD->hasDefinition(Info.Ctx)) {
3096 // The definition of this variable could be constexpr. We can't
3097 // access it right now, but may be able to in future.
3098 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003099 Info.FFDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Richard Smith3229b742013-05-05 21:17:10 +00003100 Info.Note(VD->getLocation(), diag::note_declared_at);
3101 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003102 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003103 }
3104 return CompleteObject();
3105 }
3106 }
3107
3108 if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
3109 return CompleteObject();
3110 } else {
3111 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
3112
3113 if (!Frame) {
Richard Smithe6c01442013-06-05 00:46:14 +00003114 if (const MaterializeTemporaryExpr *MTE =
3115 dyn_cast<MaterializeTemporaryExpr>(Base)) {
3116 assert(MTE->getStorageDuration() == SD_Static &&
3117 "should have a frame for a non-global materialized temporary");
Richard Smith3229b742013-05-05 21:17:10 +00003118
Richard Smithe6c01442013-06-05 00:46:14 +00003119 // Per C++1y [expr.const]p2:
3120 // an lvalue-to-rvalue conversion [is not allowed unless it applies to]
3121 // - a [...] glvalue of integral or enumeration type that refers to
3122 // a non-volatile const object [...]
3123 // [...]
3124 // - a [...] glvalue of literal type that refers to a non-volatile
3125 // object whose lifetime began within the evaluation of e.
3126 //
3127 // C++11 misses the 'began within the evaluation of e' check and
3128 // instead allows all temporaries, including things like:
3129 // int &&r = 1;
3130 // int x = ++r;
3131 // constexpr int k = r;
3132 // Therefore we use the C++1y rules in C++11 too.
3133 const ValueDecl *VD = Info.EvaluatingDecl.dyn_cast<const ValueDecl*>();
3134 const ValueDecl *ED = MTE->getExtendingDecl();
3135 if (!(BaseType.isConstQualified() &&
3136 BaseType->isIntegralOrEnumerationType()) &&
3137 !(VD && VD->getCanonicalDecl() == ED->getCanonicalDecl())) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003138 Info.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
Richard Smithe6c01442013-06-05 00:46:14 +00003139 Info.Note(MTE->getExprLoc(), diag::note_constexpr_temporary_here);
3140 return CompleteObject();
3141 }
3142
3143 BaseVal = Info.Ctx.getMaterializedTemporaryValue(MTE, false);
3144 assert(BaseVal && "got reference to unevaluated temporary");
3145 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003146 Info.FFDiag(E);
Richard Smithe6c01442013-06-05 00:46:14 +00003147 return CompleteObject();
3148 }
3149 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003150 BaseVal = Frame->getTemporary(Base);
3151 assert(BaseVal && "missing value for temporary");
Richard Smithe6c01442013-06-05 00:46:14 +00003152 }
Richard Smith3229b742013-05-05 21:17:10 +00003153
3154 // Volatile temporary objects cannot be accessed in constant expressions.
3155 if (BaseType.isVolatileQualified()) {
3156 if (Info.getLangOpts().CPlusPlus) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003157 Info.FFDiag(E, diag::note_constexpr_access_volatile_obj, 1)
Richard Smith3229b742013-05-05 21:17:10 +00003158 << AK << 0;
3159 Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
3160 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003161 Info.FFDiag(E);
Richard Smith3229b742013-05-05 21:17:10 +00003162 }
3163 return CompleteObject();
3164 }
3165 }
3166
Richard Smith7525ff62013-05-09 07:14:00 +00003167 // During the construction of an object, it is not yet 'const'.
Erik Pilkington42925492017-10-04 00:18:55 +00003168 // FIXME: This doesn't do quite the right thing for const subobjects of the
Richard Smith7525ff62013-05-09 07:14:00 +00003169 // object under construction.
Erik Pilkington42925492017-10-04 00:18:55 +00003170 if (Info.isEvaluatingConstructor(LVal.getLValueBase(), LVal.CallIndex)) {
Richard Smith7525ff62013-05-09 07:14:00 +00003171 BaseType = Info.Ctx.getCanonicalType(BaseType);
3172 BaseType.removeLocalConst();
3173 }
3174
Richard Smith6d4c6582013-11-05 22:18:15 +00003175 // In C++1y, we can't safely access any mutable state when we might be
George Burgess IV8c892b52016-05-25 22:31:54 +00003176 // evaluating after an unmodeled side effect.
Richard Smith6d4c6582013-11-05 22:18:15 +00003177 //
3178 // FIXME: Not all local state is mutable. Allow local constant subobjects
3179 // to be read here (but take care with 'mutable' fields).
George Burgess IV8c892b52016-05-25 22:31:54 +00003180 if ((Frame && Info.getLangOpts().CPlusPlus14 &&
3181 Info.EvalStatus.HasSideEffects) ||
3182 (AK != AK_Read && Info.IsSpeculativelyEvaluating))
Richard Smith3229b742013-05-05 21:17:10 +00003183 return CompleteObject();
3184
3185 return CompleteObject(BaseVal, BaseType);
3186}
3187
Richard Smith243ef902013-05-05 23:31:59 +00003188/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
3189/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
3190/// glvalue referred to by an entity of reference type.
Richard Smithd62306a2011-11-10 06:34:14 +00003191///
3192/// \param Info - Information about the ongoing evaluation.
Richard Smithf57d8cb2011-12-09 22:58:01 +00003193/// \param Conv - The expression for which we are performing the conversion.
3194/// Used for diagnostics.
Richard Smith3da88fa2013-04-26 14:36:30 +00003195/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
3196/// case of a non-class type).
Richard Smithd62306a2011-11-10 06:34:14 +00003197/// \param LVal - The glvalue on which we are attempting to perform this action.
3198/// \param RVal - The produced value will be placed here.
Richard Smith243ef902013-05-05 23:31:59 +00003199static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
Richard Smithf57d8cb2011-12-09 22:58:01 +00003200 QualType Type,
Richard Smith2e312c82012-03-03 22:46:17 +00003201 const LValue &LVal, APValue &RVal) {
Richard Smitha8105bc2012-01-06 16:39:00 +00003202 if (LVal.Designator.Invalid)
Richard Smitha8105bc2012-01-06 16:39:00 +00003203 return false;
3204
Richard Smith3229b742013-05-05 21:17:10 +00003205 // Check for special cases where there is no existing APValue to look at.
Richard Smithce40ad62011-11-12 22:28:03 +00003206 const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
George Burgess IVbdb5b262015-08-19 02:19:07 +00003207 if (Base && !LVal.CallIndex && !Type.isVolatileQualified()) {
Richard Smith3229b742013-05-05 21:17:10 +00003208 if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
3209 // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
3210 // initializer until now for such expressions. Such an expression can't be
3211 // an ICE in C, so this only matters for fold.
Richard Smith3229b742013-05-05 21:17:10 +00003212 if (Type.isVolatileQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003213 Info.FFDiag(Conv);
Richard Smith96e0c102011-11-04 02:25:55 +00003214 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00003215 }
Richard Smith3229b742013-05-05 21:17:10 +00003216 APValue Lit;
3217 if (!Evaluate(Lit, Info, CLE->getInitializer()))
3218 return false;
3219 CompleteObject LitObj(&Lit, Base->getType());
3220 return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
Alexey Bataevec474782014-10-09 08:45:04 +00003221 } else if (isa<StringLiteral>(Base) || isa<PredefinedExpr>(Base)) {
Richard Smith3229b742013-05-05 21:17:10 +00003222 // We represent a string literal array as an lvalue pointing at the
3223 // corresponding expression, rather than building an array of chars.
Alexey Bataevec474782014-10-09 08:45:04 +00003224 // FIXME: Support ObjCEncodeExpr, MakeStringConstant
Richard Smith3229b742013-05-05 21:17:10 +00003225 APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
3226 CompleteObject StrObj(&Str, Base->getType());
3227 return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
Richard Smith96e0c102011-11-04 02:25:55 +00003228 }
Richard Smith11562c52011-10-28 17:51:58 +00003229 }
3230
Richard Smith3229b742013-05-05 21:17:10 +00003231 CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
3232 return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
Richard Smith3da88fa2013-04-26 14:36:30 +00003233}
3234
3235/// Perform an assignment of Val to LVal. Takes ownership of Val.
Richard Smith243ef902013-05-05 23:31:59 +00003236static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
Richard Smith3da88fa2013-04-26 14:36:30 +00003237 QualType LValType, APValue &Val) {
Richard Smith3da88fa2013-04-26 14:36:30 +00003238 if (LVal.Designator.Invalid)
Richard Smith3da88fa2013-04-26 14:36:30 +00003239 return false;
3240
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003241 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003242 Info.FFDiag(E);
Richard Smith3da88fa2013-04-26 14:36:30 +00003243 return false;
3244 }
3245
Richard Smith3229b742013-05-05 21:17:10 +00003246 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3247 return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
Richard Smith11562c52011-10-28 17:51:58 +00003248}
3249
Richard Smith243ef902013-05-05 23:31:59 +00003250static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
3251 return T->isSignedIntegerType() &&
3252 Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
3253}
3254
3255namespace {
Richard Smith43e77732013-05-07 04:50:00 +00003256struct CompoundAssignSubobjectHandler {
3257 EvalInfo &Info;
3258 const Expr *E;
3259 QualType PromotedLHSType;
3260 BinaryOperatorKind Opcode;
3261 const APValue &RHS;
3262
3263 static const AccessKinds AccessKind = AK_Assign;
3264
3265 typedef bool result_type;
3266
3267 bool checkConst(QualType QT) {
3268 // Assigning to a const object has undefined behavior.
3269 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003270 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith43e77732013-05-07 04:50:00 +00003271 return false;
3272 }
3273 return true;
3274 }
3275
3276 bool failed() { return false; }
3277 bool found(APValue &Subobj, QualType SubobjType) {
3278 switch (Subobj.getKind()) {
3279 case APValue::Int:
3280 return found(Subobj.getInt(), SubobjType);
3281 case APValue::Float:
3282 return found(Subobj.getFloat(), SubobjType);
3283 case APValue::ComplexInt:
3284 case APValue::ComplexFloat:
3285 // FIXME: Implement complex compound assignment.
Faisal Valie690b7a2016-07-02 22:34:24 +00003286 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003287 return false;
3288 case APValue::LValue:
3289 return foundPointer(Subobj, SubobjType);
3290 default:
3291 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003292 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003293 return false;
3294 }
3295 }
3296 bool found(APSInt &Value, QualType SubobjType) {
3297 if (!checkConst(SubobjType))
3298 return false;
3299
3300 if (!SubobjType->isIntegerType() || !RHS.isInt()) {
3301 // We don't support compound assignment on integer-cast-to-pointer
3302 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003303 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003304 return false;
3305 }
3306
3307 APSInt LHS = HandleIntToIntCast(Info, E, PromotedLHSType,
3308 SubobjType, Value);
3309 if (!handleIntIntBinOp(Info, E, LHS, Opcode, RHS.getInt(), LHS))
3310 return false;
3311 Value = HandleIntToIntCast(Info, E, SubobjType, PromotedLHSType, LHS);
3312 return true;
3313 }
3314 bool found(APFloat &Value, QualType SubobjType) {
Richard Smith861b5b52013-05-07 23:34:45 +00003315 return checkConst(SubobjType) &&
3316 HandleFloatToFloatCast(Info, E, SubobjType, PromotedLHSType,
3317 Value) &&
3318 handleFloatFloatBinOp(Info, E, Value, Opcode, RHS.getFloat()) &&
3319 HandleFloatToFloatCast(Info, E, PromotedLHSType, SubobjType, Value);
Richard Smith43e77732013-05-07 04:50:00 +00003320 }
3321 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3322 if (!checkConst(SubobjType))
3323 return false;
3324
3325 QualType PointeeType;
3326 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3327 PointeeType = PT->getPointeeType();
Richard Smith861b5b52013-05-07 23:34:45 +00003328
3329 if (PointeeType.isNull() || !RHS.isInt() ||
3330 (Opcode != BO_Add && Opcode != BO_Sub)) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003331 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003332 return false;
3333 }
3334
Richard Smithd6cc1982017-01-31 02:23:02 +00003335 APSInt Offset = RHS.getInt();
Richard Smith861b5b52013-05-07 23:34:45 +00003336 if (Opcode == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00003337 negateAsSigned(Offset);
Richard Smith861b5b52013-05-07 23:34:45 +00003338
3339 LValue LVal;
3340 LVal.setFrom(Info.Ctx, Subobj);
3341 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType, Offset))
3342 return false;
3343 LVal.moveInto(Subobj);
3344 return true;
Richard Smith43e77732013-05-07 04:50:00 +00003345 }
3346 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3347 llvm_unreachable("shouldn't encounter string elements here");
3348 }
3349};
3350} // end anonymous namespace
3351
3352const AccessKinds CompoundAssignSubobjectHandler::AccessKind;
3353
3354/// Perform a compound assignment of LVal <op>= RVal.
3355static bool handleCompoundAssignment(
3356 EvalInfo &Info, const Expr *E,
3357 const LValue &LVal, QualType LValType, QualType PromotedLValType,
3358 BinaryOperatorKind Opcode, const APValue &RVal) {
3359 if (LVal.Designator.Invalid)
3360 return false;
3361
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003362 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003363 Info.FFDiag(E);
Richard Smith43e77732013-05-07 04:50:00 +00003364 return false;
3365 }
3366
3367 CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
3368 CompoundAssignSubobjectHandler Handler = { Info, E, PromotedLValType, Opcode,
3369 RVal };
3370 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3371}
3372
3373namespace {
Richard Smith243ef902013-05-05 23:31:59 +00003374struct IncDecSubobjectHandler {
3375 EvalInfo &Info;
3376 const Expr *E;
3377 AccessKinds AccessKind;
3378 APValue *Old;
3379
3380 typedef bool result_type;
3381
3382 bool checkConst(QualType QT) {
3383 // Assigning to a const object has undefined behavior.
3384 if (QT.isConstQualified()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003385 Info.FFDiag(E, diag::note_constexpr_modify_const_type) << QT;
Richard Smith243ef902013-05-05 23:31:59 +00003386 return false;
3387 }
3388 return true;
3389 }
3390
3391 bool failed() { return false; }
3392 bool found(APValue &Subobj, QualType SubobjType) {
3393 // Stash the old value. Also clear Old, so we don't clobber it later
3394 // if we're post-incrementing a complex.
3395 if (Old) {
3396 *Old = Subobj;
Craig Topper36250ad2014-05-12 05:36:57 +00003397 Old = nullptr;
Richard Smith243ef902013-05-05 23:31:59 +00003398 }
3399
3400 switch (Subobj.getKind()) {
3401 case APValue::Int:
3402 return found(Subobj.getInt(), SubobjType);
3403 case APValue::Float:
3404 return found(Subobj.getFloat(), SubobjType);
3405 case APValue::ComplexInt:
3406 return found(Subobj.getComplexIntReal(),
3407 SubobjType->castAs<ComplexType>()->getElementType()
3408 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3409 case APValue::ComplexFloat:
3410 return found(Subobj.getComplexFloatReal(),
3411 SubobjType->castAs<ComplexType>()->getElementType()
3412 .withCVRQualifiers(SubobjType.getCVRQualifiers()));
3413 case APValue::LValue:
3414 return foundPointer(Subobj, SubobjType);
3415 default:
3416 // FIXME: can this happen?
Faisal Valie690b7a2016-07-02 22:34:24 +00003417 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003418 return false;
3419 }
3420 }
3421 bool found(APSInt &Value, QualType SubobjType) {
3422 if (!checkConst(SubobjType))
3423 return false;
3424
3425 if (!SubobjType->isIntegerType()) {
3426 // We don't support increment / decrement on integer-cast-to-pointer
3427 // values.
Faisal Valie690b7a2016-07-02 22:34:24 +00003428 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003429 return false;
3430 }
3431
3432 if (Old) *Old = APValue(Value);
3433
3434 // bool arithmetic promotes to int, and the conversion back to bool
3435 // doesn't reduce mod 2^n, so special-case it.
3436 if (SubobjType->isBooleanType()) {
3437 if (AccessKind == AK_Increment)
3438 Value = 1;
3439 else
3440 Value = !Value;
3441 return true;
3442 }
3443
3444 bool WasNegative = Value.isNegative();
3445 if (AccessKind == AK_Increment) {
3446 ++Value;
3447
3448 if (!WasNegative && Value.isNegative() &&
3449 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3450 APSInt ActualValue(Value, /*IsUnsigned*/true);
Richard Smith0c6124b2015-12-03 01:36:22 +00003451 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003452 }
3453 } else {
3454 --Value;
3455
3456 if (WasNegative && !Value.isNegative() &&
3457 isOverflowingIntegerType(Info.Ctx, SubobjType)) {
3458 unsigned BitWidth = Value.getBitWidth();
3459 APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
3460 ActualValue.setBit(BitWidth);
Richard Smith0c6124b2015-12-03 01:36:22 +00003461 return HandleOverflow(Info, E, ActualValue, SubobjType);
Richard Smith243ef902013-05-05 23:31:59 +00003462 }
3463 }
3464 return true;
3465 }
3466 bool found(APFloat &Value, QualType SubobjType) {
3467 if (!checkConst(SubobjType))
3468 return false;
3469
3470 if (Old) *Old = APValue(Value);
3471
3472 APFloat One(Value.getSemantics(), 1);
3473 if (AccessKind == AK_Increment)
3474 Value.add(One, APFloat::rmNearestTiesToEven);
3475 else
3476 Value.subtract(One, APFloat::rmNearestTiesToEven);
3477 return true;
3478 }
3479 bool foundPointer(APValue &Subobj, QualType SubobjType) {
3480 if (!checkConst(SubobjType))
3481 return false;
3482
3483 QualType PointeeType;
3484 if (const PointerType *PT = SubobjType->getAs<PointerType>())
3485 PointeeType = PT->getPointeeType();
3486 else {
Faisal Valie690b7a2016-07-02 22:34:24 +00003487 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003488 return false;
3489 }
3490
3491 LValue LVal;
3492 LVal.setFrom(Info.Ctx, Subobj);
3493 if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
3494 AccessKind == AK_Increment ? 1 : -1))
3495 return false;
3496 LVal.moveInto(Subobj);
3497 return true;
3498 }
3499 bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
3500 llvm_unreachable("shouldn't encounter string elements here");
3501 }
3502};
3503} // end anonymous namespace
3504
3505/// Perform an increment or decrement on LVal.
3506static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
3507 QualType LValType, bool IsIncrement, APValue *Old) {
3508 if (LVal.Designator.Invalid)
3509 return false;
3510
Aaron Ballmandd69ef32014-08-19 15:55:55 +00003511 if (!Info.getLangOpts().CPlusPlus14) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003512 Info.FFDiag(E);
Richard Smith243ef902013-05-05 23:31:59 +00003513 return false;
3514 }
3515
3516 AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
3517 CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
3518 IncDecSubobjectHandler Handler = { Info, E, AK, Old };
3519 return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
3520}
3521
Richard Smithe97cbd72011-11-11 04:05:33 +00003522/// Build an lvalue for the object argument of a member function call.
3523static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
3524 LValue &This) {
3525 if (Object->getType()->isPointerType())
3526 return EvaluatePointer(Object, This, Info);
3527
3528 if (Object->isGLValue())
3529 return EvaluateLValue(Object, This, Info);
3530
Richard Smithd9f663b2013-04-22 15:31:51 +00003531 if (Object->getType()->isLiteralType(Info.Ctx))
Richard Smith027bf112011-11-17 22:56:20 +00003532 return EvaluateTemporary(Object, This, Info);
3533
Faisal Valie690b7a2016-07-02 22:34:24 +00003534 Info.FFDiag(Object, diag::note_constexpr_nonliteral) << Object->getType();
Richard Smith027bf112011-11-17 22:56:20 +00003535 return false;
3536}
3537
3538/// HandleMemberPointerAccess - Evaluate a member access operation and build an
3539/// lvalue referring to the result.
3540///
3541/// \param Info - Information about the ongoing evaluation.
Richard Smith84401042013-06-03 05:03:02 +00003542/// \param LV - An lvalue referring to the base of the member pointer.
3543/// \param RHS - The member pointer expression.
Richard Smith027bf112011-11-17 22:56:20 +00003544/// \param IncludeMember - Specifies whether the member itself is included in
3545/// the resulting LValue subobject designator. This is not possible when
3546/// creating a bound member function.
3547/// \return The field or method declaration to which the member pointer refers,
3548/// or 0 if evaluation fails.
3549static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
Richard Smith84401042013-06-03 05:03:02 +00003550 QualType LVType,
Richard Smith027bf112011-11-17 22:56:20 +00003551 LValue &LV,
Richard Smith84401042013-06-03 05:03:02 +00003552 const Expr *RHS,
Richard Smith027bf112011-11-17 22:56:20 +00003553 bool IncludeMember = true) {
Richard Smith027bf112011-11-17 22:56:20 +00003554 MemberPtr MemPtr;
Richard Smith84401042013-06-03 05:03:02 +00003555 if (!EvaluateMemberPointer(RHS, MemPtr, Info))
Craig Topper36250ad2014-05-12 05:36:57 +00003556 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003557
3558 // C++11 [expr.mptr.oper]p6: If the second operand is the null pointer to
3559 // member value, the behavior is undefined.
Richard Smith84401042013-06-03 05:03:02 +00003560 if (!MemPtr.getDecl()) {
3561 // FIXME: Specific diagnostic.
Faisal Valie690b7a2016-07-02 22:34:24 +00003562 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003563 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003564 }
Richard Smith253c2a32012-01-27 01:14:48 +00003565
Richard Smith027bf112011-11-17 22:56:20 +00003566 if (MemPtr.isDerivedMember()) {
3567 // This is a member of some derived class. Truncate LV appropriately.
Richard Smith027bf112011-11-17 22:56:20 +00003568 // The end of the derived-to-base path for the base object must match the
3569 // derived-to-base path for the member pointer.
Richard Smitha8105bc2012-01-06 16:39:00 +00003570 if (LV.Designator.MostDerivedPathLength + MemPtr.Path.size() >
Richard Smith84401042013-06-03 05:03:02 +00003571 LV.Designator.Entries.size()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003572 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003573 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003574 }
Richard Smith027bf112011-11-17 22:56:20 +00003575 unsigned PathLengthToMember =
3576 LV.Designator.Entries.size() - MemPtr.Path.size();
3577 for (unsigned I = 0, N = MemPtr.Path.size(); I != N; ++I) {
3578 const CXXRecordDecl *LVDecl = getAsBaseClass(
3579 LV.Designator.Entries[PathLengthToMember + I]);
3580 const CXXRecordDecl *MPDecl = MemPtr.Path[I];
Richard Smith84401042013-06-03 05:03:02 +00003581 if (LVDecl->getCanonicalDecl() != MPDecl->getCanonicalDecl()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00003582 Info.FFDiag(RHS);
Craig Topper36250ad2014-05-12 05:36:57 +00003583 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003584 }
Richard Smith027bf112011-11-17 22:56:20 +00003585 }
3586
3587 // Truncate the lvalue to the appropriate derived class.
Richard Smith84401042013-06-03 05:03:02 +00003588 if (!CastToDerivedClass(Info, RHS, LV, MemPtr.getContainingRecord(),
Richard Smitha8105bc2012-01-06 16:39:00 +00003589 PathLengthToMember))
Craig Topper36250ad2014-05-12 05:36:57 +00003590 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003591 } else if (!MemPtr.Path.empty()) {
3592 // Extend the LValue path with the member pointer's path.
3593 LV.Designator.Entries.reserve(LV.Designator.Entries.size() +
3594 MemPtr.Path.size() + IncludeMember);
3595
3596 // Walk down to the appropriate base class.
Richard Smith027bf112011-11-17 22:56:20 +00003597 if (const PointerType *PT = LVType->getAs<PointerType>())
3598 LVType = PT->getPointeeType();
3599 const CXXRecordDecl *RD = LVType->getAsCXXRecordDecl();
3600 assert(RD && "member pointer access on non-class-type expression");
3601 // The first class in the path is that of the lvalue.
3602 for (unsigned I = 1, N = MemPtr.Path.size(); I != N; ++I) {
3603 const CXXRecordDecl *Base = MemPtr.Path[N - I - 1];
Richard Smith84401042013-06-03 05:03:02 +00003604 if (!HandleLValueDirectBase(Info, RHS, LV, RD, Base))
Craig Topper36250ad2014-05-12 05:36:57 +00003605 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003606 RD = Base;
3607 }
3608 // Finally cast to the class containing the member.
Richard Smith84401042013-06-03 05:03:02 +00003609 if (!HandleLValueDirectBase(Info, RHS, LV, RD,
3610 MemPtr.getContainingRecord()))
Craig Topper36250ad2014-05-12 05:36:57 +00003611 return nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00003612 }
3613
3614 // Add the member. Note that we cannot build bound member functions here.
3615 if (IncludeMember) {
John McCalld7bca762012-05-01 00:38:49 +00003616 if (const FieldDecl *FD = dyn_cast<FieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003617 if (!HandleLValueMember(Info, RHS, LV, FD))
Craig Topper36250ad2014-05-12 05:36:57 +00003618 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003619 } else if (const IndirectFieldDecl *IFD =
3620 dyn_cast<IndirectFieldDecl>(MemPtr.getDecl())) {
Richard Smith84401042013-06-03 05:03:02 +00003621 if (!HandleLValueIndirectMember(Info, RHS, LV, IFD))
Craig Topper36250ad2014-05-12 05:36:57 +00003622 return nullptr;
John McCalld7bca762012-05-01 00:38:49 +00003623 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00003624 llvm_unreachable("can't construct reference to bound member function");
John McCalld7bca762012-05-01 00:38:49 +00003625 }
Richard Smith027bf112011-11-17 22:56:20 +00003626 }
3627
3628 return MemPtr.getDecl();
3629}
3630
Richard Smith84401042013-06-03 05:03:02 +00003631static const ValueDecl *HandleMemberPointerAccess(EvalInfo &Info,
3632 const BinaryOperator *BO,
3633 LValue &LV,
3634 bool IncludeMember = true) {
3635 assert(BO->getOpcode() == BO_PtrMemD || BO->getOpcode() == BO_PtrMemI);
3636
3637 if (!EvaluateObjectArgument(Info, BO->getLHS(), LV)) {
George Burgess IVa145e252016-05-25 22:38:36 +00003638 if (Info.noteFailure()) {
Richard Smith84401042013-06-03 05:03:02 +00003639 MemberPtr MemPtr;
3640 EvaluateMemberPointer(BO->getRHS(), MemPtr, Info);
3641 }
Craig Topper36250ad2014-05-12 05:36:57 +00003642 return nullptr;
Richard Smith84401042013-06-03 05:03:02 +00003643 }
3644
3645 return HandleMemberPointerAccess(Info, BO->getLHS()->getType(), LV,
3646 BO->getRHS(), IncludeMember);
3647}
3648
Richard Smith027bf112011-11-17 22:56:20 +00003649/// HandleBaseToDerivedCast - Apply the given base-to-derived cast operation on
3650/// the provided lvalue, which currently refers to the base object.
3651static bool HandleBaseToDerivedCast(EvalInfo &Info, const CastExpr *E,
3652 LValue &Result) {
Richard Smith027bf112011-11-17 22:56:20 +00003653 SubobjectDesignator &D = Result.Designator;
Richard Smitha8105bc2012-01-06 16:39:00 +00003654 if (D.Invalid || !Result.checkNullPointer(Info, E, CSK_Derived))
Richard Smith027bf112011-11-17 22:56:20 +00003655 return false;
3656
Richard Smitha8105bc2012-01-06 16:39:00 +00003657 QualType TargetQT = E->getType();
3658 if (const PointerType *PT = TargetQT->getAs<PointerType>())
3659 TargetQT = PT->getPointeeType();
3660
3661 // Check this cast lands within the final derived-to-base subobject path.
3662 if (D.MostDerivedPathLength + E->path_size() > D.Entries.size()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003663 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003664 << D.MostDerivedType << TargetQT;
3665 return false;
3666 }
3667
Richard Smith027bf112011-11-17 22:56:20 +00003668 // Check the type of the final cast. We don't need to check the path,
3669 // since a cast can only be formed if the path is unique.
3670 unsigned NewEntriesSize = D.Entries.size() - E->path_size();
Richard Smith027bf112011-11-17 22:56:20 +00003671 const CXXRecordDecl *TargetType = TargetQT->getAsCXXRecordDecl();
3672 const CXXRecordDecl *FinalType;
Richard Smitha8105bc2012-01-06 16:39:00 +00003673 if (NewEntriesSize == D.MostDerivedPathLength)
3674 FinalType = D.MostDerivedType->getAsCXXRecordDecl();
3675 else
Richard Smith027bf112011-11-17 22:56:20 +00003676 FinalType = getAsBaseClass(D.Entries[NewEntriesSize - 1]);
Richard Smitha8105bc2012-01-06 16:39:00 +00003677 if (FinalType->getCanonicalDecl() != TargetType->getCanonicalDecl()) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00003678 Info.CCEDiag(E, diag::note_constexpr_invalid_downcast)
Richard Smitha8105bc2012-01-06 16:39:00 +00003679 << D.MostDerivedType << TargetQT;
Richard Smith027bf112011-11-17 22:56:20 +00003680 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00003681 }
Richard Smith027bf112011-11-17 22:56:20 +00003682
3683 // Truncate the lvalue to the appropriate derived class.
Richard Smitha8105bc2012-01-06 16:39:00 +00003684 return CastToDerivedClass(Info, E, Result, TargetType, NewEntriesSize);
Richard Smithe97cbd72011-11-11 04:05:33 +00003685}
3686
Mike Stump876387b2009-10-27 22:09:17 +00003687namespace {
Richard Smith254a73d2011-10-28 22:34:42 +00003688enum EvalStmtResult {
3689 /// Evaluation failed.
3690 ESR_Failed,
3691 /// Hit a 'return' statement.
3692 ESR_Returned,
3693 /// Evaluation succeeded.
Richard Smith4e18ca52013-05-06 05:56:11 +00003694 ESR_Succeeded,
3695 /// Hit a 'continue' statement.
3696 ESR_Continue,
3697 /// Hit a 'break' statement.
Richard Smith496ddcf2013-05-12 17:32:42 +00003698 ESR_Break,
3699 /// Still scanning for 'case' or 'default' statement.
3700 ESR_CaseNotFound
Richard Smith254a73d2011-10-28 22:34:42 +00003701};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00003702}
Richard Smith254a73d2011-10-28 22:34:42 +00003703
Richard Smith97fcf4b2016-08-14 23:15:52 +00003704static bool EvaluateVarDecl(EvalInfo &Info, const VarDecl *VD) {
3705 // We don't need to evaluate the initializer for a static local.
3706 if (!VD->hasLocalStorage())
3707 return true;
Richard Smithd9f663b2013-04-22 15:31:51 +00003708
Richard Smith97fcf4b2016-08-14 23:15:52 +00003709 LValue Result;
3710 Result.set(VD, Info.CurrentCall->Index);
3711 APValue &Val = Info.CurrentCall->createTemporary(VD, true);
Richard Smithd9f663b2013-04-22 15:31:51 +00003712
Richard Smith97fcf4b2016-08-14 23:15:52 +00003713 const Expr *InitE = VD->getInit();
3714 if (!InitE) {
3715 Info.FFDiag(VD->getLocStart(), diag::note_constexpr_uninitialized)
3716 << false << VD->getType();
3717 Val = APValue();
3718 return false;
3719 }
Richard Smith51f03172013-06-20 03:00:05 +00003720
Richard Smith97fcf4b2016-08-14 23:15:52 +00003721 if (InitE->isValueDependent())
3722 return false;
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00003723
Richard Smith97fcf4b2016-08-14 23:15:52 +00003724 if (!EvaluateInPlace(Val, Info, Result, InitE)) {
3725 // Wipe out any partially-computed value, to allow tracking that this
3726 // evaluation failed.
3727 Val = APValue();
3728 return false;
Richard Smithd9f663b2013-04-22 15:31:51 +00003729 }
3730
3731 return true;
3732}
3733
Richard Smith97fcf4b2016-08-14 23:15:52 +00003734static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
3735 bool OK = true;
3736
3737 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
3738 OK &= EvaluateVarDecl(Info, VD);
3739
3740 if (const DecompositionDecl *DD = dyn_cast<DecompositionDecl>(D))
3741 for (auto *BD : DD->bindings())
3742 if (auto *VD = BD->getHoldingVar())
3743 OK &= EvaluateDecl(Info, VD);
3744
3745 return OK;
3746}
3747
3748
Richard Smith4e18ca52013-05-06 05:56:11 +00003749/// Evaluate a condition (either a variable declaration or an expression).
3750static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
3751 const Expr *Cond, bool &Result) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003752 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003753 if (CondDecl && !EvaluateDecl(Info, CondDecl))
3754 return false;
3755 return EvaluateAsBooleanCondition(Cond, Result, Info);
3756}
3757
Richard Smith89210072016-04-04 23:29:43 +00003758namespace {
Richard Smith52a980a2015-08-28 02:43:42 +00003759/// \brief A location where the result (returned value) of evaluating a
3760/// statement should be stored.
3761struct StmtResult {
3762 /// The APValue that should be filled in with the returned value.
3763 APValue &Value;
3764 /// The location containing the result, if any (used to support RVO).
3765 const LValue *Slot;
3766};
Richard Smith89210072016-04-04 23:29:43 +00003767}
Richard Smith52a980a2015-08-28 02:43:42 +00003768
3769static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Craig Topper36250ad2014-05-12 05:36:57 +00003770 const Stmt *S,
3771 const SwitchCase *SC = nullptr);
Richard Smith4e18ca52013-05-06 05:56:11 +00003772
3773/// Evaluate the body of a loop, and translate the result as appropriate.
Richard Smith52a980a2015-08-28 02:43:42 +00003774static EvalStmtResult EvaluateLoopBody(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003775 const Stmt *Body,
Craig Topper36250ad2014-05-12 05:36:57 +00003776 const SwitchCase *Case = nullptr) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003777 BlockScopeRAII Scope(Info);
Richard Smith496ddcf2013-05-12 17:32:42 +00003778 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body, Case)) {
Richard Smith4e18ca52013-05-06 05:56:11 +00003779 case ESR_Break:
3780 return ESR_Succeeded;
3781 case ESR_Succeeded:
3782 case ESR_Continue:
3783 return ESR_Continue;
3784 case ESR_Failed:
3785 case ESR_Returned:
Richard Smith496ddcf2013-05-12 17:32:42 +00003786 case ESR_CaseNotFound:
Richard Smith4e18ca52013-05-06 05:56:11 +00003787 return ESR;
3788 }
Hans Wennborg9242bd12013-05-06 15:13:34 +00003789 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith4e18ca52013-05-06 05:56:11 +00003790}
3791
Richard Smith496ddcf2013-05-12 17:32:42 +00003792/// Evaluate a switch statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003793static EvalStmtResult EvaluateSwitch(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003794 const SwitchStmt *SS) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003795 BlockScopeRAII Scope(Info);
3796
Richard Smith496ddcf2013-05-12 17:32:42 +00003797 // Evaluate the switch condition.
Richard Smith496ddcf2013-05-12 17:32:42 +00003798 APSInt Value;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003799 {
3800 FullExpressionRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003801 if (const Stmt *Init = SS->getInit()) {
3802 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3803 if (ESR != ESR_Succeeded)
3804 return ESR;
3805 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00003806 if (SS->getConditionVariable() &&
3807 !EvaluateDecl(Info, SS->getConditionVariable()))
3808 return ESR_Failed;
3809 if (!EvaluateInteger(SS->getCond(), Value, Info))
3810 return ESR_Failed;
3811 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003812
3813 // Find the switch case corresponding to the value of the condition.
3814 // FIXME: Cache this lookup.
Craig Topper36250ad2014-05-12 05:36:57 +00003815 const SwitchCase *Found = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003816 for (const SwitchCase *SC = SS->getSwitchCaseList(); SC;
3817 SC = SC->getNextSwitchCase()) {
3818 if (isa<DefaultStmt>(SC)) {
3819 Found = SC;
3820 continue;
3821 }
3822
3823 const CaseStmt *CS = cast<CaseStmt>(SC);
3824 APSInt LHS = CS->getLHS()->EvaluateKnownConstInt(Info.Ctx);
3825 APSInt RHS = CS->getRHS() ? CS->getRHS()->EvaluateKnownConstInt(Info.Ctx)
3826 : LHS;
3827 if (LHS <= Value && Value <= RHS) {
3828 Found = SC;
3829 break;
3830 }
3831 }
3832
3833 if (!Found)
3834 return ESR_Succeeded;
3835
3836 // Search the switch body for the switch case and evaluate it from there.
3837 switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, SS->getBody(), Found)) {
3838 case ESR_Break:
3839 return ESR_Succeeded;
3840 case ESR_Succeeded:
3841 case ESR_Continue:
3842 case ESR_Failed:
3843 case ESR_Returned:
3844 return ESR;
3845 case ESR_CaseNotFound:
Richard Smith51f03172013-06-20 03:00:05 +00003846 // This can only happen if the switch case is nested within a statement
3847 // expression. We have no intention of supporting that.
Faisal Valie690b7a2016-07-02 22:34:24 +00003848 Info.FFDiag(Found->getLocStart(), diag::note_constexpr_stmt_expr_unsupported);
Richard Smith51f03172013-06-20 03:00:05 +00003849 return ESR_Failed;
Richard Smith496ddcf2013-05-12 17:32:42 +00003850 }
Richard Smithf8cf9d42013-05-13 20:33:30 +00003851 llvm_unreachable("Invalid EvalStmtResult!");
Richard Smith496ddcf2013-05-12 17:32:42 +00003852}
3853
Richard Smith254a73d2011-10-28 22:34:42 +00003854// Evaluate a statement.
Richard Smith52a980a2015-08-28 02:43:42 +00003855static EvalStmtResult EvaluateStmt(StmtResult &Result, EvalInfo &Info,
Richard Smith496ddcf2013-05-12 17:32:42 +00003856 const Stmt *S, const SwitchCase *Case) {
Richard Smitha3d3bd22013-05-08 02:12:03 +00003857 if (!Info.nextStep(S))
3858 return ESR_Failed;
3859
Richard Smith496ddcf2013-05-12 17:32:42 +00003860 // If we're hunting down a 'case' or 'default' label, recurse through
3861 // substatements until we hit the label.
3862 if (Case) {
3863 // FIXME: We don't start the lifetime of objects whose initialization we
3864 // jump over. However, such objects must be of class type with a trivial
3865 // default constructor that initialize all subobjects, so must be empty,
3866 // so this almost never matters.
3867 switch (S->getStmtClass()) {
3868 case Stmt::CompoundStmtClass:
3869 // FIXME: Precompute which substatement of a compound statement we
3870 // would jump to, and go straight there rather than performing a
3871 // linear scan each time.
3872 case Stmt::LabelStmtClass:
3873 case Stmt::AttributedStmtClass:
3874 case Stmt::DoStmtClass:
3875 break;
3876
3877 case Stmt::CaseStmtClass:
3878 case Stmt::DefaultStmtClass:
3879 if (Case == S)
Craig Topper36250ad2014-05-12 05:36:57 +00003880 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003881 break;
3882
3883 case Stmt::IfStmtClass: {
3884 // FIXME: Precompute which side of an 'if' we would jump to, and go
3885 // straight there rather than scanning both sides.
3886 const IfStmt *IS = cast<IfStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00003887
3888 // Wrap the evaluation in a block scope, in case it's a DeclStmt
3889 // preceded by our switch label.
3890 BlockScopeRAII Scope(Info);
3891
Richard Smith496ddcf2013-05-12 17:32:42 +00003892 EvalStmtResult ESR = EvaluateStmt(Result, Info, IS->getThen(), Case);
3893 if (ESR != ESR_CaseNotFound || !IS->getElse())
3894 return ESR;
3895 return EvaluateStmt(Result, Info, IS->getElse(), Case);
3896 }
3897
3898 case Stmt::WhileStmtClass: {
3899 EvalStmtResult ESR =
3900 EvaluateLoopBody(Result, Info, cast<WhileStmt>(S)->getBody(), Case);
3901 if (ESR != ESR_Continue)
3902 return ESR;
3903 break;
3904 }
3905
3906 case Stmt::ForStmtClass: {
3907 const ForStmt *FS = cast<ForStmt>(S);
3908 EvalStmtResult ESR =
3909 EvaluateLoopBody(Result, Info, FS->getBody(), Case);
3910 if (ESR != ESR_Continue)
3911 return ESR;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003912 if (FS->getInc()) {
3913 FullExpressionRAII IncScope(Info);
3914 if (!EvaluateIgnoredValue(Info, FS->getInc()))
3915 return ESR_Failed;
3916 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003917 break;
3918 }
3919
3920 case Stmt::DeclStmtClass:
3921 // FIXME: If the variable has initialization that can't be jumped over,
3922 // bail out of any immediately-surrounding compound-statement too.
3923 default:
3924 return ESR_CaseNotFound;
3925 }
3926 }
3927
Richard Smith254a73d2011-10-28 22:34:42 +00003928 switch (S->getStmtClass()) {
3929 default:
Richard Smithd9f663b2013-04-22 15:31:51 +00003930 if (const Expr *E = dyn_cast<Expr>(S)) {
Richard Smithd9f663b2013-04-22 15:31:51 +00003931 // Don't bother evaluating beyond an expression-statement which couldn't
3932 // be evaluated.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003933 FullExpressionRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00003934 if (!EvaluateIgnoredValue(Info, E))
Richard Smithd9f663b2013-04-22 15:31:51 +00003935 return ESR_Failed;
3936 return ESR_Succeeded;
3937 }
3938
Faisal Valie690b7a2016-07-02 22:34:24 +00003939 Info.FFDiag(S->getLocStart());
Richard Smith254a73d2011-10-28 22:34:42 +00003940 return ESR_Failed;
3941
3942 case Stmt::NullStmtClass:
Richard Smith254a73d2011-10-28 22:34:42 +00003943 return ESR_Succeeded;
3944
Richard Smithd9f663b2013-04-22 15:31:51 +00003945 case Stmt::DeclStmtClass: {
3946 const DeclStmt *DS = cast<DeclStmt>(S);
Aaron Ballman535bbcc2014-03-14 17:01:24 +00003947 for (const auto *DclIt : DS->decls()) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003948 // Each declaration initialization is its own full-expression.
3949 // FIXME: This isn't quite right; if we're performing aggregate
3950 // initialization, each braced subexpression is its own full-expression.
3951 FullExpressionRAII Scope(Info);
George Burgess IVa145e252016-05-25 22:38:36 +00003952 if (!EvaluateDecl(Info, DclIt) && !Info.noteFailure())
Richard Smithd9f663b2013-04-22 15:31:51 +00003953 return ESR_Failed;
Richard Smith08d6a2c2013-07-24 07:11:57 +00003954 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003955 return ESR_Succeeded;
3956 }
3957
Richard Smith357362d2011-12-13 06:39:58 +00003958 case Stmt::ReturnStmtClass: {
Richard Smith357362d2011-12-13 06:39:58 +00003959 const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
Richard Smith08d6a2c2013-07-24 07:11:57 +00003960 FullExpressionRAII Scope(Info);
Richard Smith52a980a2015-08-28 02:43:42 +00003961 if (RetExpr &&
3962 !(Result.Slot
3963 ? EvaluateInPlace(Result.Value, Info, *Result.Slot, RetExpr)
3964 : Evaluate(Result.Value, Info, RetExpr)))
Richard Smith357362d2011-12-13 06:39:58 +00003965 return ESR_Failed;
3966 return ESR_Returned;
3967 }
Richard Smith254a73d2011-10-28 22:34:42 +00003968
3969 case Stmt::CompoundStmtClass: {
Richard Smith08d6a2c2013-07-24 07:11:57 +00003970 BlockScopeRAII Scope(Info);
3971
Richard Smith254a73d2011-10-28 22:34:42 +00003972 const CompoundStmt *CS = cast<CompoundStmt>(S);
Aaron Ballmanc7e4e212014-03-17 14:19:37 +00003973 for (const auto *BI : CS->body()) {
3974 EvalStmtResult ESR = EvaluateStmt(Result, Info, BI, Case);
Richard Smith496ddcf2013-05-12 17:32:42 +00003975 if (ESR == ESR_Succeeded)
Craig Topper36250ad2014-05-12 05:36:57 +00003976 Case = nullptr;
Richard Smith496ddcf2013-05-12 17:32:42 +00003977 else if (ESR != ESR_CaseNotFound)
Richard Smith254a73d2011-10-28 22:34:42 +00003978 return ESR;
3979 }
Richard Smith496ddcf2013-05-12 17:32:42 +00003980 return Case ? ESR_CaseNotFound : ESR_Succeeded;
Richard Smith254a73d2011-10-28 22:34:42 +00003981 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003982
3983 case Stmt::IfStmtClass: {
3984 const IfStmt *IS = cast<IfStmt>(S);
3985
3986 // Evaluate the condition, as either a var decl or as an expression.
Richard Smith08d6a2c2013-07-24 07:11:57 +00003987 BlockScopeRAII Scope(Info);
Richard Smitha547eb22016-07-14 00:11:03 +00003988 if (const Stmt *Init = IS->getInit()) {
3989 EvalStmtResult ESR = EvaluateStmt(Result, Info, Init);
3990 if (ESR != ESR_Succeeded)
3991 return ESR;
3992 }
Richard Smithd9f663b2013-04-22 15:31:51 +00003993 bool Cond;
Richard Smith4e18ca52013-05-06 05:56:11 +00003994 if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
Richard Smithd9f663b2013-04-22 15:31:51 +00003995 return ESR_Failed;
3996
3997 if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
3998 EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
3999 if (ESR != ESR_Succeeded)
4000 return ESR;
4001 }
4002 return ESR_Succeeded;
4003 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004004
4005 case Stmt::WhileStmtClass: {
4006 const WhileStmt *WS = cast<WhileStmt>(S);
4007 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004008 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004009 bool Continue;
4010 if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
4011 Continue))
4012 return ESR_Failed;
4013 if (!Continue)
4014 break;
4015
4016 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
4017 if (ESR != ESR_Continue)
4018 return ESR;
4019 }
4020 return ESR_Succeeded;
4021 }
4022
4023 case Stmt::DoStmtClass: {
4024 const DoStmt *DS = cast<DoStmt>(S);
4025 bool Continue;
4026 do {
Richard Smith496ddcf2013-05-12 17:32:42 +00004027 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody(), Case);
Richard Smith4e18ca52013-05-06 05:56:11 +00004028 if (ESR != ESR_Continue)
4029 return ESR;
Craig Topper36250ad2014-05-12 05:36:57 +00004030 Case = nullptr;
Richard Smith4e18ca52013-05-06 05:56:11 +00004031
Richard Smith08d6a2c2013-07-24 07:11:57 +00004032 FullExpressionRAII CondScope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004033 if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
4034 return ESR_Failed;
4035 } while (Continue);
4036 return ESR_Succeeded;
4037 }
4038
4039 case Stmt::ForStmtClass: {
4040 const ForStmt *FS = cast<ForStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004041 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004042 if (FS->getInit()) {
4043 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
4044 if (ESR != ESR_Succeeded)
4045 return ESR;
4046 }
4047 while (true) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004048 BlockScopeRAII Scope(Info);
Richard Smith4e18ca52013-05-06 05:56:11 +00004049 bool Continue = true;
4050 if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
4051 FS->getCond(), Continue))
4052 return ESR_Failed;
4053 if (!Continue)
4054 break;
4055
4056 EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4057 if (ESR != ESR_Continue)
4058 return ESR;
4059
Richard Smith08d6a2c2013-07-24 07:11:57 +00004060 if (FS->getInc()) {
4061 FullExpressionRAII IncScope(Info);
4062 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4063 return ESR_Failed;
4064 }
Richard Smith4e18ca52013-05-06 05:56:11 +00004065 }
4066 return ESR_Succeeded;
4067 }
4068
Richard Smith896e0d72013-05-06 06:51:17 +00004069 case Stmt::CXXForRangeStmtClass: {
4070 const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
Richard Smith08d6a2c2013-07-24 07:11:57 +00004071 BlockScopeRAII Scope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004072
4073 // Initialize the __range variable.
4074 EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
4075 if (ESR != ESR_Succeeded)
4076 return ESR;
4077
4078 // Create the __begin and __end iterators.
Richard Smith01694c32016-03-20 10:33:40 +00004079 ESR = EvaluateStmt(Result, Info, FS->getBeginStmt());
4080 if (ESR != ESR_Succeeded)
4081 return ESR;
4082 ESR = EvaluateStmt(Result, Info, FS->getEndStmt());
Richard Smith896e0d72013-05-06 06:51:17 +00004083 if (ESR != ESR_Succeeded)
4084 return ESR;
4085
4086 while (true) {
4087 // Condition: __begin != __end.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004088 {
4089 bool Continue = true;
4090 FullExpressionRAII CondExpr(Info);
4091 if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
4092 return ESR_Failed;
4093 if (!Continue)
4094 break;
4095 }
Richard Smith896e0d72013-05-06 06:51:17 +00004096
4097 // User's variable declaration, initialized by *__begin.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004098 BlockScopeRAII InnerScope(Info);
Richard Smith896e0d72013-05-06 06:51:17 +00004099 ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
4100 if (ESR != ESR_Succeeded)
4101 return ESR;
4102
4103 // Loop body.
4104 ESR = EvaluateLoopBody(Result, Info, FS->getBody());
4105 if (ESR != ESR_Continue)
4106 return ESR;
4107
4108 // Increment: ++__begin
4109 if (!EvaluateIgnoredValue(Info, FS->getInc()))
4110 return ESR_Failed;
4111 }
4112
4113 return ESR_Succeeded;
4114 }
4115
Richard Smith496ddcf2013-05-12 17:32:42 +00004116 case Stmt::SwitchStmtClass:
4117 return EvaluateSwitch(Result, Info, cast<SwitchStmt>(S));
4118
Richard Smith4e18ca52013-05-06 05:56:11 +00004119 case Stmt::ContinueStmtClass:
4120 return ESR_Continue;
4121
4122 case Stmt::BreakStmtClass:
4123 return ESR_Break;
Richard Smith496ddcf2013-05-12 17:32:42 +00004124
4125 case Stmt::LabelStmtClass:
4126 return EvaluateStmt(Result, Info, cast<LabelStmt>(S)->getSubStmt(), Case);
4127
4128 case Stmt::AttributedStmtClass:
4129 // As a general principle, C++11 attributes can be ignored without
4130 // any semantic impact.
4131 return EvaluateStmt(Result, Info, cast<AttributedStmt>(S)->getSubStmt(),
4132 Case);
4133
4134 case Stmt::CaseStmtClass:
4135 case Stmt::DefaultStmtClass:
4136 return EvaluateStmt(Result, Info, cast<SwitchCase>(S)->getSubStmt(), Case);
Richard Smith254a73d2011-10-28 22:34:42 +00004137 }
4138}
4139
Richard Smithcc36f692011-12-22 02:22:31 +00004140/// CheckTrivialDefaultConstructor - Check whether a constructor is a trivial
4141/// default constructor. If so, we'll fold it whether or not it's marked as
4142/// constexpr. If it is marked as constexpr, we will never implicitly define it,
4143/// so we need special handling.
4144static bool CheckTrivialDefaultConstructor(EvalInfo &Info, SourceLocation Loc,
Richard Smithfddd3842011-12-30 21:15:51 +00004145 const CXXConstructorDecl *CD,
4146 bool IsValueInitialization) {
Richard Smithcc36f692011-12-22 02:22:31 +00004147 if (!CD->isTrivial() || !CD->isDefaultConstructor())
4148 return false;
4149
Richard Smith66e05fe2012-01-18 05:21:49 +00004150 // Value-initialization does not call a trivial default constructor, so such a
4151 // call is a core constant expression whether or not the constructor is
4152 // constexpr.
4153 if (!CD->isConstexpr() && !IsValueInitialization) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004154 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith66e05fe2012-01-18 05:21:49 +00004155 // FIXME: If DiagDecl is an implicitly-declared special member function,
4156 // we should be much more explicit about why it's not constexpr.
4157 Info.CCEDiag(Loc, diag::note_constexpr_invalid_function, 1)
4158 << /*IsConstexpr*/0 << /*IsConstructor*/1 << CD;
4159 Info.Note(CD->getLocation(), diag::note_declared_at);
Richard Smithcc36f692011-12-22 02:22:31 +00004160 } else {
4161 Info.CCEDiag(Loc, diag::note_invalid_subexpr_in_const_expr);
4162 }
4163 }
4164 return true;
4165}
4166
Richard Smith357362d2011-12-13 06:39:58 +00004167/// CheckConstexprFunction - Check that a function can be called in a constant
4168/// expression.
4169static bool CheckConstexprFunction(EvalInfo &Info, SourceLocation CallLoc,
4170 const FunctionDecl *Declaration,
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004171 const FunctionDecl *Definition,
4172 const Stmt *Body) {
Richard Smith253c2a32012-01-27 01:14:48 +00004173 // Potential constant expressions can contain calls to declared, but not yet
4174 // defined, constexpr functions.
Richard Smith6d4c6582013-11-05 22:18:15 +00004175 if (Info.checkingPotentialConstantExpression() && !Definition &&
Richard Smith253c2a32012-01-27 01:14:48 +00004176 Declaration->isConstexpr())
4177 return false;
4178
Richard Smith0838f3a2013-05-14 05:18:44 +00004179 // Bail out with no diagnostic if the function declaration itself is invalid.
4180 // We will have produced a relevant diagnostic while parsing it.
4181 if (Declaration->isInvalidDecl())
4182 return false;
4183
Richard Smith357362d2011-12-13 06:39:58 +00004184 // Can we evaluate this function call?
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00004185 if (Definition && Definition->isConstexpr() &&
4186 !Definition->isInvalidDecl() && Body)
Richard Smith357362d2011-12-13 06:39:58 +00004187 return true;
4188
Richard Smith2bf7fdb2013-01-02 11:42:31 +00004189 if (Info.getLangOpts().CPlusPlus11) {
Richard Smith357362d2011-12-13 06:39:58 +00004190 const FunctionDecl *DiagDecl = Definition ? Definition : Declaration;
Daniel Jasperffdee092017-05-02 19:21:42 +00004191
Richard Smith5179eb72016-06-28 19:03:57 +00004192 // If this function is not constexpr because it is an inherited
4193 // non-constexpr constructor, diagnose that directly.
4194 auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
4195 if (CD && CD->isInheritingConstructor()) {
4196 auto *Inherited = CD->getInheritedConstructor().getConstructor();
Daniel Jasperffdee092017-05-02 19:21:42 +00004197 if (!Inherited->isConstexpr())
Richard Smith5179eb72016-06-28 19:03:57 +00004198 DiagDecl = CD = Inherited;
4199 }
4200
4201 // FIXME: If DiagDecl is an implicitly-declared special member function
4202 // or an inheriting constructor, we should be much more explicit about why
4203 // it's not constexpr.
4204 if (CD && CD->isInheritingConstructor())
Faisal Valie690b7a2016-07-02 22:34:24 +00004205 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_inhctor, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004206 << CD->getInheritedConstructor().getConstructor()->getParent();
4207 else
Faisal Valie690b7a2016-07-02 22:34:24 +00004208 Info.FFDiag(CallLoc, diag::note_constexpr_invalid_function, 1)
Richard Smith5179eb72016-06-28 19:03:57 +00004209 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
Richard Smith357362d2011-12-13 06:39:58 +00004210 Info.Note(DiagDecl->getLocation(), diag::note_declared_at);
4211 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00004212 Info.FFDiag(CallLoc, diag::note_invalid_subexpr_in_const_expr);
Richard Smith357362d2011-12-13 06:39:58 +00004213 }
4214 return false;
4215}
4216
Richard Smithbe6dd812014-11-19 21:27:17 +00004217/// Determine if a class has any fields that might need to be copied by a
4218/// trivial copy or move operation.
4219static bool hasFields(const CXXRecordDecl *RD) {
4220 if (!RD || RD->isEmpty())
4221 return false;
4222 for (auto *FD : RD->fields()) {
4223 if (FD->isUnnamedBitfield())
4224 continue;
4225 return true;
4226 }
4227 for (auto &Base : RD->bases())
4228 if (hasFields(Base.getType()->getAsCXXRecordDecl()))
4229 return true;
4230 return false;
4231}
4232
Richard Smithd62306a2011-11-10 06:34:14 +00004233namespace {
Richard Smith2e312c82012-03-03 22:46:17 +00004234typedef SmallVector<APValue, 8> ArgVector;
Richard Smithd62306a2011-11-10 06:34:14 +00004235}
4236
4237/// EvaluateArgs - Evaluate the arguments to a function call.
4238static bool EvaluateArgs(ArrayRef<const Expr*> Args, ArgVector &ArgValues,
4239 EvalInfo &Info) {
Richard Smith253c2a32012-01-27 01:14:48 +00004240 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004241 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
Richard Smith253c2a32012-01-27 01:14:48 +00004242 I != E; ++I) {
4243 if (!Evaluate(ArgValues[I - Args.begin()], Info, *I)) {
4244 // If we're checking for a potential constant expression, evaluate all
4245 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004246 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004247 return false;
4248 Success = false;
4249 }
4250 }
4251 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00004252}
4253
Richard Smith254a73d2011-10-28 22:34:42 +00004254/// Evaluate a function call.
Richard Smith253c2a32012-01-27 01:14:48 +00004255static bool HandleFunctionCall(SourceLocation CallLoc,
4256 const FunctionDecl *Callee, const LValue *This,
Richard Smithf57d8cb2011-12-09 22:58:01 +00004257 ArrayRef<const Expr*> Args, const Stmt *Body,
Richard Smith52a980a2015-08-28 02:43:42 +00004258 EvalInfo &Info, APValue &Result,
4259 const LValue *ResultSlot) {
Richard Smithd62306a2011-11-10 06:34:14 +00004260 ArgVector ArgValues(Args.size());
4261 if (!EvaluateArgs(Args, ArgValues, Info))
4262 return false;
Richard Smith254a73d2011-10-28 22:34:42 +00004263
Richard Smith253c2a32012-01-27 01:14:48 +00004264 if (!Info.CheckCallLimit(CallLoc))
4265 return false;
4266
4267 CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
Richard Smith99005e62013-05-07 03:19:20 +00004268
4269 // For a trivial copy or move assignment, perform an APValue copy. This is
4270 // essential for unions, where the operations performed by the assignment
4271 // operator cannot be represented as statements.
Richard Smithbe6dd812014-11-19 21:27:17 +00004272 //
4273 // Skip this for non-union classes with no fields; in that case, the defaulted
4274 // copy/move does not actually read the object.
Richard Smith99005e62013-05-07 03:19:20 +00004275 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Callee);
Richard Smith419bd092015-04-29 19:26:57 +00004276 if (MD && MD->isDefaulted() &&
4277 (MD->getParent()->isUnion() ||
4278 (MD->isTrivial() && hasFields(MD->getParent())))) {
Richard Smith99005e62013-05-07 03:19:20 +00004279 assert(This &&
4280 (MD->isCopyAssignmentOperator() || MD->isMoveAssignmentOperator()));
4281 LValue RHS;
4282 RHS.setFrom(Info.Ctx, ArgValues[0]);
4283 APValue RHSValue;
4284 if (!handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
4285 RHS, RHSValue))
4286 return false;
4287 if (!handleAssignment(Info, Args[0], *This, MD->getThisType(Info.Ctx),
4288 RHSValue))
4289 return false;
4290 This->moveInto(Result);
4291 return true;
Faisal Vali051e3a22017-02-16 04:12:21 +00004292 } else if (MD && isLambdaCallOperator(MD)) {
4293 // We're in a lambda; determine the lambda capture field maps.
4294 MD->getParent()->getCaptureFields(Frame.LambdaCaptureFields,
4295 Frame.LambdaThisCaptureField);
Richard Smith99005e62013-05-07 03:19:20 +00004296 }
4297
Richard Smith52a980a2015-08-28 02:43:42 +00004298 StmtResult Ret = {Result, ResultSlot};
4299 EvalStmtResult ESR = EvaluateStmt(Ret, Info, Body);
Richard Smith3da88fa2013-04-26 14:36:30 +00004300 if (ESR == ESR_Succeeded) {
Alp Toker314cc812014-01-25 16:55:45 +00004301 if (Callee->getReturnType()->isVoidType())
Richard Smith3da88fa2013-04-26 14:36:30 +00004302 return true;
Faisal Valie690b7a2016-07-02 22:34:24 +00004303 Info.FFDiag(Callee->getLocEnd(), diag::note_constexpr_no_return);
Richard Smith3da88fa2013-04-26 14:36:30 +00004304 }
Richard Smithd9f663b2013-04-22 15:31:51 +00004305 return ESR == ESR_Returned;
Richard Smith254a73d2011-10-28 22:34:42 +00004306}
4307
Richard Smithd62306a2011-11-10 06:34:14 +00004308/// Evaluate a constructor call.
Richard Smith5179eb72016-06-28 19:03:57 +00004309static bool HandleConstructorCall(const Expr *E, const LValue &This,
4310 APValue *ArgValues,
Richard Smithd62306a2011-11-10 06:34:14 +00004311 const CXXConstructorDecl *Definition,
Richard Smithfddd3842011-12-30 21:15:51 +00004312 EvalInfo &Info, APValue &Result) {
Richard Smith5179eb72016-06-28 19:03:57 +00004313 SourceLocation CallLoc = E->getExprLoc();
Richard Smith253c2a32012-01-27 01:14:48 +00004314 if (!Info.CheckCallLimit(CallLoc))
4315 return false;
4316
Richard Smith3607ffe2012-02-13 03:54:03 +00004317 const CXXRecordDecl *RD = Definition->getParent();
4318 if (RD->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004319 Info.FFDiag(CallLoc, diag::note_constexpr_virtual_base) << RD;
Richard Smith3607ffe2012-02-13 03:54:03 +00004320 return false;
4321 }
4322
Erik Pilkington42925492017-10-04 00:18:55 +00004323 EvalInfo::EvaluatingConstructorRAII EvalObj(
4324 Info, {This.getLValueBase(), This.CallIndex});
Richard Smith5179eb72016-06-28 19:03:57 +00004325 CallStackFrame Frame(Info, CallLoc, Definition, &This, ArgValues);
Richard Smithd62306a2011-11-10 06:34:14 +00004326
Richard Smith52a980a2015-08-28 02:43:42 +00004327 // FIXME: Creating an APValue just to hold a nonexistent return value is
4328 // wasteful.
4329 APValue RetVal;
4330 StmtResult Ret = {RetVal, nullptr};
4331
Richard Smith5179eb72016-06-28 19:03:57 +00004332 // If it's a delegating constructor, delegate.
Richard Smithd62306a2011-11-10 06:34:14 +00004333 if (Definition->isDelegatingConstructor()) {
4334 CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
Richard Smith9ff62af2013-11-07 18:45:03 +00004335 {
4336 FullExpressionRAII InitScope(Info);
4337 if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
4338 return false;
4339 }
Richard Smith52a980a2015-08-28 02:43:42 +00004340 return EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004341 }
4342
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004343 // For a trivial copy or move constructor, perform an APValue copy. This is
Richard Smithbe6dd812014-11-19 21:27:17 +00004344 // essential for unions (or classes with anonymous union members), where the
4345 // operations performed by the constructor cannot be represented by
4346 // ctor-initializers.
4347 //
4348 // Skip this for empty non-union classes; we should not perform an
4349 // lvalue-to-rvalue conversion on them because their copy constructor does not
4350 // actually read them.
Richard Smith419bd092015-04-29 19:26:57 +00004351 if (Definition->isDefaulted() && Definition->isCopyOrMoveConstructor() &&
Richard Smithbe6dd812014-11-19 21:27:17 +00004352 (Definition->getParent()->isUnion() ||
Richard Smith419bd092015-04-29 19:26:57 +00004353 (Definition->isTrivial() && hasFields(Definition->getParent())))) {
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004354 LValue RHS;
Richard Smith2e312c82012-03-03 22:46:17 +00004355 RHS.setFrom(Info.Ctx, ArgValues[0]);
Richard Smith5179eb72016-06-28 19:03:57 +00004356 return handleLValueToRValueConversion(
4357 Info, E, Definition->getParamDecl(0)->getType().getNonReferenceType(),
4358 RHS, Result);
Richard Smith1bc5c2c2012-01-10 04:32:03 +00004359 }
4360
4361 // Reserve space for the struct members.
Richard Smithfddd3842011-12-30 21:15:51 +00004362 if (!RD->isUnion() && Result.isUninit())
Richard Smithd62306a2011-11-10 06:34:14 +00004363 Result = APValue(APValue::UninitStruct(), RD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004364 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00004365
John McCalld7bca762012-05-01 00:38:49 +00004366 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004367 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
4368
Richard Smith08d6a2c2013-07-24 07:11:57 +00004369 // A scope for temporaries lifetime-extended by reference members.
4370 BlockScopeRAII LifetimeExtendedScope(Info);
4371
Richard Smith253c2a32012-01-27 01:14:48 +00004372 bool Success = true;
Richard Smithd62306a2011-11-10 06:34:14 +00004373 unsigned BasesSeen = 0;
4374#ifndef NDEBUG
4375 CXXRecordDecl::base_class_const_iterator BaseIt = RD->bases_begin();
4376#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004377 for (const auto *I : Definition->inits()) {
Richard Smith253c2a32012-01-27 01:14:48 +00004378 LValue Subobject = This;
4379 APValue *Value = &Result;
4380
4381 // Determine the subobject to initialize.
Craig Topper36250ad2014-05-12 05:36:57 +00004382 FieldDecl *FD = nullptr;
Aaron Ballman0ad78302014-03-13 17:34:31 +00004383 if (I->isBaseInitializer()) {
4384 QualType BaseType(I->getBaseClass(), 0);
Richard Smithd62306a2011-11-10 06:34:14 +00004385#ifndef NDEBUG
4386 // Non-virtual base classes are initialized in the order in the class
Richard Smith3607ffe2012-02-13 03:54:03 +00004387 // definition. We have already checked for virtual base classes.
Richard Smithd62306a2011-11-10 06:34:14 +00004388 assert(!BaseIt->isVirtual() && "virtual base for literal type");
4389 assert(Info.Ctx.hasSameType(BaseIt->getType(), BaseType) &&
4390 "base class initializers not in expected order");
4391 ++BaseIt;
4392#endif
Aaron Ballman0ad78302014-03-13 17:34:31 +00004393 if (!HandleLValueDirectBase(Info, I->getInit(), Subobject, RD,
John McCalld7bca762012-05-01 00:38:49 +00004394 BaseType->getAsCXXRecordDecl(), &Layout))
4395 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00004396 Value = &Result.getStructBase(BasesSeen++);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004397 } else if ((FD = I->getMember())) {
4398 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00004399 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00004400 if (RD->isUnion()) {
4401 Result = APValue(FD);
Richard Smith253c2a32012-01-27 01:14:48 +00004402 Value = &Result.getUnionValue();
4403 } else {
4404 Value = &Result.getStructField(FD->getFieldIndex());
4405 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004406 } else if (IndirectFieldDecl *IFD = I->getIndirectMember()) {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004407 // Walk the indirect field decl's chain to find the object to initialize,
4408 // and make sure we've initialized every step along it.
Aaron Ballman29c94602014-03-07 18:36:15 +00004409 for (auto *C : IFD->chain()) {
Aaron Ballman13916082014-03-07 18:11:58 +00004410 FD = cast<FieldDecl>(C);
Richard Smith1b78b3d2012-01-25 22:15:11 +00004411 CXXRecordDecl *CD = cast<CXXRecordDecl>(FD->getParent());
4412 // Switch the union field if it differs. This happens if we had
4413 // preceding zero-initialization, and we're now initializing a union
4414 // subobject other than the first.
4415 // FIXME: In this case, the values of the other subobjects are
4416 // specified, since zero-initialization sets all padding bits to zero.
4417 if (Value->isUninit() ||
4418 (Value->isUnion() && Value->getUnionField() != FD)) {
4419 if (CD->isUnion())
4420 *Value = APValue(FD);
4421 else
4422 *Value = APValue(APValue::UninitStruct(), CD->getNumBases(),
Aaron Ballman62e47c42014-03-10 13:43:55 +00004423 std::distance(CD->field_begin(), CD->field_end()));
Richard Smith1b78b3d2012-01-25 22:15:11 +00004424 }
Aaron Ballman0ad78302014-03-13 17:34:31 +00004425 if (!HandleLValueMember(Info, I->getInit(), Subobject, FD))
John McCalld7bca762012-05-01 00:38:49 +00004426 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00004427 if (CD->isUnion())
4428 Value = &Value->getUnionValue();
4429 else
4430 Value = &Value->getStructField(FD->getFieldIndex());
Richard Smith1b78b3d2012-01-25 22:15:11 +00004431 }
Richard Smithd62306a2011-11-10 06:34:14 +00004432 } else {
Richard Smith1b78b3d2012-01-25 22:15:11 +00004433 llvm_unreachable("unknown base initializer kind");
Richard Smithd62306a2011-11-10 06:34:14 +00004434 }
Richard Smith253c2a32012-01-27 01:14:48 +00004435
Richard Smith08d6a2c2013-07-24 07:11:57 +00004436 FullExpressionRAII InitScope(Info);
Aaron Ballman0ad78302014-03-13 17:34:31 +00004437 if (!EvaluateInPlace(*Value, Info, Subobject, I->getInit()) ||
4438 (FD && FD->isBitField() && !truncateBitfieldValue(Info, I->getInit(),
Richard Smith49ca8aa2013-08-06 07:09:20 +00004439 *Value, FD))) {
Richard Smith253c2a32012-01-27 01:14:48 +00004440 // If we're checking for a potential constant expression, evaluate all
4441 // initializers even if some of them fail.
George Burgess IVa145e252016-05-25 22:38:36 +00004442 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00004443 return false;
4444 Success = false;
4445 }
Richard Smithd62306a2011-11-10 06:34:14 +00004446 }
4447
Richard Smithd9f663b2013-04-22 15:31:51 +00004448 return Success &&
Richard Smith52a980a2015-08-28 02:43:42 +00004449 EvaluateStmt(Ret, Info, Definition->getBody()) != ESR_Failed;
Richard Smithd62306a2011-11-10 06:34:14 +00004450}
4451
Richard Smith5179eb72016-06-28 19:03:57 +00004452static bool HandleConstructorCall(const Expr *E, const LValue &This,
4453 ArrayRef<const Expr*> Args,
4454 const CXXConstructorDecl *Definition,
4455 EvalInfo &Info, APValue &Result) {
4456 ArgVector ArgValues(Args.size());
4457 if (!EvaluateArgs(Args, ArgValues, Info))
4458 return false;
4459
4460 return HandleConstructorCall(E, This, ArgValues.data(), Definition,
4461 Info, Result);
4462}
4463
Eli Friedman9a156e52008-11-12 09:44:48 +00004464//===----------------------------------------------------------------------===//
Peter Collingbournee9200682011-05-13 03:29:01 +00004465// Generic Evaluation
4466//===----------------------------------------------------------------------===//
4467namespace {
4468
Aaron Ballman68af21c2014-01-03 19:26:43 +00004469template <class Derived>
Peter Collingbournee9200682011-05-13 03:29:01 +00004470class ExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004471 : public ConstStmtVisitor<Derived, bool> {
Peter Collingbournee9200682011-05-13 03:29:01 +00004472private:
Richard Smith52a980a2015-08-28 02:43:42 +00004473 Derived &getDerived() { return static_cast<Derived&>(*this); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004474 bool DerivedSuccess(const APValue &V, const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004475 return getDerived().Success(V, E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004476 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004477 bool DerivedZeroInitialization(const Expr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004478 return getDerived().ZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004479 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004480
Richard Smith17100ba2012-02-16 02:46:34 +00004481 // Check whether a conditional operator with a non-constant condition is a
4482 // potential constant expression. If neither arm is a potential constant
4483 // expression, then the conditional operator is not either.
4484 template<typename ConditionalOperator>
4485 void CheckPotentialConstantConditional(const ConditionalOperator *E) {
Richard Smith6d4c6582013-11-05 22:18:15 +00004486 assert(Info.checkingPotentialConstantExpression());
Richard Smith17100ba2012-02-16 02:46:34 +00004487
4488 // Speculatively evaluate both arms.
George Burgess IV8c892b52016-05-25 22:31:54 +00004489 SmallVector<PartialDiagnosticAt, 8> Diag;
Richard Smith17100ba2012-02-16 02:46:34 +00004490 {
Richard Smith17100ba2012-02-16 02:46:34 +00004491 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004492 StmtVisitorTy::Visit(E->getFalseExpr());
4493 if (Diag.empty())
4494 return;
George Burgess IV8c892b52016-05-25 22:31:54 +00004495 }
Richard Smith17100ba2012-02-16 02:46:34 +00004496
George Burgess IV8c892b52016-05-25 22:31:54 +00004497 {
4498 SpeculativeEvaluationRAII Speculate(Info, &Diag);
Richard Smith17100ba2012-02-16 02:46:34 +00004499 Diag.clear();
4500 StmtVisitorTy::Visit(E->getTrueExpr());
4501 if (Diag.empty())
4502 return;
4503 }
4504
4505 Error(E, diag::note_constexpr_conditional_never_const);
4506 }
4507
4508
4509 template<typename ConditionalOperator>
4510 bool HandleConditionalOperator(const ConditionalOperator *E) {
4511 bool BoolResult;
4512 if (!EvaluateAsBooleanCondition(E->getCond(), BoolResult, Info)) {
Nick Lewycky20edee62017-04-27 07:11:09 +00004513 if (Info.checkingPotentialConstantExpression() && Info.noteFailure()) {
Richard Smith17100ba2012-02-16 02:46:34 +00004514 CheckPotentialConstantConditional(E);
Nick Lewycky20edee62017-04-27 07:11:09 +00004515 return false;
4516 }
4517 if (Info.noteFailure()) {
4518 StmtVisitorTy::Visit(E->getTrueExpr());
4519 StmtVisitorTy::Visit(E->getFalseExpr());
4520 }
Richard Smith17100ba2012-02-16 02:46:34 +00004521 return false;
4522 }
4523
4524 Expr *EvalExpr = BoolResult ? E->getTrueExpr() : E->getFalseExpr();
4525 return StmtVisitorTy::Visit(EvalExpr);
4526 }
4527
Peter Collingbournee9200682011-05-13 03:29:01 +00004528protected:
4529 EvalInfo &Info;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004530 typedef ConstStmtVisitor<Derived, bool> StmtVisitorTy;
Peter Collingbournee9200682011-05-13 03:29:01 +00004531 typedef ExprEvaluatorBase ExprEvaluatorBaseTy;
4532
Richard Smith92b1ce02011-12-12 09:28:41 +00004533 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
Richard Smithce1ec5e2012-03-15 04:53:45 +00004534 return Info.CCEDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004535 }
4536
Aaron Ballman68af21c2014-01-03 19:26:43 +00004537 bool ZeroInitialization(const Expr *E) { return Error(E); }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00004538
4539public:
4540 ExprEvaluatorBase(EvalInfo &Info) : Info(Info) {}
4541
4542 EvalInfo &getEvalInfo() { return Info; }
4543
Richard Smithf57d8cb2011-12-09 22:58:01 +00004544 /// Report an evaluation error. This should only be called when an error is
4545 /// first discovered. When propagating an error, just return false.
4546 bool Error(const Expr *E, diag::kind D) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004547 Info.FFDiag(E, D);
Richard Smithf57d8cb2011-12-09 22:58:01 +00004548 return false;
4549 }
4550 bool Error(const Expr *E) {
4551 return Error(E, diag::note_invalid_subexpr_in_const_expr);
4552 }
4553
Aaron Ballman68af21c2014-01-03 19:26:43 +00004554 bool VisitStmt(const Stmt *) {
David Blaikie83d382b2011-09-23 05:06:16 +00004555 llvm_unreachable("Expression evaluator should not be called on stmts");
Peter Collingbournee9200682011-05-13 03:29:01 +00004556 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004557 bool VisitExpr(const Expr *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004558 return Error(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004559 }
4560
Aaron Ballman68af21c2014-01-03 19:26:43 +00004561 bool VisitParenExpr(const ParenExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004562 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004563 bool VisitUnaryExtension(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004564 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004565 bool VisitUnaryPlus(const UnaryOperator *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004566 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004567 bool VisitChooseExpr(const ChooseExpr *E)
Eli Friedman75807f22013-07-20 00:40:58 +00004568 { return StmtVisitorTy::Visit(E->getChosenSubExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004569 bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Peter Collingbournee9200682011-05-13 03:29:01 +00004570 { return StmtVisitorTy::Visit(E->getResultExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004571 bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
John McCall7c454bb2011-07-15 05:09:51 +00004572 { return StmtVisitorTy::Visit(E->getReplacement()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004573 bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Richard Smithf8120ca2011-11-09 02:12:41 +00004574 { return StmtVisitorTy::Visit(E->getExpr()); }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004575 bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
Richard Smith17e32462013-09-13 20:51:45 +00004576 // The initializer may not have been parsed yet, or might be erroneous.
4577 if (!E->getExpr())
4578 return Error(E);
4579 return StmtVisitorTy::Visit(E->getExpr());
4580 }
Richard Smith5894a912011-12-19 22:12:41 +00004581 // We cannot create any objects for which cleanups are required, so there is
4582 // nothing to do here; all cleanups must come from unevaluated subexpressions.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004583 bool VisitExprWithCleanups(const ExprWithCleanups *E)
Richard Smith5894a912011-12-19 22:12:41 +00004584 { return StmtVisitorTy::Visit(E->getSubExpr()); }
Peter Collingbournee9200682011-05-13 03:29:01 +00004585
Aaron Ballman68af21c2014-01-03 19:26:43 +00004586 bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004587 CCEDiag(E, diag::note_constexpr_invalid_cast) << 0;
4588 return static_cast<Derived*>(this)->VisitCastExpr(E);
4589 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004590 bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E) {
Richard Smith6d6ecc32011-12-12 12:46:16 +00004591 CCEDiag(E, diag::note_constexpr_invalid_cast) << 1;
4592 return static_cast<Derived*>(this)->VisitCastExpr(E);
4593 }
4594
Aaron Ballman68af21c2014-01-03 19:26:43 +00004595 bool VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00004596 switch (E->getOpcode()) {
4597 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00004598 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00004599
4600 case BO_Comma:
4601 VisitIgnoredValue(E->getLHS());
4602 return StmtVisitorTy::Visit(E->getRHS());
4603
4604 case BO_PtrMemD:
4605 case BO_PtrMemI: {
4606 LValue Obj;
4607 if (!HandleMemberPointerAccess(Info, E, Obj))
4608 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004609 APValue Result;
Richard Smith243ef902013-05-05 23:31:59 +00004610 if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
Richard Smith027bf112011-11-17 22:56:20 +00004611 return false;
4612 return DerivedSuccess(Result, E);
4613 }
4614 }
4615 }
4616
Aaron Ballman68af21c2014-01-03 19:26:43 +00004617 bool VisitBinaryConditionalOperator(const BinaryConditionalOperator *E) {
Richard Smith26d4cc12012-06-26 08:12:11 +00004618 // Evaluate and cache the common expression. We treat it as a temporary,
4619 // even though it's not quite the same thing.
Richard Smith08d6a2c2013-07-24 07:11:57 +00004620 if (!Evaluate(Info.CurrentCall->createTemporary(E->getOpaqueValue(), false),
Richard Smith26d4cc12012-06-26 08:12:11 +00004621 Info, E->getCommon()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004622 return false;
Peter Collingbournee9200682011-05-13 03:29:01 +00004623
Richard Smith17100ba2012-02-16 02:46:34 +00004624 return HandleConditionalOperator(E);
Peter Collingbournee9200682011-05-13 03:29:01 +00004625 }
4626
Aaron Ballman68af21c2014-01-03 19:26:43 +00004627 bool VisitConditionalOperator(const ConditionalOperator *E) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00004628 bool IsBcpCall = false;
4629 // If the condition (ignoring parens) is a __builtin_constant_p call,
4630 // the result is a constant expression if it can be folded without
4631 // side-effects. This is an important GNU extension. See GCC PR38377
4632 // for discussion.
4633 if (const CallExpr *CallCE =
4634 dyn_cast<CallExpr>(E->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +00004635 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004636 IsBcpCall = true;
4637
4638 // Always assume __builtin_constant_p(...) ? ... : ... is a potential
4639 // constant expression; we can't check whether it's potentially foldable.
Richard Smith6d4c6582013-11-05 22:18:15 +00004640 if (Info.checkingPotentialConstantExpression() && IsBcpCall)
Richard Smith84f6dcf2012-02-02 01:16:57 +00004641 return false;
4642
Richard Smith6d4c6582013-11-05 22:18:15 +00004643 FoldConstant Fold(Info, IsBcpCall);
4644 if (!HandleConditionalOperator(E)) {
4645 Fold.keepDiagnostics();
Richard Smith84f6dcf2012-02-02 01:16:57 +00004646 return false;
Richard Smith6d4c6582013-11-05 22:18:15 +00004647 }
Richard Smith84f6dcf2012-02-02 01:16:57 +00004648
4649 return true;
Peter Collingbournee9200682011-05-13 03:29:01 +00004650 }
4651
Aaron Ballman68af21c2014-01-03 19:26:43 +00004652 bool VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
Richard Smith08d6a2c2013-07-24 07:11:57 +00004653 if (APValue *Value = Info.CurrentCall->getTemporary(E))
4654 return DerivedSuccess(*Value, E);
4655
4656 const Expr *Source = E->getSourceExpr();
4657 if (!Source)
4658 return Error(E);
4659 if (Source == E) { // sanity checking.
4660 assert(0 && "OpaqueValueExpr recursively refers to itself");
4661 return Error(E);
Argyrios Kyrtzidisfac35c02011-12-09 02:44:48 +00004662 }
Richard Smith08d6a2c2013-07-24 07:11:57 +00004663 return StmtVisitorTy::Visit(Source);
Peter Collingbournee9200682011-05-13 03:29:01 +00004664 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004665
Aaron Ballman68af21c2014-01-03 19:26:43 +00004666 bool VisitCallExpr(const CallExpr *E) {
Richard Smith52a980a2015-08-28 02:43:42 +00004667 APValue Result;
4668 if (!handleCallExpr(E, Result, nullptr))
4669 return false;
4670 return DerivedSuccess(Result, E);
4671 }
4672
4673 bool handleCallExpr(const CallExpr *E, APValue &Result,
Nick Lewycky13073a62017-06-12 21:15:44 +00004674 const LValue *ResultSlot) {
Richard Smith027bf112011-11-17 22:56:20 +00004675 const Expr *Callee = E->getCallee()->IgnoreParens();
Richard Smith254a73d2011-10-28 22:34:42 +00004676 QualType CalleeType = Callee->getType();
4677
Craig Topper36250ad2014-05-12 05:36:57 +00004678 const FunctionDecl *FD = nullptr;
4679 LValue *This = nullptr, ThisVal;
Craig Topper5fc8fc22014-08-27 06:28:36 +00004680 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith3607ffe2012-02-13 03:54:03 +00004681 bool HasQualifier = false;
Richard Smith656d49d2011-11-10 09:31:24 +00004682
Richard Smithe97cbd72011-11-11 04:05:33 +00004683 // Extract function decl and 'this' pointer from the callee.
4684 if (CalleeType->isSpecificBuiltinType(BuiltinType::BoundMember)) {
Craig Topper36250ad2014-05-12 05:36:57 +00004685 const ValueDecl *Member = nullptr;
Richard Smith027bf112011-11-17 22:56:20 +00004686 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Callee)) {
4687 // Explicit bound member calls, such as x.f() or p->g();
4688 if (!EvaluateObjectArgument(Info, ME->getBase(), ThisVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004689 return false;
4690 Member = ME->getMemberDecl();
Richard Smith027bf112011-11-17 22:56:20 +00004691 This = &ThisVal;
Richard Smith3607ffe2012-02-13 03:54:03 +00004692 HasQualifier = ME->hasQualifier();
Richard Smith027bf112011-11-17 22:56:20 +00004693 } else if (const BinaryOperator *BE = dyn_cast<BinaryOperator>(Callee)) {
4694 // Indirect bound member calls ('.*' or '->*').
Richard Smithf57d8cb2011-12-09 22:58:01 +00004695 Member = HandleMemberPointerAccess(Info, BE, ThisVal, false);
4696 if (!Member) return false;
Richard Smith027bf112011-11-17 22:56:20 +00004697 This = &ThisVal;
Richard Smith027bf112011-11-17 22:56:20 +00004698 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004699 return Error(Callee);
4700
4701 FD = dyn_cast<FunctionDecl>(Member);
4702 if (!FD)
4703 return Error(Callee);
Richard Smithe97cbd72011-11-11 04:05:33 +00004704 } else if (CalleeType->isFunctionPointerType()) {
Richard Smitha8105bc2012-01-06 16:39:00 +00004705 LValue Call;
4706 if (!EvaluatePointer(Callee, Call, Info))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004707 return false;
Richard Smithe97cbd72011-11-11 04:05:33 +00004708
Richard Smitha8105bc2012-01-06 16:39:00 +00004709 if (!Call.getLValueOffset().isZero())
Richard Smithf57d8cb2011-12-09 22:58:01 +00004710 return Error(Callee);
Richard Smithce40ad62011-11-12 22:28:03 +00004711 FD = dyn_cast_or_null<FunctionDecl>(
4712 Call.getLValueBase().dyn_cast<const ValueDecl*>());
Richard Smithe97cbd72011-11-11 04:05:33 +00004713 if (!FD)
Richard Smithf57d8cb2011-12-09 22:58:01 +00004714 return Error(Callee);
Faisal Valid92e7492017-01-08 18:56:11 +00004715 // Don't call function pointers which have been cast to some other type.
4716 // Per DR (no number yet), the caller and callee can differ in noexcept.
4717 if (!Info.Ctx.hasSameFunctionTypeIgnoringExceptionSpec(
4718 CalleeType->getPointeeType(), FD->getType())) {
4719 return Error(E);
4720 }
Richard Smithe97cbd72011-11-11 04:05:33 +00004721
4722 // Overloaded operator calls to member functions are represented as normal
4723 // calls with '*this' as the first argument.
4724 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
4725 if (MD && !MD->isStatic()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00004726 // FIXME: When selecting an implicit conversion for an overloaded
4727 // operator delete, we sometimes try to evaluate calls to conversion
4728 // operators without a 'this' parameter!
4729 if (Args.empty())
4730 return Error(E);
4731
Nick Lewycky13073a62017-06-12 21:15:44 +00004732 if (!EvaluateObjectArgument(Info, Args[0], ThisVal))
Richard Smithe97cbd72011-11-11 04:05:33 +00004733 return false;
4734 This = &ThisVal;
Nick Lewycky13073a62017-06-12 21:15:44 +00004735 Args = Args.slice(1);
Daniel Jasperffdee092017-05-02 19:21:42 +00004736 } else if (MD && MD->isLambdaStaticInvoker()) {
Faisal Valid92e7492017-01-08 18:56:11 +00004737 // Map the static invoker for the lambda back to the call operator.
4738 // Conveniently, we don't have to slice out the 'this' argument (as is
4739 // being done for the non-static case), since a static member function
4740 // doesn't have an implicit argument passed in.
4741 const CXXRecordDecl *ClosureClass = MD->getParent();
4742 assert(
4743 ClosureClass->captures_begin() == ClosureClass->captures_end() &&
4744 "Number of captures must be zero for conversion to function-ptr");
4745
4746 const CXXMethodDecl *LambdaCallOp =
4747 ClosureClass->getLambdaCallOperator();
4748
4749 // Set 'FD', the function that will be called below, to the call
4750 // operator. If the closure object represents a generic lambda, find
4751 // the corresponding specialization of the call operator.
4752
4753 if (ClosureClass->isGenericLambda()) {
4754 assert(MD->isFunctionTemplateSpecialization() &&
4755 "A generic lambda's static-invoker function must be a "
4756 "template specialization");
4757 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs();
4758 FunctionTemplateDecl *CallOpTemplate =
4759 LambdaCallOp->getDescribedFunctionTemplate();
4760 void *InsertPos = nullptr;
4761 FunctionDecl *CorrespondingCallOpSpecialization =
4762 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
4763 assert(CorrespondingCallOpSpecialization &&
4764 "We must always have a function call operator specialization "
4765 "that corresponds to our static invoker specialization");
4766 FD = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization);
4767 } else
4768 FD = LambdaCallOp;
Richard Smithe97cbd72011-11-11 04:05:33 +00004769 }
4770
Daniel Jasperffdee092017-05-02 19:21:42 +00004771
Richard Smithe97cbd72011-11-11 04:05:33 +00004772 } else
Richard Smithf57d8cb2011-12-09 22:58:01 +00004773 return Error(E);
Richard Smith254a73d2011-10-28 22:34:42 +00004774
Richard Smith47b34932012-02-01 02:39:43 +00004775 if (This && !This->checkSubobject(Info, E, CSK_This))
4776 return false;
4777
Richard Smith3607ffe2012-02-13 03:54:03 +00004778 // DR1358 allows virtual constexpr functions in some cases. Don't allow
4779 // calls to such functions in constant expressions.
4780 if (This && !HasQualifier &&
4781 isa<CXXMethodDecl>(FD) && cast<CXXMethodDecl>(FD)->isVirtual())
4782 return Error(E, diag::note_constexpr_virtual_call);
4783
Craig Topper36250ad2014-05-12 05:36:57 +00004784 const FunctionDecl *Definition = nullptr;
Richard Smith254a73d2011-10-28 22:34:42 +00004785 Stmt *Body = FD->getBody(Definition);
Richard Smith254a73d2011-10-28 22:34:42 +00004786
Nick Lewycky13073a62017-06-12 21:15:44 +00004787 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body) ||
4788 !HandleFunctionCall(E->getExprLoc(), Definition, This, Args, Body, Info,
Richard Smith52a980a2015-08-28 02:43:42 +00004789 Result, ResultSlot))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004790 return false;
4791
Richard Smith52a980a2015-08-28 02:43:42 +00004792 return true;
Richard Smith254a73d2011-10-28 22:34:42 +00004793 }
4794
Aaron Ballman68af21c2014-01-03 19:26:43 +00004795 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004796 return StmtVisitorTy::Visit(E->getInitializer());
4797 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004798 bool VisitInitListExpr(const InitListExpr *E) {
Eli Friedman90dc1752012-01-03 23:54:05 +00004799 if (E->getNumInits() == 0)
4800 return DerivedZeroInitialization(E);
4801 if (E->getNumInits() == 1)
4802 return StmtVisitorTy::Visit(E->getInit(0));
Richard Smithf57d8cb2011-12-09 22:58:01 +00004803 return Error(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004804 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004805 bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004806 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004807 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004808 bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004809 return DerivedZeroInitialization(E);
Richard Smith4ce706a2011-10-11 21:43:33 +00004810 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004811 bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00004812 return DerivedZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00004813 }
Richard Smith4ce706a2011-10-11 21:43:33 +00004814
Richard Smithd62306a2011-11-10 06:34:14 +00004815 /// A member expression where the object is a prvalue is itself a prvalue.
Aaron Ballman68af21c2014-01-03 19:26:43 +00004816 bool VisitMemberExpr(const MemberExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00004817 assert(!E->isArrow() && "missing call to bound member function?");
4818
Richard Smith2e312c82012-03-03 22:46:17 +00004819 APValue Val;
Richard Smithd62306a2011-11-10 06:34:14 +00004820 if (!Evaluate(Val, Info, E->getBase()))
4821 return false;
4822
4823 QualType BaseTy = E->getBase()->getType();
4824
4825 const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl());
Richard Smithf57d8cb2011-12-09 22:58:01 +00004826 if (!FD) return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00004827 assert(!FD->getType()->isReferenceType() && "prvalue reference?");
Ted Kremenek28831752012-08-23 20:46:57 +00004828 assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
Richard Smithd62306a2011-11-10 06:34:14 +00004829 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
4830
Richard Smith3229b742013-05-05 21:17:10 +00004831 CompleteObject Obj(&Val, BaseTy);
Richard Smitha8105bc2012-01-06 16:39:00 +00004832 SubobjectDesignator Designator(BaseTy);
4833 Designator.addDeclUnchecked(FD);
Richard Smithd62306a2011-11-10 06:34:14 +00004834
Richard Smith3229b742013-05-05 21:17:10 +00004835 APValue Result;
4836 return extractSubobject(Info, E, Obj, Designator, Result) &&
4837 DerivedSuccess(Result, E);
Richard Smithd62306a2011-11-10 06:34:14 +00004838 }
4839
Aaron Ballman68af21c2014-01-03 19:26:43 +00004840 bool VisitCastExpr(const CastExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00004841 switch (E->getCastKind()) {
4842 default:
4843 break;
4844
Richard Smitha23ab512013-05-23 00:30:41 +00004845 case CK_AtomicToNonAtomic: {
4846 APValue AtomicVal;
Richard Smith64cb9ca2017-02-22 22:09:50 +00004847 // This does not need to be done in place even for class/array types:
4848 // atomic-to-non-atomic conversion implies copying the object
4849 // representation.
4850 if (!Evaluate(AtomicVal, Info, E->getSubExpr()))
Richard Smitha23ab512013-05-23 00:30:41 +00004851 return false;
4852 return DerivedSuccess(AtomicVal, E);
4853 }
4854
Richard Smith11562c52011-10-28 17:51:58 +00004855 case CK_NoOp:
Richard Smith4ef685b2012-01-17 21:17:26 +00004856 case CK_UserDefinedConversion:
Richard Smith11562c52011-10-28 17:51:58 +00004857 return StmtVisitorTy::Visit(E->getSubExpr());
4858
4859 case CK_LValueToRValue: {
4860 LValue LVal;
Richard Smithf57d8cb2011-12-09 22:58:01 +00004861 if (!EvaluateLValue(E->getSubExpr(), LVal, Info))
4862 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00004863 APValue RVal;
Richard Smithc82fae62012-02-05 01:23:16 +00004864 // Note, we use the subexpression's type in order to retain cv-qualifiers.
Richard Smith243ef902013-05-05 23:31:59 +00004865 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
Richard Smithc82fae62012-02-05 01:23:16 +00004866 LVal, RVal))
Richard Smithf57d8cb2011-12-09 22:58:01 +00004867 return false;
4868 return DerivedSuccess(RVal, E);
Richard Smith11562c52011-10-28 17:51:58 +00004869 }
4870 }
4871
Richard Smithf57d8cb2011-12-09 22:58:01 +00004872 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00004873 }
4874
Aaron Ballman68af21c2014-01-03 19:26:43 +00004875 bool VisitUnaryPostInc(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004876 return VisitUnaryPostIncDec(UO);
4877 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004878 bool VisitUnaryPostDec(const UnaryOperator *UO) {
Richard Smith243ef902013-05-05 23:31:59 +00004879 return VisitUnaryPostIncDec(UO);
4880 }
Aaron Ballman68af21c2014-01-03 19:26:43 +00004881 bool VisitUnaryPostIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00004882 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00004883 return Error(UO);
4884
4885 LValue LVal;
4886 if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
4887 return false;
4888 APValue RVal;
4889 if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
4890 UO->isIncrementOp(), &RVal))
4891 return false;
4892 return DerivedSuccess(RVal, UO);
4893 }
4894
Aaron Ballman68af21c2014-01-03 19:26:43 +00004895 bool VisitStmtExpr(const StmtExpr *E) {
Richard Smith51f03172013-06-20 03:00:05 +00004896 // We will have checked the full-expressions inside the statement expression
4897 // when they were completed, and don't need to check them again now.
Richard Smith6d4c6582013-11-05 22:18:15 +00004898 if (Info.checkingForOverflow())
Richard Smith51f03172013-06-20 03:00:05 +00004899 return Error(E);
4900
Richard Smith08d6a2c2013-07-24 07:11:57 +00004901 BlockScopeRAII Scope(Info);
Richard Smith51f03172013-06-20 03:00:05 +00004902 const CompoundStmt *CS = E->getSubStmt();
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004903 if (CS->body_empty())
4904 return true;
4905
Richard Smith51f03172013-06-20 03:00:05 +00004906 for (CompoundStmt::const_body_iterator BI = CS->body_begin(),
4907 BE = CS->body_end();
4908 /**/; ++BI) {
4909 if (BI + 1 == BE) {
4910 const Expr *FinalExpr = dyn_cast<Expr>(*BI);
4911 if (!FinalExpr) {
Faisal Valie690b7a2016-07-02 22:34:24 +00004912 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004913 diag::note_constexpr_stmt_expr_unsupported);
4914 return false;
4915 }
4916 return this->Visit(FinalExpr);
4917 }
4918
4919 APValue ReturnValue;
Richard Smith52a980a2015-08-28 02:43:42 +00004920 StmtResult Result = { ReturnValue, nullptr };
4921 EvalStmtResult ESR = EvaluateStmt(Result, Info, *BI);
Richard Smith51f03172013-06-20 03:00:05 +00004922 if (ESR != ESR_Succeeded) {
4923 // FIXME: If the statement-expression terminated due to 'return',
4924 // 'break', or 'continue', it would be nice to propagate that to
4925 // the outer statement evaluation rather than bailing out.
4926 if (ESR != ESR_Failed)
Faisal Valie690b7a2016-07-02 22:34:24 +00004927 Info.FFDiag((*BI)->getLocStart(),
Richard Smith51f03172013-06-20 03:00:05 +00004928 diag::note_constexpr_stmt_expr_unsupported);
4929 return false;
4930 }
4931 }
Jonathan Roelofs104cbf92015-06-01 16:23:08 +00004932
4933 llvm_unreachable("Return from function from the loop above.");
Richard Smith51f03172013-06-20 03:00:05 +00004934 }
4935
Richard Smith4a678122011-10-24 18:44:57 +00004936 /// Visit a value which is evaluated, but whose value is ignored.
4937 void VisitIgnoredValue(const Expr *E) {
Richard Smithd9f663b2013-04-22 15:31:51 +00004938 EvaluateIgnoredValue(Info, E);
Richard Smith4a678122011-10-24 18:44:57 +00004939 }
David Majnemere9807b22016-02-26 04:23:19 +00004940
4941 /// Potentially visit a MemberExpr's base expression.
4942 void VisitIgnoredBaseExpression(const Expr *E) {
4943 // While MSVC doesn't evaluate the base expression, it does diagnose the
4944 // presence of side-effecting behavior.
4945 if (Info.getLangOpts().MSVCCompat && !E->HasSideEffects(Info.Ctx))
4946 return;
4947 VisitIgnoredValue(E);
4948 }
Peter Collingbournee9200682011-05-13 03:29:01 +00004949};
4950
Alexander Kornienkoab9db512015-06-22 23:07:51 +00004951}
Peter Collingbournee9200682011-05-13 03:29:01 +00004952
4953//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00004954// Common base class for lvalue and temporary evaluation.
4955//===----------------------------------------------------------------------===//
4956namespace {
4957template<class Derived>
4958class LValueExprEvaluatorBase
Aaron Ballman68af21c2014-01-03 19:26:43 +00004959 : public ExprEvaluatorBase<Derived> {
Richard Smith027bf112011-11-17 22:56:20 +00004960protected:
4961 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00004962 bool InvalidBaseOK;
Richard Smith027bf112011-11-17 22:56:20 +00004963 typedef LValueExprEvaluatorBase LValueExprEvaluatorBaseTy;
Aaron Ballman68af21c2014-01-03 19:26:43 +00004964 typedef ExprEvaluatorBase<Derived> ExprEvaluatorBaseTy;
Richard Smith027bf112011-11-17 22:56:20 +00004965
4966 bool Success(APValue::LValueBase B) {
4967 Result.set(B);
4968 return true;
4969 }
4970
George Burgess IVf9013bf2017-02-10 22:52:29 +00004971 bool evaluatePointer(const Expr *E, LValue &Result) {
4972 return EvaluatePointer(E, Result, this->Info, InvalidBaseOK);
4973 }
4974
Richard Smith027bf112011-11-17 22:56:20 +00004975public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00004976 LValueExprEvaluatorBase(EvalInfo &Info, LValue &Result, bool InvalidBaseOK)
4977 : ExprEvaluatorBaseTy(Info), Result(Result),
4978 InvalidBaseOK(InvalidBaseOK) {}
Richard Smith027bf112011-11-17 22:56:20 +00004979
Richard Smith2e312c82012-03-03 22:46:17 +00004980 bool Success(const APValue &V, const Expr *E) {
4981 Result.setFrom(this->Info.Ctx, V);
Richard Smith027bf112011-11-17 22:56:20 +00004982 return true;
4983 }
Richard Smith027bf112011-11-17 22:56:20 +00004984
Richard Smith027bf112011-11-17 22:56:20 +00004985 bool VisitMemberExpr(const MemberExpr *E) {
4986 // Handle non-static data members.
4987 QualType BaseTy;
George Burgess IV3a03fab2015-09-04 21:28:13 +00004988 bool EvalOK;
Richard Smith027bf112011-11-17 22:56:20 +00004989 if (E->isArrow()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00004990 EvalOK = evaluatePointer(E->getBase(), Result);
Ted Kremenek28831752012-08-23 20:46:57 +00004991 BaseTy = E->getBase()->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith357362d2011-12-13 06:39:58 +00004992 } else if (E->getBase()->isRValue()) {
Richard Smithd0b111c2011-12-19 22:01:37 +00004993 assert(E->getBase()->getType()->isRecordType());
George Burgess IV3a03fab2015-09-04 21:28:13 +00004994 EvalOK = EvaluateTemporary(E->getBase(), Result, this->Info);
Richard Smith357362d2011-12-13 06:39:58 +00004995 BaseTy = E->getBase()->getType();
Richard Smith027bf112011-11-17 22:56:20 +00004996 } else {
George Burgess IV3a03fab2015-09-04 21:28:13 +00004997 EvalOK = this->Visit(E->getBase());
Richard Smith027bf112011-11-17 22:56:20 +00004998 BaseTy = E->getBase()->getType();
4999 }
George Burgess IV3a03fab2015-09-04 21:28:13 +00005000 if (!EvalOK) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005001 if (!InvalidBaseOK)
George Burgess IV3a03fab2015-09-04 21:28:13 +00005002 return false;
George Burgess IVa51c4072015-10-16 01:49:01 +00005003 Result.setInvalid(E);
5004 return true;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005005 }
Richard Smith027bf112011-11-17 22:56:20 +00005006
Richard Smith1b78b3d2012-01-25 22:15:11 +00005007 const ValueDecl *MD = E->getMemberDecl();
5008 if (const FieldDecl *FD = dyn_cast<FieldDecl>(E->getMemberDecl())) {
5009 assert(BaseTy->getAs<RecordType>()->getDecl()->getCanonicalDecl() ==
5010 FD->getParent()->getCanonicalDecl() && "record / field mismatch");
5011 (void)BaseTy;
John McCalld7bca762012-05-01 00:38:49 +00005012 if (!HandleLValueMember(this->Info, E, Result, FD))
5013 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005014 } else if (const IndirectFieldDecl *IFD = dyn_cast<IndirectFieldDecl>(MD)) {
John McCalld7bca762012-05-01 00:38:49 +00005015 if (!HandleLValueIndirectMember(this->Info, E, Result, IFD))
5016 return false;
Richard Smith1b78b3d2012-01-25 22:15:11 +00005017 } else
5018 return this->Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00005019
Richard Smith1b78b3d2012-01-25 22:15:11 +00005020 if (MD->getType()->isReferenceType()) {
Richard Smith2e312c82012-03-03 22:46:17 +00005021 APValue RefValue;
Richard Smith243ef902013-05-05 23:31:59 +00005022 if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
Richard Smith027bf112011-11-17 22:56:20 +00005023 RefValue))
5024 return false;
5025 return Success(RefValue, E);
5026 }
5027 return true;
5028 }
5029
5030 bool VisitBinaryOperator(const BinaryOperator *E) {
5031 switch (E->getOpcode()) {
5032 default:
5033 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
5034
5035 case BO_PtrMemD:
5036 case BO_PtrMemI:
5037 return HandleMemberPointerAccess(this->Info, E, Result);
5038 }
5039 }
5040
5041 bool VisitCastExpr(const CastExpr *E) {
5042 switch (E->getCastKind()) {
5043 default:
5044 return ExprEvaluatorBaseTy::VisitCastExpr(E);
5045
5046 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005047 case CK_UncheckedDerivedToBase:
Richard Smith027bf112011-11-17 22:56:20 +00005048 if (!this->Visit(E->getSubExpr()))
5049 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005050
5051 // Now figure out the necessary offset to add to the base LV to get from
5052 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005053 return HandleLValueBasePath(this->Info, E, E->getSubExpr()->getType(),
5054 Result);
Richard Smith027bf112011-11-17 22:56:20 +00005055 }
5056 }
5057};
Alexander Kornienkoab9db512015-06-22 23:07:51 +00005058}
Richard Smith027bf112011-11-17 22:56:20 +00005059
5060//===----------------------------------------------------------------------===//
Eli Friedman9a156e52008-11-12 09:44:48 +00005061// LValue Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00005062//
5063// This is used for evaluating lvalues (in C and C++), xvalues (in C++11),
5064// function designators (in C), decl references to void objects (in C), and
5065// temporaries (if building with -Wno-address-of-temporary).
5066//
5067// LValue evaluation produces values comprising a base expression of one of the
5068// following types:
Richard Smithce40ad62011-11-12 22:28:03 +00005069// - Declarations
5070// * VarDecl
5071// * FunctionDecl
5072// - Literals
Richard Smithb3189a12016-12-05 07:49:14 +00005073// * CompoundLiteralExpr in C (and in global scope in C++)
Richard Smith11562c52011-10-28 17:51:58 +00005074// * StringLiteral
Richard Smith6e525142011-12-27 12:18:28 +00005075// * CXXTypeidExpr
Richard Smith11562c52011-10-28 17:51:58 +00005076// * PredefinedExpr
Richard Smithd62306a2011-11-10 06:34:14 +00005077// * ObjCStringLiteralExpr
Richard Smith11562c52011-10-28 17:51:58 +00005078// * ObjCEncodeExpr
5079// * AddrLabelExpr
5080// * BlockExpr
5081// * CallExpr for a MakeStringConstant builtin
Richard Smithce40ad62011-11-12 22:28:03 +00005082// - Locals and temporaries
Richard Smith84401042013-06-03 05:03:02 +00005083// * MaterializeTemporaryExpr
Richard Smithb228a862012-02-15 02:18:13 +00005084// * Any Expr, with a CallIndex indicating the function in which the temporary
Richard Smith84401042013-06-03 05:03:02 +00005085// was evaluated, for cases where the MaterializeTemporaryExpr is missing
5086// from the AST (FIXME).
Richard Smithe6c01442013-06-05 00:46:14 +00005087// * A MaterializeTemporaryExpr that has static storage duration, with no
5088// CallIndex, for a lifetime-extended temporary.
Richard Smithce40ad62011-11-12 22:28:03 +00005089// plus an offset in bytes.
Eli Friedman9a156e52008-11-12 09:44:48 +00005090//===----------------------------------------------------------------------===//
5091namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005092class LValueExprEvaluator
Richard Smith027bf112011-11-17 22:56:20 +00005093 : public LValueExprEvaluatorBase<LValueExprEvaluator> {
Eli Friedman9a156e52008-11-12 09:44:48 +00005094public:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005095 LValueExprEvaluator(EvalInfo &Info, LValue &Result, bool InvalidBaseOK) :
5096 LValueExprEvaluatorBaseTy(Info, Result, InvalidBaseOK) {}
Mike Stump11289f42009-09-09 15:08:12 +00005097
Richard Smith11562c52011-10-28 17:51:58 +00005098 bool VisitVarDecl(const Expr *E, const VarDecl *VD);
Richard Smith243ef902013-05-05 23:31:59 +00005099 bool VisitUnaryPreIncDec(const UnaryOperator *UO);
Richard Smith11562c52011-10-28 17:51:58 +00005100
Peter Collingbournee9200682011-05-13 03:29:01 +00005101 bool VisitDeclRefExpr(const DeclRefExpr *E);
5102 bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005103 bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005104 bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
5105 bool VisitMemberExpr(const MemberExpr *E);
5106 bool VisitStringLiteral(const StringLiteral *E) { return Success(E); }
5107 bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { return Success(E); }
Richard Smith6e525142011-12-27 12:18:28 +00005108 bool VisitCXXTypeidExpr(const CXXTypeidExpr *E);
Francois Pichet0066db92012-04-16 04:08:35 +00005109 bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005110 bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
5111 bool VisitUnaryDeref(const UnaryOperator *E);
Richard Smith66c96992012-02-18 22:04:06 +00005112 bool VisitUnaryReal(const UnaryOperator *E);
5113 bool VisitUnaryImag(const UnaryOperator *E);
Richard Smith243ef902013-05-05 23:31:59 +00005114 bool VisitUnaryPreInc(const UnaryOperator *UO) {
5115 return VisitUnaryPreIncDec(UO);
5116 }
5117 bool VisitUnaryPreDec(const UnaryOperator *UO) {
5118 return VisitUnaryPreIncDec(UO);
5119 }
Richard Smith3229b742013-05-05 21:17:10 +00005120 bool VisitBinAssign(const BinaryOperator *BO);
5121 bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
Anders Carlssonde55f642009-10-03 16:30:22 +00005122
Peter Collingbournee9200682011-05-13 03:29:01 +00005123 bool VisitCastExpr(const CastExpr *E) {
Anders Carlssonde55f642009-10-03 16:30:22 +00005124 switch (E->getCastKind()) {
5125 default:
Richard Smith027bf112011-11-17 22:56:20 +00005126 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
Anders Carlssonde55f642009-10-03 16:30:22 +00005127
Eli Friedmance3e02a2011-10-11 00:13:24 +00005128 case CK_LValueBitCast:
Richard Smith6d6ecc32011-12-12 12:46:16 +00005129 this->CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
Richard Smith96e0c102011-11-04 02:25:55 +00005130 if (!Visit(E->getSubExpr()))
5131 return false;
5132 Result.Designator.setInvalid();
5133 return true;
Eli Friedmance3e02a2011-10-11 00:13:24 +00005134
Richard Smith027bf112011-11-17 22:56:20 +00005135 case CK_BaseToDerived:
Richard Smithd62306a2011-11-10 06:34:14 +00005136 if (!Visit(E->getSubExpr()))
5137 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005138 return HandleBaseToDerivedCast(Info, E, Result);
Anders Carlssonde55f642009-10-03 16:30:22 +00005139 }
5140 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005141};
5142} // end anonymous namespace
5143
Richard Smith11562c52011-10-28 17:51:58 +00005144/// Evaluate an expression as an lvalue. This can be legitimately called on
Nico Weber96775622015-09-15 23:17:17 +00005145/// expressions which are not glvalues, in three cases:
Richard Smith9f8400e2013-05-01 19:00:39 +00005146/// * function designators in C, and
5147/// * "extern void" objects
Nico Weber96775622015-09-15 23:17:17 +00005148/// * @selector() expressions in Objective-C
George Burgess IVf9013bf2017-02-10 22:52:29 +00005149static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info,
5150 bool InvalidBaseOK) {
Richard Smith9f8400e2013-05-01 19:00:39 +00005151 assert(E->isGLValue() || E->getType()->isFunctionType() ||
Nico Weber96775622015-09-15 23:17:17 +00005152 E->getType()->isVoidType() || isa<ObjCSelectorExpr>(E));
George Burgess IVf9013bf2017-02-10 22:52:29 +00005153 return LValueExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005154}
5155
Peter Collingbournee9200682011-05-13 03:29:01 +00005156bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
David Majnemer0c43d802014-06-25 08:15:07 +00005157 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(E->getDecl()))
Richard Smithce40ad62011-11-12 22:28:03 +00005158 return Success(FD);
5159 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getDecl()))
Richard Smith11562c52011-10-28 17:51:58 +00005160 return VisitVarDecl(E, VD);
Richard Smithdca60b42016-08-12 00:39:32 +00005161 if (const BindingDecl *BD = dyn_cast<BindingDecl>(E->getDecl()))
Richard Smith97fcf4b2016-08-14 23:15:52 +00005162 return Visit(BD->getBinding());
Richard Smith11562c52011-10-28 17:51:58 +00005163 return Error(E);
5164}
Richard Smith733237d2011-10-24 23:14:33 +00005165
Faisal Vali0528a312016-11-13 06:09:16 +00005166
Richard Smith11562c52011-10-28 17:51:58 +00005167bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
Faisal Vali051e3a22017-02-16 04:12:21 +00005168
5169 // If we are within a lambda's call operator, check whether the 'VD' referred
5170 // to within 'E' actually represents a lambda-capture that maps to a
5171 // data-member/field within the closure object, and if so, evaluate to the
5172 // field or what the field refers to.
5173 if (Info.CurrentCall && isLambdaCallOperator(Info.CurrentCall->Callee)) {
5174 if (auto *FD = Info.CurrentCall->LambdaCaptureFields.lookup(VD)) {
5175 if (Info.checkingPotentialConstantExpression())
5176 return false;
5177 // Start with 'Result' referring to the complete closure object...
5178 Result = *Info.CurrentCall->This;
5179 // ... then update it to refer to the field of the closure object
5180 // that represents the capture.
5181 if (!HandleLValueMember(Info, E, Result, FD))
5182 return false;
5183 // And if the field is of reference type, update 'Result' to refer to what
5184 // the field refers to.
5185 if (FD->getType()->isReferenceType()) {
5186 APValue RVal;
5187 if (!handleLValueToRValueConversion(Info, E, FD->getType(), Result,
5188 RVal))
5189 return false;
5190 Result.setFrom(Info.Ctx, RVal);
5191 }
5192 return true;
5193 }
5194 }
Craig Topper36250ad2014-05-12 05:36:57 +00005195 CallStackFrame *Frame = nullptr;
Faisal Vali0528a312016-11-13 06:09:16 +00005196 if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1) {
5197 // Only if a local variable was declared in the function currently being
5198 // evaluated, do we expect to be able to find its value in the current
5199 // frame. (Otherwise it was likely declared in an enclosing context and
5200 // could either have a valid evaluatable value (for e.g. a constexpr
5201 // variable) or be ill-formed (and trigger an appropriate evaluation
5202 // diagnostic)).
5203 if (Info.CurrentCall->Callee &&
5204 Info.CurrentCall->Callee->Equals(VD->getDeclContext())) {
5205 Frame = Info.CurrentCall;
5206 }
5207 }
Richard Smith3229b742013-05-05 21:17:10 +00005208
Richard Smithfec09922011-11-01 16:57:24 +00005209 if (!VD->getType()->isReferenceType()) {
Richard Smith3229b742013-05-05 21:17:10 +00005210 if (Frame) {
5211 Result.set(VD, Frame->Index);
Richard Smithfec09922011-11-01 16:57:24 +00005212 return true;
5213 }
Richard Smithce40ad62011-11-12 22:28:03 +00005214 return Success(VD);
Richard Smithfec09922011-11-01 16:57:24 +00005215 }
Eli Friedman751aa72b72009-05-27 06:04:58 +00005216
Richard Smith3229b742013-05-05 21:17:10 +00005217 APValue *V;
5218 if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
Richard Smithf57d8cb2011-12-09 22:58:01 +00005219 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00005220 if (V->isUninit()) {
Richard Smith6d4c6582013-11-05 22:18:15 +00005221 if (!Info.checkingPotentialConstantExpression())
Faisal Valie690b7a2016-07-02 22:34:24 +00005222 Info.FFDiag(E, diag::note_constexpr_use_uninit_reference);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005223 return false;
5224 }
Richard Smith3229b742013-05-05 21:17:10 +00005225 return Success(*V, E);
Anders Carlssona42ee442008-11-24 04:41:22 +00005226}
5227
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005228bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
5229 const MaterializeTemporaryExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005230 // Walk through the expression to find the materialized temporary itself.
5231 SmallVector<const Expr *, 2> CommaLHSs;
5232 SmallVector<SubobjectAdjustment, 2> Adjustments;
5233 const Expr *Inner = E->GetTemporaryExpr()->
5234 skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
Richard Smith027bf112011-11-17 22:56:20 +00005235
Richard Smith84401042013-06-03 05:03:02 +00005236 // If we passed any comma operators, evaluate their LHSs.
5237 for (unsigned I = 0, N = CommaLHSs.size(); I != N; ++I)
5238 if (!EvaluateIgnoredValue(Info, CommaLHSs[I]))
5239 return false;
5240
Richard Smithe6c01442013-06-05 00:46:14 +00005241 // A materialized temporary with static storage duration can appear within the
5242 // result of a constant expression evaluation, so we need to preserve its
5243 // value for use outside this evaluation.
5244 APValue *Value;
5245 if (E->getStorageDuration() == SD_Static) {
5246 Value = Info.Ctx.getMaterializedTemporaryValue(E, true);
Richard Smitha509f2f2013-06-14 03:07:01 +00005247 *Value = APValue();
Richard Smithe6c01442013-06-05 00:46:14 +00005248 Result.set(E);
5249 } else {
Richard Smith08d6a2c2013-07-24 07:11:57 +00005250 Value = &Info.CurrentCall->
5251 createTemporary(E, E->getStorageDuration() == SD_Automatic);
Richard Smithe6c01442013-06-05 00:46:14 +00005252 Result.set(E, Info.CurrentCall->Index);
5253 }
5254
Richard Smithea4ad5d2013-06-06 08:19:16 +00005255 QualType Type = Inner->getType();
5256
Richard Smith84401042013-06-03 05:03:02 +00005257 // Materialize the temporary itself.
Richard Smithea4ad5d2013-06-06 08:19:16 +00005258 if (!EvaluateInPlace(*Value, Info, Result, Inner) ||
5259 (E->getStorageDuration() == SD_Static &&
5260 !CheckConstantExpression(Info, E->getExprLoc(), Type, *Value))) {
5261 *Value = APValue();
Richard Smith84401042013-06-03 05:03:02 +00005262 return false;
Richard Smithea4ad5d2013-06-06 08:19:16 +00005263 }
Richard Smith84401042013-06-03 05:03:02 +00005264
5265 // Adjust our lvalue to refer to the desired subobject.
Richard Smith84401042013-06-03 05:03:02 +00005266 for (unsigned I = Adjustments.size(); I != 0; /**/) {
5267 --I;
5268 switch (Adjustments[I].Kind) {
5269 case SubobjectAdjustment::DerivedToBaseAdjustment:
5270 if (!HandleLValueBasePath(Info, Adjustments[I].DerivedToBase.BasePath,
5271 Type, Result))
5272 return false;
5273 Type = Adjustments[I].DerivedToBase.BasePath->getType();
5274 break;
5275
5276 case SubobjectAdjustment::FieldAdjustment:
5277 if (!HandleLValueMember(Info, E, Result, Adjustments[I].Field))
5278 return false;
5279 Type = Adjustments[I].Field->getType();
5280 break;
5281
5282 case SubobjectAdjustment::MemberPointerAdjustment:
5283 if (!HandleMemberPointerAccess(this->Info, Type, Result,
5284 Adjustments[I].Ptr.RHS))
5285 return false;
5286 Type = Adjustments[I].Ptr.MPT->getPointeeType();
5287 break;
5288 }
5289 }
5290
5291 return true;
Richard Smith4e4c78ff2011-10-31 05:52:43 +00005292}
5293
Peter Collingbournee9200682011-05-13 03:29:01 +00005294bool
5295LValueExprEvaluator::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
Richard Smithb3189a12016-12-05 07:49:14 +00005296 assert((!Info.getLangOpts().CPlusPlus || E->isFileScope()) &&
5297 "lvalue compound literal in c++?");
Richard Smith11562c52011-10-28 17:51:58 +00005298 // Defer visiting the literal until the lvalue-to-rvalue conversion. We can
5299 // only see this when folding in C, so there's no standard to follow here.
John McCall45d55e42010-05-07 21:00:08 +00005300 return Success(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005301}
5302
Richard Smith6e525142011-12-27 12:18:28 +00005303bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
Richard Smith6f3d4352012-10-17 23:52:07 +00005304 if (!E->isPotentiallyEvaluated())
Richard Smith6e525142011-12-27 12:18:28 +00005305 return Success(E);
Richard Smith6f3d4352012-10-17 23:52:07 +00005306
Faisal Valie690b7a2016-07-02 22:34:24 +00005307 Info.FFDiag(E, diag::note_constexpr_typeid_polymorphic)
Richard Smith6f3d4352012-10-17 23:52:07 +00005308 << E->getExprOperand()->getType()
5309 << E->getExprOperand()->getSourceRange();
5310 return false;
Richard Smith6e525142011-12-27 12:18:28 +00005311}
5312
Francois Pichet0066db92012-04-16 04:08:35 +00005313bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
5314 return Success(E);
Richard Smith3229b742013-05-05 21:17:10 +00005315}
Francois Pichet0066db92012-04-16 04:08:35 +00005316
Peter Collingbournee9200682011-05-13 03:29:01 +00005317bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005318 // Handle static data members.
5319 if (const VarDecl *VD = dyn_cast<VarDecl>(E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00005320 VisitIgnoredBaseExpression(E->getBase());
Richard Smith11562c52011-10-28 17:51:58 +00005321 return VisitVarDecl(E, VD);
5322 }
5323
Richard Smith254a73d2011-10-28 22:34:42 +00005324 // Handle static member functions.
5325 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(E->getMemberDecl())) {
5326 if (MD->isStatic()) {
David Majnemere9807b22016-02-26 04:23:19 +00005327 VisitIgnoredBaseExpression(E->getBase());
Richard Smithce40ad62011-11-12 22:28:03 +00005328 return Success(MD);
Richard Smith254a73d2011-10-28 22:34:42 +00005329 }
5330 }
5331
Richard Smithd62306a2011-11-10 06:34:14 +00005332 // Handle non-static data members.
Richard Smith027bf112011-11-17 22:56:20 +00005333 return LValueExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00005334}
5335
Peter Collingbournee9200682011-05-13 03:29:01 +00005336bool LValueExprEvaluator::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00005337 // FIXME: Deal with vectors as array subscript bases.
5338 if (E->getBase()->getType()->isVectorType())
Richard Smithf57d8cb2011-12-09 22:58:01 +00005339 return Error(E);
Richard Smith11562c52011-10-28 17:51:58 +00005340
Nick Lewyckyad888682017-04-27 07:27:36 +00005341 bool Success = true;
5342 if (!evaluatePointer(E->getBase(), Result)) {
5343 if (!Info.noteFailure())
5344 return false;
5345 Success = false;
5346 }
Mike Stump11289f42009-09-09 15:08:12 +00005347
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005348 APSInt Index;
5349 if (!EvaluateInteger(E->getIdx(), Index, Info))
John McCall45d55e42010-05-07 21:00:08 +00005350 return false;
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005351
Nick Lewyckyad888682017-04-27 07:27:36 +00005352 return Success &&
5353 HandleLValueArrayAdjustment(Info, E, Result, E->getType(), Index);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00005354}
Eli Friedman9a156e52008-11-12 09:44:48 +00005355
Peter Collingbournee9200682011-05-13 03:29:01 +00005356bool LValueExprEvaluator::VisitUnaryDeref(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005357 return evaluatePointer(E->getSubExpr(), Result);
Eli Friedman0b8337c2009-02-20 01:57:15 +00005358}
5359
Richard Smith66c96992012-02-18 22:04:06 +00005360bool LValueExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
5361 if (!Visit(E->getSubExpr()))
5362 return false;
5363 // __real is a no-op on scalar lvalues.
5364 if (E->getSubExpr()->getType()->isAnyComplexType())
5365 HandleLValueComplexElement(Info, E, Result, E->getType(), false);
5366 return true;
5367}
5368
5369bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
5370 assert(E->getSubExpr()->getType()->isAnyComplexType() &&
5371 "lvalue __imag__ on scalar?");
5372 if (!Visit(E->getSubExpr()))
5373 return false;
5374 HandleLValueComplexElement(Info, E, Result, E->getType(), true);
5375 return true;
5376}
5377
Richard Smith243ef902013-05-05 23:31:59 +00005378bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005379 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005380 return Error(UO);
5381
5382 if (!this->Visit(UO->getSubExpr()))
5383 return false;
5384
Richard Smith243ef902013-05-05 23:31:59 +00005385 return handleIncDec(
5386 this->Info, UO, Result, UO->getSubExpr()->getType(),
Craig Topper36250ad2014-05-12 05:36:57 +00005387 UO->isIncrementOp(), nullptr);
Richard Smith3229b742013-05-05 21:17:10 +00005388}
5389
5390bool LValueExprEvaluator::VisitCompoundAssignOperator(
5391 const CompoundAssignOperator *CAO) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005392 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith3229b742013-05-05 21:17:10 +00005393 return Error(CAO);
5394
Richard Smith3229b742013-05-05 21:17:10 +00005395 APValue RHS;
Richard Smith243ef902013-05-05 23:31:59 +00005396
5397 // The overall lvalue result is the result of evaluating the LHS.
5398 if (!this->Visit(CAO->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005399 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005400 Evaluate(RHS, this->Info, CAO->getRHS());
5401 return false;
5402 }
5403
Richard Smith3229b742013-05-05 21:17:10 +00005404 if (!Evaluate(RHS, this->Info, CAO->getRHS()))
5405 return false;
5406
Richard Smith43e77732013-05-07 04:50:00 +00005407 return handleCompoundAssignment(
5408 this->Info, CAO,
5409 Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
5410 CAO->getOpForCompoundAssignment(CAO->getOpcode()), RHS);
Richard Smith3229b742013-05-05 21:17:10 +00005411}
5412
5413bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
Aaron Ballmandd69ef32014-08-19 15:55:55 +00005414 if (!Info.getLangOpts().CPlusPlus14 && !Info.keepEvaluatingAfterFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005415 return Error(E);
5416
Richard Smith3229b742013-05-05 21:17:10 +00005417 APValue NewVal;
Richard Smith243ef902013-05-05 23:31:59 +00005418
5419 if (!this->Visit(E->getLHS())) {
George Burgess IVa145e252016-05-25 22:38:36 +00005420 if (Info.noteFailure())
Richard Smith243ef902013-05-05 23:31:59 +00005421 Evaluate(NewVal, this->Info, E->getRHS());
5422 return false;
5423 }
5424
Richard Smith3229b742013-05-05 21:17:10 +00005425 if (!Evaluate(NewVal, this->Info, E->getRHS()))
5426 return false;
Richard Smith243ef902013-05-05 23:31:59 +00005427
5428 return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
Richard Smith3229b742013-05-05 21:17:10 +00005429 NewVal);
5430}
5431
Eli Friedman9a156e52008-11-12 09:44:48 +00005432//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00005433// Pointer Evaluation
5434//===----------------------------------------------------------------------===//
5435
George Burgess IVe3763372016-12-22 02:50:20 +00005436/// \brief Attempts to compute the number of bytes available at the pointer
5437/// returned by a function with the alloc_size attribute. Returns true if we
5438/// were successful. Places an unsigned number into `Result`.
5439///
5440/// This expects the given CallExpr to be a call to a function with an
5441/// alloc_size attribute.
5442static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5443 const CallExpr *Call,
5444 llvm::APInt &Result) {
5445 const AllocSizeAttr *AllocSize = getAllocSizeAttr(Call);
5446
5447 // alloc_size args are 1-indexed, 0 means not present.
5448 assert(AllocSize && AllocSize->getElemSizeParam() != 0);
5449 unsigned SizeArgNo = AllocSize->getElemSizeParam() - 1;
5450 unsigned BitsInSizeT = Ctx.getTypeSize(Ctx.getSizeType());
5451 if (Call->getNumArgs() <= SizeArgNo)
5452 return false;
5453
5454 auto EvaluateAsSizeT = [&](const Expr *E, APSInt &Into) {
5455 if (!E->EvaluateAsInt(Into, Ctx, Expr::SE_AllowSideEffects))
5456 return false;
5457 if (Into.isNegative() || !Into.isIntN(BitsInSizeT))
5458 return false;
5459 Into = Into.zextOrSelf(BitsInSizeT);
5460 return true;
5461 };
5462
5463 APSInt SizeOfElem;
5464 if (!EvaluateAsSizeT(Call->getArg(SizeArgNo), SizeOfElem))
5465 return false;
5466
5467 if (!AllocSize->getNumElemsParam()) {
5468 Result = std::move(SizeOfElem);
5469 return true;
5470 }
5471
5472 APSInt NumberOfElems;
5473 // Argument numbers start at 1
5474 unsigned NumArgNo = AllocSize->getNumElemsParam() - 1;
5475 if (!EvaluateAsSizeT(Call->getArg(NumArgNo), NumberOfElems))
5476 return false;
5477
5478 bool Overflow;
5479 llvm::APInt BytesAvailable = SizeOfElem.umul_ov(NumberOfElems, Overflow);
5480 if (Overflow)
5481 return false;
5482
5483 Result = std::move(BytesAvailable);
5484 return true;
5485}
5486
5487/// \brief Convenience function. LVal's base must be a call to an alloc_size
5488/// function.
5489static bool getBytesReturnedByAllocSizeCall(const ASTContext &Ctx,
5490 const LValue &LVal,
5491 llvm::APInt &Result) {
5492 assert(isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
5493 "Can't get the size of a non alloc_size function");
5494 const auto *Base = LVal.getLValueBase().get<const Expr *>();
5495 const CallExpr *CE = tryUnwrapAllocSizeCall(Base);
5496 return getBytesReturnedByAllocSizeCall(Ctx, CE, Result);
5497}
5498
5499/// \brief Attempts to evaluate the given LValueBase as the result of a call to
5500/// a function with the alloc_size attribute. If it was possible to do so, this
5501/// function will return true, make Result's Base point to said function call,
5502/// and mark Result's Base as invalid.
5503static bool evaluateLValueAsAllocSize(EvalInfo &Info, APValue::LValueBase Base,
5504 LValue &Result) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005505 if (Base.isNull())
George Burgess IVe3763372016-12-22 02:50:20 +00005506 return false;
5507
5508 // Because we do no form of static analysis, we only support const variables.
5509 //
5510 // Additionally, we can't support parameters, nor can we support static
5511 // variables (in the latter case, use-before-assign isn't UB; in the former,
5512 // we have no clue what they'll be assigned to).
5513 const auto *VD =
5514 dyn_cast_or_null<VarDecl>(Base.dyn_cast<const ValueDecl *>());
5515 if (!VD || !VD->isLocalVarDecl() || !VD->getType().isConstQualified())
5516 return false;
5517
5518 const Expr *Init = VD->getAnyInitializer();
5519 if (!Init)
5520 return false;
5521
5522 const Expr *E = Init->IgnoreParens();
5523 if (!tryUnwrapAllocSizeCall(E))
5524 return false;
5525
5526 // Store E instead of E unwrapped so that the type of the LValue's base is
5527 // what the user wanted.
5528 Result.setInvalid(E);
5529
5530 QualType Pointee = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005531 Result.addUnsizedArray(Info, E, Pointee);
George Burgess IVe3763372016-12-22 02:50:20 +00005532 return true;
5533}
5534
Anders Carlsson0a1707c2008-07-08 05:13:58 +00005535namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00005536class PointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00005537 : public ExprEvaluatorBase<PointerExprEvaluator> {
John McCall45d55e42010-05-07 21:00:08 +00005538 LValue &Result;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005539 bool InvalidBaseOK;
John McCall45d55e42010-05-07 21:00:08 +00005540
Peter Collingbournee9200682011-05-13 03:29:01 +00005541 bool Success(const Expr *E) {
Richard Smithce40ad62011-11-12 22:28:03 +00005542 Result.set(E);
John McCall45d55e42010-05-07 21:00:08 +00005543 return true;
5544 }
George Burgess IVe3763372016-12-22 02:50:20 +00005545
George Burgess IVf9013bf2017-02-10 22:52:29 +00005546 bool evaluateLValue(const Expr *E, LValue &Result) {
5547 return EvaluateLValue(E, Result, Info, InvalidBaseOK);
5548 }
5549
5550 bool evaluatePointer(const Expr *E, LValue &Result) {
5551 return EvaluatePointer(E, Result, Info, InvalidBaseOK);
5552 }
5553
George Burgess IVe3763372016-12-22 02:50:20 +00005554 bool visitNonBuiltinCallExpr(const CallExpr *E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005555public:
Mike Stump11289f42009-09-09 15:08:12 +00005556
George Burgess IVf9013bf2017-02-10 22:52:29 +00005557 PointerExprEvaluator(EvalInfo &info, LValue &Result, bool InvalidBaseOK)
5558 : ExprEvaluatorBaseTy(info), Result(Result),
5559 InvalidBaseOK(InvalidBaseOK) {}
Chris Lattner05706e882008-07-11 18:11:29 +00005560
Richard Smith2e312c82012-03-03 22:46:17 +00005561 bool Success(const APValue &V, const Expr *E) {
5562 Result.setFrom(Info.Ctx, V);
Peter Collingbournee9200682011-05-13 03:29:01 +00005563 return true;
5564 }
Richard Smithfddd3842011-12-30 21:15:51 +00005565 bool ZeroInitialization(const Expr *E) {
Tim Northover01503332017-05-26 02:16:00 +00005566 auto TargetVal = Info.Ctx.getTargetNullPointerValue(E->getType());
5567 Result.setNull(E->getType(), TargetVal);
Yaxun Liu402804b2016-12-15 08:09:08 +00005568 return true;
Richard Smith4ce706a2011-10-11 21:43:33 +00005569 }
Anders Carlssonb5ad0212008-07-08 14:30:00 +00005570
John McCall45d55e42010-05-07 21:00:08 +00005571 bool VisitBinaryOperator(const BinaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005572 bool VisitCastExpr(const CastExpr* E);
John McCall45d55e42010-05-07 21:00:08 +00005573 bool VisitUnaryAddrOf(const UnaryOperator *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00005574 bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
John McCall45d55e42010-05-07 21:00:08 +00005575 { return Success(E); }
Nick Lewycky19ae6dc2017-04-29 00:07:27 +00005576 bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
5577 if (Info.noteFailure())
5578 EvaluateIgnoredValue(Info, E->getSubExpr());
5579 return Error(E);
5580 }
Peter Collingbournee9200682011-05-13 03:29:01 +00005581 bool VisitAddrLabelExpr(const AddrLabelExpr *E)
John McCall45d55e42010-05-07 21:00:08 +00005582 { return Success(E); }
Peter Collingbournee9200682011-05-13 03:29:01 +00005583 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005584 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Peter Collingbournee9200682011-05-13 03:29:01 +00005585 bool VisitBlockExpr(const BlockExpr *E) {
John McCallc63de662011-02-02 13:00:07 +00005586 if (!E->getBlockDecl()->hasCaptures())
John McCall45d55e42010-05-07 21:00:08 +00005587 return Success(E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00005588 return Error(E);
Mike Stumpa6703322009-02-19 22:01:56 +00005589 }
Richard Smithd62306a2011-11-10 06:34:14 +00005590 bool VisitCXXThisExpr(const CXXThisExpr *E) {
Richard Smith84401042013-06-03 05:03:02 +00005591 // Can't look at 'this' when checking a potential constant expression.
Richard Smith6d4c6582013-11-05 22:18:15 +00005592 if (Info.checkingPotentialConstantExpression())
Richard Smith84401042013-06-03 05:03:02 +00005593 return false;
Richard Smith22a5d612014-07-07 06:00:13 +00005594 if (!Info.CurrentCall->This) {
5595 if (Info.getLangOpts().CPlusPlus11)
Faisal Valie690b7a2016-07-02 22:34:24 +00005596 Info.FFDiag(E, diag::note_constexpr_this) << E->isImplicit();
Richard Smith22a5d612014-07-07 06:00:13 +00005597 else
Faisal Valie690b7a2016-07-02 22:34:24 +00005598 Info.FFDiag(E);
Richard Smith22a5d612014-07-07 06:00:13 +00005599 return false;
5600 }
Richard Smithd62306a2011-11-10 06:34:14 +00005601 Result = *Info.CurrentCall->This;
Faisal Vali051e3a22017-02-16 04:12:21 +00005602 // If we are inside a lambda's call operator, the 'this' expression refers
5603 // to the enclosing '*this' object (either by value or reference) which is
5604 // either copied into the closure object's field that represents the '*this'
5605 // or refers to '*this'.
5606 if (isLambdaCallOperator(Info.CurrentCall->Callee)) {
5607 // Update 'Result' to refer to the data member/field of the closure object
5608 // that represents the '*this' capture.
5609 if (!HandleLValueMember(Info, E, Result,
Daniel Jasperffdee092017-05-02 19:21:42 +00005610 Info.CurrentCall->LambdaThisCaptureField))
Faisal Vali051e3a22017-02-16 04:12:21 +00005611 return false;
5612 // If we captured '*this' by reference, replace the field with its referent.
5613 if (Info.CurrentCall->LambdaThisCaptureField->getType()
5614 ->isPointerType()) {
5615 APValue RVal;
5616 if (!handleLValueToRValueConversion(Info, E, E->getType(), Result,
5617 RVal))
5618 return false;
5619
5620 Result.setFrom(Info.Ctx, RVal);
5621 }
5622 }
Richard Smithd62306a2011-11-10 06:34:14 +00005623 return true;
5624 }
John McCallc07a0c72011-02-17 10:25:35 +00005625
Eli Friedman449fe542009-03-23 04:56:01 +00005626 // FIXME: Missing: @protocol, @selector
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005627};
Chris Lattner05706e882008-07-11 18:11:29 +00005628} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00005629
George Burgess IVf9013bf2017-02-10 22:52:29 +00005630static bool EvaluatePointer(const Expr* E, LValue& Result, EvalInfo &Info,
5631 bool InvalidBaseOK) {
Richard Smith11562c52011-10-28 17:51:58 +00005632 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
George Burgess IVf9013bf2017-02-10 22:52:29 +00005633 return PointerExprEvaluator(Info, Result, InvalidBaseOK).Visit(E);
Chris Lattner05706e882008-07-11 18:11:29 +00005634}
5635
John McCall45d55e42010-05-07 21:00:08 +00005636bool PointerExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
John McCalle3027922010-08-25 11:45:40 +00005637 if (E->getOpcode() != BO_Add &&
5638 E->getOpcode() != BO_Sub)
Richard Smith027bf112011-11-17 22:56:20 +00005639 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Mike Stump11289f42009-09-09 15:08:12 +00005640
Chris Lattner05706e882008-07-11 18:11:29 +00005641 const Expr *PExp = E->getLHS();
5642 const Expr *IExp = E->getRHS();
5643 if (IExp->getType()->isPointerType())
5644 std::swap(PExp, IExp);
Mike Stump11289f42009-09-09 15:08:12 +00005645
George Burgess IVf9013bf2017-02-10 22:52:29 +00005646 bool EvalPtrOK = evaluatePointer(PExp, Result);
George Burgess IVa145e252016-05-25 22:38:36 +00005647 if (!EvalPtrOK && !Info.noteFailure())
John McCall45d55e42010-05-07 21:00:08 +00005648 return false;
Mike Stump11289f42009-09-09 15:08:12 +00005649
John McCall45d55e42010-05-07 21:00:08 +00005650 llvm::APSInt Offset;
Richard Smith253c2a32012-01-27 01:14:48 +00005651 if (!EvaluateInteger(IExp, Offset, Info) || !EvalPtrOK)
John McCall45d55e42010-05-07 21:00:08 +00005652 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00005653
Richard Smith96e0c102011-11-04 02:25:55 +00005654 if (E->getOpcode() == BO_Sub)
Richard Smithd6cc1982017-01-31 02:23:02 +00005655 negateAsSigned(Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005656
Ted Kremenek28831752012-08-23 20:46:57 +00005657 QualType Pointee = PExp->getType()->castAs<PointerType>()->getPointeeType();
Richard Smithd6cc1982017-01-31 02:23:02 +00005658 return HandleLValueArrayAdjustment(Info, E, Result, Pointee, Offset);
Chris Lattner05706e882008-07-11 18:11:29 +00005659}
Eli Friedman9a156e52008-11-12 09:44:48 +00005660
John McCall45d55e42010-05-07 21:00:08 +00005661bool PointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005662 return evaluateLValue(E->getSubExpr(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00005663}
Mike Stump11289f42009-09-09 15:08:12 +00005664
Peter Collingbournee9200682011-05-13 03:29:01 +00005665bool PointerExprEvaluator::VisitCastExpr(const CastExpr* E) {
5666 const Expr* SubExpr = E->getSubExpr();
Chris Lattner05706e882008-07-11 18:11:29 +00005667
Eli Friedman847a2bc2009-12-27 05:43:15 +00005668 switch (E->getCastKind()) {
5669 default:
5670 break;
5671
John McCalle3027922010-08-25 11:45:40 +00005672 case CK_BitCast:
John McCall9320b872011-09-09 05:25:32 +00005673 case CK_CPointerToObjCPointerCast:
5674 case CK_BlockPointerToObjCPointerCast:
John McCalle3027922010-08-25 11:45:40 +00005675 case CK_AnyPointerToBlockPointerCast:
Anastasia Stulova5d8ad8a2014-11-26 15:36:41 +00005676 case CK_AddressSpaceConversion:
Richard Smithb19ac0d2012-01-15 03:25:41 +00005677 if (!Visit(SubExpr))
5678 return false;
Richard Smith6d6ecc32011-12-12 12:46:16 +00005679 // Bitcasts to cv void* are static_casts, not reinterpret_casts, so are
5680 // permitted in constant expressions in C++11. Bitcasts from cv void* are
5681 // also static_casts, but we disallow them as a resolution to DR1312.
Richard Smithff07af12011-12-12 19:10:03 +00005682 if (!E->getType()->isVoidPointerType()) {
Richard Smithb19ac0d2012-01-15 03:25:41 +00005683 Result.Designator.setInvalid();
Richard Smithff07af12011-12-12 19:10:03 +00005684 if (SubExpr->getType()->isVoidPointerType())
5685 CCEDiag(E, diag::note_constexpr_invalid_cast)
5686 << 3 << SubExpr->getType();
5687 else
5688 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5689 }
Yaxun Liu402804b2016-12-15 08:09:08 +00005690 if (E->getCastKind() == CK_AddressSpaceConversion && Result.IsNullPtr)
5691 ZeroInitialization(E);
Richard Smith96e0c102011-11-04 02:25:55 +00005692 return true;
Eli Friedman847a2bc2009-12-27 05:43:15 +00005693
Anders Carlsson18275092010-10-31 20:41:46 +00005694 case CK_DerivedToBase:
Richard Smith84401042013-06-03 05:03:02 +00005695 case CK_UncheckedDerivedToBase:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005696 if (!evaluatePointer(E->getSubExpr(), Result))
Anders Carlsson18275092010-10-31 20:41:46 +00005697 return false;
Richard Smith027bf112011-11-17 22:56:20 +00005698 if (!Result.Base && Result.Offset.isZero())
5699 return true;
Anders Carlsson18275092010-10-31 20:41:46 +00005700
Richard Smithd62306a2011-11-10 06:34:14 +00005701 // Now figure out the necessary offset to add to the base LV to get from
Anders Carlsson18275092010-10-31 20:41:46 +00005702 // the derived class to the base class.
Richard Smith84401042013-06-03 05:03:02 +00005703 return HandleLValueBasePath(Info, E, E->getSubExpr()->getType()->
5704 castAs<PointerType>()->getPointeeType(),
5705 Result);
Anders Carlsson18275092010-10-31 20:41:46 +00005706
Richard Smith027bf112011-11-17 22:56:20 +00005707 case CK_BaseToDerived:
5708 if (!Visit(E->getSubExpr()))
5709 return false;
5710 if (!Result.Base && Result.Offset.isZero())
5711 return true;
5712 return HandleBaseToDerivedCast(Info, E, Result);
5713
Richard Smith0b0a0b62011-10-29 20:57:55 +00005714 case CK_NullToPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00005715 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00005716 return ZeroInitialization(E);
John McCalle84af4e2010-11-13 01:35:44 +00005717
John McCalle3027922010-08-25 11:45:40 +00005718 case CK_IntegralToPointer: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00005719 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
5720
Richard Smith2e312c82012-03-03 22:46:17 +00005721 APValue Value;
John McCall45d55e42010-05-07 21:00:08 +00005722 if (!EvaluateIntegerOrLValue(SubExpr, Value, Info))
Eli Friedman847a2bc2009-12-27 05:43:15 +00005723 break;
Daniel Dunbarce399542009-02-20 18:22:23 +00005724
John McCall45d55e42010-05-07 21:00:08 +00005725 if (Value.isInt()) {
Richard Smith0b0a0b62011-10-29 20:57:55 +00005726 unsigned Size = Info.Ctx.getTypeSize(E->getType());
5727 uint64_t N = Value.getInt().extOrTrunc(Size).getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00005728 Result.Base = (Expr*)nullptr;
George Burgess IV3a03fab2015-09-04 21:28:13 +00005729 Result.InvalidBase = false;
Richard Smith0b0a0b62011-10-29 20:57:55 +00005730 Result.Offset = CharUnits::fromQuantity(N);
Richard Smithb228a862012-02-15 02:18:13 +00005731 Result.CallIndex = 0;
Richard Smith96e0c102011-11-04 02:25:55 +00005732 Result.Designator.setInvalid();
Yaxun Liu402804b2016-12-15 08:09:08 +00005733 Result.IsNullPtr = false;
John McCall45d55e42010-05-07 21:00:08 +00005734 return true;
5735 } else {
5736 // Cast is of an lvalue, no need to change value.
Richard Smith2e312c82012-03-03 22:46:17 +00005737 Result.setFrom(Info.Ctx, Value);
John McCall45d55e42010-05-07 21:00:08 +00005738 return true;
Chris Lattner05706e882008-07-11 18:11:29 +00005739 }
5740 }
Richard Smith6f4f0f12017-10-20 22:56:25 +00005741
5742 case CK_ArrayToPointerDecay: {
Richard Smith027bf112011-11-17 22:56:20 +00005743 if (SubExpr->isGLValue()) {
George Burgess IVf9013bf2017-02-10 22:52:29 +00005744 if (!evaluateLValue(SubExpr, Result))
Richard Smith027bf112011-11-17 22:56:20 +00005745 return false;
5746 } else {
Richard Smithb228a862012-02-15 02:18:13 +00005747 Result.set(SubExpr, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00005748 if (!EvaluateInPlace(Info.CurrentCall->createTemporary(SubExpr, false),
Richard Smithb228a862012-02-15 02:18:13 +00005749 Info, Result, SubExpr))
Richard Smith027bf112011-11-17 22:56:20 +00005750 return false;
5751 }
Richard Smith96e0c102011-11-04 02:25:55 +00005752 // The result is a pointer to the first element of the array.
Richard Smith6f4f0f12017-10-20 22:56:25 +00005753 auto *AT = Info.Ctx.getAsArrayType(SubExpr->getType());
5754 if (auto *CAT = dyn_cast<ConstantArrayType>(AT))
Richard Smitha8105bc2012-01-06 16:39:00 +00005755 Result.addArray(Info, E, CAT);
Daniel Jasperffdee092017-05-02 19:21:42 +00005756 else
Richard Smith6f4f0f12017-10-20 22:56:25 +00005757 Result.addUnsizedArray(Info, E, AT->getElementType());
Richard Smith96e0c102011-11-04 02:25:55 +00005758 return true;
Richard Smith6f4f0f12017-10-20 22:56:25 +00005759 }
Richard Smithdd785442011-10-31 20:57:44 +00005760
John McCalle3027922010-08-25 11:45:40 +00005761 case CK_FunctionToPointerDecay:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005762 return evaluateLValue(SubExpr, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005763
5764 case CK_LValueToRValue: {
5765 LValue LVal;
George Burgess IVf9013bf2017-02-10 22:52:29 +00005766 if (!evaluateLValue(E->getSubExpr(), LVal))
George Burgess IVe3763372016-12-22 02:50:20 +00005767 return false;
5768
5769 APValue RVal;
5770 // Note, we use the subexpression's type in order to retain cv-qualifiers.
5771 if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
5772 LVal, RVal))
George Burgess IVf9013bf2017-02-10 22:52:29 +00005773 return InvalidBaseOK &&
5774 evaluateLValueAsAllocSize(Info, LVal.Base, Result);
George Burgess IVe3763372016-12-22 02:50:20 +00005775 return Success(RVal, E);
5776 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005777 }
5778
Richard Smith11562c52011-10-28 17:51:58 +00005779 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Mike Stump11289f42009-09-09 15:08:12 +00005780}
Chris Lattner05706e882008-07-11 18:11:29 +00005781
Hal Finkel0dd05d42014-10-03 17:18:37 +00005782static CharUnits GetAlignOfType(EvalInfo &Info, QualType T) {
5783 // C++ [expr.alignof]p3:
5784 // When alignof is applied to a reference type, the result is the
5785 // alignment of the referenced type.
5786 if (const ReferenceType *Ref = T->getAs<ReferenceType>())
5787 T = Ref->getPointeeType();
5788
5789 // __alignof is defined to return the preferred alignment.
Roger Ferrer Ibanez3fa38a12017-03-08 14:00:44 +00005790 if (T.getQualifiers().hasUnaligned())
5791 return CharUnits::One();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005792 return Info.Ctx.toCharUnitsFromBits(
5793 Info.Ctx.getPreferredTypeAlign(T.getTypePtr()));
5794}
5795
5796static CharUnits GetAlignOfExpr(EvalInfo &Info, const Expr *E) {
5797 E = E->IgnoreParens();
5798
5799 // The kinds of expressions that we have special-case logic here for
5800 // should be kept up to date with the special checks for those
5801 // expressions in Sema.
5802
5803 // alignof decl is always accepted, even if it doesn't make sense: we default
5804 // to 1 in those cases.
5805 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
5806 return Info.Ctx.getDeclAlign(DRE->getDecl(),
5807 /*RefAsPointee*/true);
5808
5809 if (const MemberExpr *ME = dyn_cast<MemberExpr>(E))
5810 return Info.Ctx.getDeclAlign(ME->getMemberDecl(),
5811 /*RefAsPointee*/true);
5812
5813 return GetAlignOfType(Info, E->getType());
5814}
5815
George Burgess IVe3763372016-12-22 02:50:20 +00005816// To be clear: this happily visits unsupported builtins. Better name welcomed.
5817bool PointerExprEvaluator::visitNonBuiltinCallExpr(const CallExpr *E) {
5818 if (ExprEvaluatorBaseTy::VisitCallExpr(E))
5819 return true;
5820
George Burgess IVf9013bf2017-02-10 22:52:29 +00005821 if (!(InvalidBaseOK && getAllocSizeAttr(E)))
George Burgess IVe3763372016-12-22 02:50:20 +00005822 return false;
5823
5824 Result.setInvalid(E);
5825 QualType PointeeTy = E->getType()->castAs<PointerType>()->getPointeeType();
Richard Smith6f4f0f12017-10-20 22:56:25 +00005826 Result.addUnsizedArray(Info, E, PointeeTy);
George Burgess IVe3763372016-12-22 02:50:20 +00005827 return true;
5828}
5829
Peter Collingbournee9200682011-05-13 03:29:01 +00005830bool PointerExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00005831 if (IsStringLiteralCall(E))
John McCall45d55e42010-05-07 21:00:08 +00005832 return Success(E);
Eli Friedmanc69d4542009-01-25 01:54:01 +00005833
Richard Smith6328cbd2016-11-16 00:57:23 +00005834 if (unsigned BuiltinOp = E->getBuiltinCallee())
5835 return VisitBuiltinCallExpr(E, BuiltinOp);
5836
George Burgess IVe3763372016-12-22 02:50:20 +00005837 return visitNonBuiltinCallExpr(E);
Richard Smith6328cbd2016-11-16 00:57:23 +00005838}
5839
5840bool PointerExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
5841 unsigned BuiltinOp) {
5842 switch (BuiltinOp) {
Richard Smith6cbd65d2013-07-11 02:27:57 +00005843 case Builtin::BI__builtin_addressof:
George Burgess IVf9013bf2017-02-10 22:52:29 +00005844 return evaluateLValue(E->getArg(0), Result);
Hal Finkel0dd05d42014-10-03 17:18:37 +00005845 case Builtin::BI__builtin_assume_aligned: {
5846 // We need to be very careful here because: if the pointer does not have the
5847 // asserted alignment, then the behavior is undefined, and undefined
5848 // behavior is non-constant.
George Burgess IVf9013bf2017-02-10 22:52:29 +00005849 if (!evaluatePointer(E->getArg(0), Result))
Hal Finkel0dd05d42014-10-03 17:18:37 +00005850 return false;
Richard Smith6cbd65d2013-07-11 02:27:57 +00005851
Hal Finkel0dd05d42014-10-03 17:18:37 +00005852 LValue OffsetResult(Result);
5853 APSInt Alignment;
5854 if (!EvaluateInteger(E->getArg(1), Alignment, Info))
5855 return false;
Richard Smith642a2362017-01-30 23:30:26 +00005856 CharUnits Align = CharUnits::fromQuantity(Alignment.getZExtValue());
Hal Finkel0dd05d42014-10-03 17:18:37 +00005857
5858 if (E->getNumArgs() > 2) {
5859 APSInt Offset;
5860 if (!EvaluateInteger(E->getArg(2), Offset, Info))
5861 return false;
5862
Richard Smith642a2362017-01-30 23:30:26 +00005863 int64_t AdditionalOffset = -Offset.getZExtValue();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005864 OffsetResult.Offset += CharUnits::fromQuantity(AdditionalOffset);
5865 }
5866
5867 // If there is a base object, then it must have the correct alignment.
5868 if (OffsetResult.Base) {
5869 CharUnits BaseAlignment;
5870 if (const ValueDecl *VD =
5871 OffsetResult.Base.dyn_cast<const ValueDecl*>()) {
5872 BaseAlignment = Info.Ctx.getDeclAlign(VD);
5873 } else {
5874 BaseAlignment =
5875 GetAlignOfExpr(Info, OffsetResult.Base.get<const Expr*>());
5876 }
5877
5878 if (BaseAlignment < Align) {
5879 Result.Designator.setInvalid();
Richard Smith642a2362017-01-30 23:30:26 +00005880 // FIXME: Add support to Diagnostic for long / long long.
Hal Finkel0dd05d42014-10-03 17:18:37 +00005881 CCEDiag(E->getArg(0),
5882 diag::note_constexpr_baa_insufficient_alignment) << 0
Richard Smith642a2362017-01-30 23:30:26 +00005883 << (unsigned)BaseAlignment.getQuantity()
5884 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005885 return false;
5886 }
5887 }
5888
5889 // The offset must also have the correct alignment.
Rui Ueyama83aa9792016-01-14 21:00:27 +00005890 if (OffsetResult.Offset.alignTo(Align) != OffsetResult.Offset) {
Hal Finkel0dd05d42014-10-03 17:18:37 +00005891 Result.Designator.setInvalid();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005892
Richard Smith642a2362017-01-30 23:30:26 +00005893 (OffsetResult.Base
5894 ? CCEDiag(E->getArg(0),
5895 diag::note_constexpr_baa_insufficient_alignment) << 1
5896 : CCEDiag(E->getArg(0),
5897 diag::note_constexpr_baa_value_insufficient_alignment))
5898 << (int)OffsetResult.Offset.getQuantity()
5899 << (unsigned)Align.getQuantity();
Hal Finkel0dd05d42014-10-03 17:18:37 +00005900 return false;
5901 }
5902
5903 return true;
5904 }
Richard Smithe9507952016-11-12 01:39:56 +00005905
5906 case Builtin::BIstrchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005907 case Builtin::BIwcschr:
Richard Smithe9507952016-11-12 01:39:56 +00005908 case Builtin::BImemchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005909 case Builtin::BIwmemchr:
Richard Smithe9507952016-11-12 01:39:56 +00005910 if (Info.getLangOpts().CPlusPlus11)
5911 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
5912 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00005913 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe9507952016-11-12 01:39:56 +00005914 else
5915 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
5916 // Fall through.
5917 case Builtin::BI__builtin_strchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005918 case Builtin::BI__builtin_wcschr:
5919 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005920 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005921 case Builtin::BI__builtin_wmemchr: {
Richard Smithe9507952016-11-12 01:39:56 +00005922 if (!Visit(E->getArg(0)))
5923 return false;
5924 APSInt Desired;
5925 if (!EvaluateInteger(E->getArg(1), Desired, Info))
5926 return false;
5927 uint64_t MaxLength = uint64_t(-1);
5928 if (BuiltinOp != Builtin::BIstrchr &&
Richard Smith8110c9d2016-11-29 19:45:17 +00005929 BuiltinOp != Builtin::BIwcschr &&
5930 BuiltinOp != Builtin::BI__builtin_strchr &&
5931 BuiltinOp != Builtin::BI__builtin_wcschr) {
Richard Smithe9507952016-11-12 01:39:56 +00005932 APSInt N;
5933 if (!EvaluateInteger(E->getArg(2), N, Info))
5934 return false;
5935 MaxLength = N.getExtValue();
5936 }
5937
Richard Smith8110c9d2016-11-29 19:45:17 +00005938 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
Richard Smithe9507952016-11-12 01:39:56 +00005939
Richard Smith8110c9d2016-11-29 19:45:17 +00005940 // Figure out what value we're actually looking for (after converting to
5941 // the corresponding unsigned type if necessary).
5942 uint64_t DesiredVal;
5943 bool StopAtNull = false;
5944 switch (BuiltinOp) {
5945 case Builtin::BIstrchr:
5946 case Builtin::BI__builtin_strchr:
5947 // strchr compares directly to the passed integer, and therefore
5948 // always fails if given an int that is not a char.
5949 if (!APSInt::isSameValue(HandleIntToIntCast(Info, E, CharTy,
5950 E->getArg(1)->getType(),
5951 Desired),
5952 Desired))
5953 return ZeroInitialization(E);
5954 StopAtNull = true;
5955 // Fall through.
5956 case Builtin::BImemchr:
5957 case Builtin::BI__builtin_memchr:
Richard Smith5e29dd32017-01-20 00:45:35 +00005958 case Builtin::BI__builtin_char_memchr:
Richard Smith8110c9d2016-11-29 19:45:17 +00005959 // memchr compares by converting both sides to unsigned char. That's also
5960 // correct for strchr if we get this far (to cope with plain char being
5961 // unsigned in the strchr case).
5962 DesiredVal = Desired.trunc(Info.Ctx.getCharWidth()).getZExtValue();
5963 break;
Richard Smithe9507952016-11-12 01:39:56 +00005964
Richard Smith8110c9d2016-11-29 19:45:17 +00005965 case Builtin::BIwcschr:
5966 case Builtin::BI__builtin_wcschr:
5967 StopAtNull = true;
5968 // Fall through.
5969 case Builtin::BIwmemchr:
5970 case Builtin::BI__builtin_wmemchr:
5971 // wcschr and wmemchr are given a wchar_t to look for. Just use it.
5972 DesiredVal = Desired.getZExtValue();
5973 break;
5974 }
Richard Smithe9507952016-11-12 01:39:56 +00005975
5976 for (; MaxLength; --MaxLength) {
5977 APValue Char;
5978 if (!handleLValueToRValueConversion(Info, E, CharTy, Result, Char) ||
5979 !Char.isInt())
5980 return false;
5981 if (Char.getInt().getZExtValue() == DesiredVal)
5982 return true;
Richard Smith8110c9d2016-11-29 19:45:17 +00005983 if (StopAtNull && !Char.getInt())
Richard Smithe9507952016-11-12 01:39:56 +00005984 break;
5985 if (!HandleLValueArrayAdjustment(Info, E, Result, CharTy, 1))
5986 return false;
5987 }
5988 // Not found: return nullptr.
5989 return ZeroInitialization(E);
5990 }
5991
Richard Smith6cbd65d2013-07-11 02:27:57 +00005992 default:
George Burgess IVe3763372016-12-22 02:50:20 +00005993 return visitNonBuiltinCallExpr(E);
Richard Smith6cbd65d2013-07-11 02:27:57 +00005994 }
Eli Friedman9a156e52008-11-12 09:44:48 +00005995}
Chris Lattner05706e882008-07-11 18:11:29 +00005996
5997//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00005998// Member Pointer Evaluation
5999//===----------------------------------------------------------------------===//
6000
6001namespace {
6002class MemberPointerExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006003 : public ExprEvaluatorBase<MemberPointerExprEvaluator> {
Richard Smith027bf112011-11-17 22:56:20 +00006004 MemberPtr &Result;
6005
6006 bool Success(const ValueDecl *D) {
6007 Result = MemberPtr(D);
6008 return true;
6009 }
6010public:
6011
6012 MemberPointerExprEvaluator(EvalInfo &Info, MemberPtr &Result)
6013 : ExprEvaluatorBaseTy(Info), Result(Result) {}
6014
Richard Smith2e312c82012-03-03 22:46:17 +00006015 bool Success(const APValue &V, const Expr *E) {
Richard Smith027bf112011-11-17 22:56:20 +00006016 Result.setFrom(V);
6017 return true;
6018 }
Richard Smithfddd3842011-12-30 21:15:51 +00006019 bool ZeroInitialization(const Expr *E) {
Craig Topper36250ad2014-05-12 05:36:57 +00006020 return Success((const ValueDecl*)nullptr);
Richard Smith027bf112011-11-17 22:56:20 +00006021 }
6022
6023 bool VisitCastExpr(const CastExpr *E);
6024 bool VisitUnaryAddrOf(const UnaryOperator *E);
6025};
6026} // end anonymous namespace
6027
6028static bool EvaluateMemberPointer(const Expr *E, MemberPtr &Result,
6029 EvalInfo &Info) {
6030 assert(E->isRValue() && E->getType()->isMemberPointerType());
6031 return MemberPointerExprEvaluator(Info, Result).Visit(E);
6032}
6033
6034bool MemberPointerExprEvaluator::VisitCastExpr(const CastExpr *E) {
6035 switch (E->getCastKind()) {
6036 default:
6037 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6038
6039 case CK_NullToMemberPointer:
Richard Smith4051ff72012-04-08 08:02:07 +00006040 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006041 return ZeroInitialization(E);
Richard Smith027bf112011-11-17 22:56:20 +00006042
6043 case CK_BaseToDerivedMemberPointer: {
6044 if (!Visit(E->getSubExpr()))
6045 return false;
6046 if (E->path_empty())
6047 return true;
6048 // Base-to-derived member pointer casts store the path in derived-to-base
6049 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
6050 // the wrong end of the derived->base arc, so stagger the path by one class.
6051 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
6052 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
6053 PathI != PathE; ++PathI) {
6054 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6055 const CXXRecordDecl *Derived = (*PathI)->getType()->getAsCXXRecordDecl();
6056 if (!Result.castToDerived(Derived))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006057 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006058 }
6059 const Type *FinalTy = E->getType()->castAs<MemberPointerType>()->getClass();
6060 if (!Result.castToDerived(FinalTy->getAsCXXRecordDecl()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006061 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006062 return true;
6063 }
6064
6065 case CK_DerivedToBaseMemberPointer:
6066 if (!Visit(E->getSubExpr()))
6067 return false;
6068 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6069 PathE = E->path_end(); PathI != PathE; ++PathI) {
6070 assert(!(*PathI)->isVirtual() && "memptr cast through vbase");
6071 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6072 if (!Result.castToBase(Base))
Richard Smithf57d8cb2011-12-09 22:58:01 +00006073 return Error(E);
Richard Smith027bf112011-11-17 22:56:20 +00006074 }
6075 return true;
6076 }
6077}
6078
6079bool MemberPointerExprEvaluator::VisitUnaryAddrOf(const UnaryOperator *E) {
6080 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
6081 // member can be formed.
6082 return Success(cast<DeclRefExpr>(E->getSubExpr())->getDecl());
6083}
6084
6085//===----------------------------------------------------------------------===//
Richard Smithd62306a2011-11-10 06:34:14 +00006086// Record Evaluation
6087//===----------------------------------------------------------------------===//
6088
6089namespace {
6090 class RecordExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006091 : public ExprEvaluatorBase<RecordExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006092 const LValue &This;
6093 APValue &Result;
6094 public:
6095
6096 RecordExprEvaluator(EvalInfo &info, const LValue &This, APValue &Result)
6097 : ExprEvaluatorBaseTy(info), This(This), Result(Result) {}
6098
Richard Smith2e312c82012-03-03 22:46:17 +00006099 bool Success(const APValue &V, const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006100 Result = V;
6101 return true;
Richard Smithd62306a2011-11-10 06:34:14 +00006102 }
Richard Smithb8348f52016-05-12 22:16:28 +00006103 bool ZeroInitialization(const Expr *E) {
6104 return ZeroInitialization(E, E->getType());
6105 }
6106 bool ZeroInitialization(const Expr *E, QualType T);
Richard Smithd62306a2011-11-10 06:34:14 +00006107
Richard Smith52a980a2015-08-28 02:43:42 +00006108 bool VisitCallExpr(const CallExpr *E) {
6109 return handleCallExpr(E, Result, &This);
6110 }
Richard Smithe97cbd72011-11-11 04:05:33 +00006111 bool VisitCastExpr(const CastExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006112 bool VisitInitListExpr(const InitListExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006113 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6114 return VisitCXXConstructExpr(E, E->getType());
6115 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006116 bool VisitLambdaExpr(const LambdaExpr *E);
Richard Smith5179eb72016-06-28 19:03:57 +00006117 bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
Richard Smithb8348f52016-05-12 22:16:28 +00006118 bool VisitCXXConstructExpr(const CXXConstructExpr *E, QualType T);
Richard Smithcc1b96d2013-06-12 22:31:48 +00006119 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
Richard Smithd62306a2011-11-10 06:34:14 +00006120 };
Alexander Kornienkoab9db512015-06-22 23:07:51 +00006121}
Richard Smithd62306a2011-11-10 06:34:14 +00006122
Richard Smithfddd3842011-12-30 21:15:51 +00006123/// Perform zero-initialization on an object of non-union class type.
6124/// C++11 [dcl.init]p5:
6125/// To zero-initialize an object or reference of type T means:
6126/// [...]
6127/// -- if T is a (possibly cv-qualified) non-union class type,
6128/// each non-static data member and each base-class subobject is
6129/// zero-initialized
Richard Smitha8105bc2012-01-06 16:39:00 +00006130static bool HandleClassZeroInitialization(EvalInfo &Info, const Expr *E,
6131 const RecordDecl *RD,
Richard Smithfddd3842011-12-30 21:15:51 +00006132 const LValue &This, APValue &Result) {
6133 assert(!RD->isUnion() && "Expected non-union class type");
6134 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD);
6135 Result = APValue(APValue::UninitStruct(), CD ? CD->getNumBases() : 0,
Aaron Ballman62e47c42014-03-10 13:43:55 +00006136 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithfddd3842011-12-30 21:15:51 +00006137
John McCalld7bca762012-05-01 00:38:49 +00006138 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006139 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6140
6141 if (CD) {
6142 unsigned Index = 0;
6143 for (CXXRecordDecl::base_class_const_iterator I = CD->bases_begin(),
Richard Smitha8105bc2012-01-06 16:39:00 +00006144 End = CD->bases_end(); I != End; ++I, ++Index) {
Richard Smithfddd3842011-12-30 21:15:51 +00006145 const CXXRecordDecl *Base = I->getType()->getAsCXXRecordDecl();
6146 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006147 if (!HandleLValueDirectBase(Info, E, Subobject, CD, Base, &Layout))
6148 return false;
Richard Smitha8105bc2012-01-06 16:39:00 +00006149 if (!HandleClassZeroInitialization(Info, E, Base, Subobject,
Richard Smithfddd3842011-12-30 21:15:51 +00006150 Result.getStructBase(Index)))
6151 return false;
6152 }
6153 }
6154
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006155 for (const auto *I : RD->fields()) {
Richard Smithfddd3842011-12-30 21:15:51 +00006156 // -- if T is a reference type, no initialization is performed.
David Blaikie2d7c57e2012-04-30 02:36:29 +00006157 if (I->getType()->isReferenceType())
Richard Smithfddd3842011-12-30 21:15:51 +00006158 continue;
6159
6160 LValue Subobject = This;
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006161 if (!HandleLValueMember(Info, E, Subobject, I, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006162 return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006163
David Blaikie2d7c57e2012-04-30 02:36:29 +00006164 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006165 if (!EvaluateInPlace(
David Blaikie2d7c57e2012-04-30 02:36:29 +00006166 Result.getStructField(I->getFieldIndex()), Info, Subobject, &VIE))
Richard Smithfddd3842011-12-30 21:15:51 +00006167 return false;
6168 }
6169
6170 return true;
6171}
6172
Richard Smithb8348f52016-05-12 22:16:28 +00006173bool RecordExprEvaluator::ZeroInitialization(const Expr *E, QualType T) {
6174 const RecordDecl *RD = T->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006175 if (RD->isInvalidDecl()) return false;
Richard Smithfddd3842011-12-30 21:15:51 +00006176 if (RD->isUnion()) {
6177 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
6178 // object's first non-static named data member is zero-initialized
6179 RecordDecl::field_iterator I = RD->field_begin();
6180 if (I == RD->field_end()) {
Craig Topper36250ad2014-05-12 05:36:57 +00006181 Result = APValue((const FieldDecl*)nullptr);
Richard Smithfddd3842011-12-30 21:15:51 +00006182 return true;
6183 }
6184
6185 LValue Subobject = This;
David Blaikie40ed2972012-06-06 20:45:41 +00006186 if (!HandleLValueMember(Info, E, Subobject, *I))
John McCalld7bca762012-05-01 00:38:49 +00006187 return false;
David Blaikie40ed2972012-06-06 20:45:41 +00006188 Result = APValue(*I);
David Blaikie2d7c57e2012-04-30 02:36:29 +00006189 ImplicitValueInitExpr VIE(I->getType());
Richard Smithb228a862012-02-15 02:18:13 +00006190 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, &VIE);
Richard Smithfddd3842011-12-30 21:15:51 +00006191 }
6192
Richard Smith5d108602012-02-17 00:44:16 +00006193 if (isa<CXXRecordDecl>(RD) && cast<CXXRecordDecl>(RD)->getNumVBases()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00006194 Info.FFDiag(E, diag::note_constexpr_virtual_base) << RD;
Richard Smith5d108602012-02-17 00:44:16 +00006195 return false;
6196 }
6197
Richard Smitha8105bc2012-01-06 16:39:00 +00006198 return HandleClassZeroInitialization(Info, E, RD, This, Result);
Richard Smithfddd3842011-12-30 21:15:51 +00006199}
6200
Richard Smithe97cbd72011-11-11 04:05:33 +00006201bool RecordExprEvaluator::VisitCastExpr(const CastExpr *E) {
6202 switch (E->getCastKind()) {
6203 default:
6204 return ExprEvaluatorBaseTy::VisitCastExpr(E);
6205
6206 case CK_ConstructorConversion:
6207 return Visit(E->getSubExpr());
6208
6209 case CK_DerivedToBase:
6210 case CK_UncheckedDerivedToBase: {
Richard Smith2e312c82012-03-03 22:46:17 +00006211 APValue DerivedObject;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006212 if (!Evaluate(DerivedObject, Info, E->getSubExpr()))
Richard Smithe97cbd72011-11-11 04:05:33 +00006213 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00006214 if (!DerivedObject.isStruct())
6215 return Error(E->getSubExpr());
Richard Smithe97cbd72011-11-11 04:05:33 +00006216
6217 // Derived-to-base rvalue conversion: just slice off the derived part.
6218 APValue *Value = &DerivedObject;
6219 const CXXRecordDecl *RD = E->getSubExpr()->getType()->getAsCXXRecordDecl();
6220 for (CastExpr::path_const_iterator PathI = E->path_begin(),
6221 PathE = E->path_end(); PathI != PathE; ++PathI) {
6222 assert(!(*PathI)->isVirtual() && "record rvalue with virtual base");
6223 const CXXRecordDecl *Base = (*PathI)->getType()->getAsCXXRecordDecl();
6224 Value = &Value->getStructBase(getBaseIndex(RD, Base));
6225 RD = Base;
6226 }
6227 Result = *Value;
6228 return true;
6229 }
6230 }
6231}
6232
Richard Smithd62306a2011-11-10 06:34:14 +00006233bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith122f88d2016-12-06 23:52:28 +00006234 if (E->isTransparent())
6235 return Visit(E->getInit(0));
6236
Richard Smithd62306a2011-11-10 06:34:14 +00006237 const RecordDecl *RD = E->getType()->castAs<RecordType>()->getDecl();
John McCall3c79d882012-04-26 18:10:01 +00006238 if (RD->isInvalidDecl()) return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006239 const ASTRecordLayout &Layout = Info.Ctx.getASTRecordLayout(RD);
6240
6241 if (RD->isUnion()) {
Richard Smith9eae7232012-01-12 18:54:33 +00006242 const FieldDecl *Field = E->getInitializedFieldInUnion();
6243 Result = APValue(Field);
6244 if (!Field)
Richard Smithd62306a2011-11-10 06:34:14 +00006245 return true;
Richard Smith9eae7232012-01-12 18:54:33 +00006246
6247 // If the initializer list for a union does not contain any elements, the
6248 // first element of the union is value-initialized.
Richard Smith852c9db2013-04-20 22:23:05 +00006249 // FIXME: The element should be initialized from an initializer list.
6250 // Is this difference ever observable for initializer lists which
6251 // we don't build?
Richard Smith9eae7232012-01-12 18:54:33 +00006252 ImplicitValueInitExpr VIE(Field->getType());
6253 const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
6254
Richard Smithd62306a2011-11-10 06:34:14 +00006255 LValue Subobject = This;
John McCalld7bca762012-05-01 00:38:49 +00006256 if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
6257 return false;
Richard Smith852c9db2013-04-20 22:23:05 +00006258
6259 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6260 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6261 isa<CXXDefaultInitExpr>(InitExpr));
6262
Richard Smithb228a862012-02-15 02:18:13 +00006263 return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
Richard Smithd62306a2011-11-10 06:34:14 +00006264 }
6265
Richard Smith872307e2016-03-08 22:17:41 +00006266 auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
Richard Smithc0d04a22016-05-25 22:06:25 +00006267 if (Result.isUninit())
6268 Result = APValue(APValue::UninitStruct(), CXXRD ? CXXRD->getNumBases() : 0,
6269 std::distance(RD->field_begin(), RD->field_end()));
Richard Smithd62306a2011-11-10 06:34:14 +00006270 unsigned ElementNo = 0;
Richard Smith253c2a32012-01-27 01:14:48 +00006271 bool Success = true;
Richard Smith872307e2016-03-08 22:17:41 +00006272
6273 // Initialize base classes.
6274 if (CXXRD) {
6275 for (const auto &Base : CXXRD->bases()) {
6276 assert(ElementNo < E->getNumInits() && "missing init for base class");
6277 const Expr *Init = E->getInit(ElementNo);
6278
6279 LValue Subobject = This;
6280 if (!HandleLValueBase(Info, Init, Subobject, CXXRD, &Base))
6281 return false;
6282
6283 APValue &FieldVal = Result.getStructBase(ElementNo);
6284 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006285 if (!Info.noteFailure())
Richard Smith872307e2016-03-08 22:17:41 +00006286 return false;
6287 Success = false;
6288 }
6289 ++ElementNo;
6290 }
6291 }
6292
6293 // Initialize members.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006294 for (const auto *Field : RD->fields()) {
Richard Smithd62306a2011-11-10 06:34:14 +00006295 // Anonymous bit-fields are not considered members of the class for
6296 // purposes of aggregate initialization.
6297 if (Field->isUnnamedBitfield())
6298 continue;
6299
6300 LValue Subobject = This;
Richard Smithd62306a2011-11-10 06:34:14 +00006301
Richard Smith253c2a32012-01-27 01:14:48 +00006302 bool HaveInit = ElementNo < E->getNumInits();
6303
6304 // FIXME: Diagnostics here should point to the end of the initializer
6305 // list, not the start.
John McCalld7bca762012-05-01 00:38:49 +00006306 if (!HandleLValueMember(Info, HaveInit ? E->getInit(ElementNo) : E,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006307 Subobject, Field, &Layout))
John McCalld7bca762012-05-01 00:38:49 +00006308 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006309
6310 // Perform an implicit value-initialization for members beyond the end of
6311 // the initializer list.
6312 ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
Richard Smith852c9db2013-04-20 22:23:05 +00006313 const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
Richard Smith253c2a32012-01-27 01:14:48 +00006314
Richard Smith852c9db2013-04-20 22:23:05 +00006315 // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
6316 ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
6317 isa<CXXDefaultInitExpr>(Init));
6318
Richard Smith49ca8aa2013-08-06 07:09:20 +00006319 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6320 if (!EvaluateInPlace(FieldVal, Info, Subobject, Init) ||
6321 (Field->isBitField() && !truncateBitfieldValue(Info, Init,
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00006322 FieldVal, Field))) {
George Burgess IVa145e252016-05-25 22:38:36 +00006323 if (!Info.noteFailure())
Richard Smithd62306a2011-11-10 06:34:14 +00006324 return false;
Richard Smith253c2a32012-01-27 01:14:48 +00006325 Success = false;
Richard Smithd62306a2011-11-10 06:34:14 +00006326 }
6327 }
6328
Richard Smith253c2a32012-01-27 01:14:48 +00006329 return Success;
Richard Smithd62306a2011-11-10 06:34:14 +00006330}
6331
Richard Smithb8348f52016-05-12 22:16:28 +00006332bool RecordExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6333 QualType T) {
6334 // Note that E's type is not necessarily the type of our class here; we might
6335 // be initializing an array element instead.
Richard Smithd62306a2011-11-10 06:34:14 +00006336 const CXXConstructorDecl *FD = E->getConstructor();
John McCall3c79d882012-04-26 18:10:01 +00006337 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl()) return false;
6338
Richard Smithfddd3842011-12-30 21:15:51 +00006339 bool ZeroInit = E->requiresZeroInitialization();
6340 if (CheckTrivialDefaultConstructor(Info, E->getExprLoc(), FD, ZeroInit)) {
Richard Smith9eae7232012-01-12 18:54:33 +00006341 // If we've already performed zero-initialization, we're already done.
6342 if (!Result.isUninit())
6343 return true;
6344
Richard Smithda3f4fd2014-03-05 23:32:50 +00006345 // We can get here in two different ways:
6346 // 1) We're performing value-initialization, and should zero-initialize
6347 // the object, or
6348 // 2) We're performing default-initialization of an object with a trivial
6349 // constexpr default constructor, in which case we should start the
6350 // lifetimes of all the base subobjects (there can be no data member
6351 // subobjects in this case) per [basic.life]p1.
6352 // Either way, ZeroInitialization is appropriate.
Richard Smithb8348f52016-05-12 22:16:28 +00006353 return ZeroInitialization(E, T);
Richard Smithcc36f692011-12-22 02:22:31 +00006354 }
6355
Craig Topper36250ad2014-05-12 05:36:57 +00006356 const FunctionDecl *Definition = nullptr;
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006357 auto Body = FD->getBody(Definition);
Richard Smithd62306a2011-11-10 06:34:14 +00006358
Olivier Goffart8bc0caa2e2016-02-12 12:34:44 +00006359 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
Richard Smith357362d2011-12-13 06:39:58 +00006360 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00006361
Richard Smith1bc5c2c2012-01-10 04:32:03 +00006362 // Avoid materializing a temporary for an elidable copy/move constructor.
Richard Smithfddd3842011-12-30 21:15:51 +00006363 if (E->isElidable() && !ZeroInit)
Richard Smithd62306a2011-11-10 06:34:14 +00006364 if (const MaterializeTemporaryExpr *ME
6365 = dyn_cast<MaterializeTemporaryExpr>(E->getArg(0)))
6366 return Visit(ME->GetTemporaryExpr());
6367
Richard Smithb8348f52016-05-12 22:16:28 +00006368 if (ZeroInit && !ZeroInitialization(E, T))
Richard Smithfddd3842011-12-30 21:15:51 +00006369 return false;
6370
Craig Topper5fc8fc22014-08-27 06:28:36 +00006371 auto Args = llvm::makeArrayRef(E->getArgs(), E->getNumArgs());
Richard Smith5179eb72016-06-28 19:03:57 +00006372 return HandleConstructorCall(E, This, Args,
6373 cast<CXXConstructorDecl>(Definition), Info,
6374 Result);
6375}
6376
6377bool RecordExprEvaluator::VisitCXXInheritedCtorInitExpr(
6378 const CXXInheritedCtorInitExpr *E) {
6379 if (!Info.CurrentCall) {
6380 assert(Info.checkingPotentialConstantExpression());
6381 return false;
6382 }
6383
6384 const CXXConstructorDecl *FD = E->getConstructor();
6385 if (FD->isInvalidDecl() || FD->getParent()->isInvalidDecl())
6386 return false;
6387
6388 const FunctionDecl *Definition = nullptr;
6389 auto Body = FD->getBody(Definition);
6390
6391 if (!CheckConstexprFunction(Info, E->getExprLoc(), FD, Definition, Body))
6392 return false;
6393
6394 return HandleConstructorCall(E, This, Info.CurrentCall->Arguments,
Richard Smithf57d8cb2011-12-09 22:58:01 +00006395 cast<CXXConstructorDecl>(Definition), Info,
6396 Result);
Richard Smithd62306a2011-11-10 06:34:14 +00006397}
6398
Richard Smithcc1b96d2013-06-12 22:31:48 +00006399bool RecordExprEvaluator::VisitCXXStdInitializerListExpr(
6400 const CXXStdInitializerListExpr *E) {
6401 const ConstantArrayType *ArrayType =
6402 Info.Ctx.getAsConstantArrayType(E->getSubExpr()->getType());
6403
6404 LValue Array;
6405 if (!EvaluateLValue(E->getSubExpr(), Array, Info))
6406 return false;
6407
6408 // Get a pointer to the first element of the array.
6409 Array.addArray(Info, E, ArrayType);
6410
6411 // FIXME: Perform the checks on the field types in SemaInit.
6412 RecordDecl *Record = E->getType()->castAs<RecordType>()->getDecl();
6413 RecordDecl::field_iterator Field = Record->field_begin();
6414 if (Field == Record->field_end())
6415 return Error(E);
6416
6417 // Start pointer.
6418 if (!Field->getType()->isPointerType() ||
6419 !Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6420 ArrayType->getElementType()))
6421 return Error(E);
6422
6423 // FIXME: What if the initializer_list type has base classes, etc?
6424 Result = APValue(APValue::UninitStruct(), 0, 2);
6425 Array.moveInto(Result.getStructField(0));
6426
6427 if (++Field == Record->field_end())
6428 return Error(E);
6429
6430 if (Field->getType()->isPointerType() &&
6431 Info.Ctx.hasSameType(Field->getType()->getPointeeType(),
6432 ArrayType->getElementType())) {
6433 // End pointer.
6434 if (!HandleLValueArrayAdjustment(Info, E, Array,
6435 ArrayType->getElementType(),
6436 ArrayType->getSize().getZExtValue()))
6437 return false;
6438 Array.moveInto(Result.getStructField(1));
6439 } else if (Info.Ctx.hasSameType(Field->getType(), Info.Ctx.getSizeType()))
6440 // Length.
6441 Result.getStructField(1) = APValue(APSInt(ArrayType->getSize()));
6442 else
6443 return Error(E);
6444
6445 if (++Field != Record->field_end())
6446 return Error(E);
6447
6448 return true;
6449}
6450
Faisal Valic72a08c2017-01-09 03:02:53 +00006451bool RecordExprEvaluator::VisitLambdaExpr(const LambdaExpr *E) {
6452 const CXXRecordDecl *ClosureClass = E->getLambdaClass();
6453 if (ClosureClass->isInvalidDecl()) return false;
6454
6455 if (Info.checkingPotentialConstantExpression()) return true;
Daniel Jasperffdee092017-05-02 19:21:42 +00006456
Faisal Vali051e3a22017-02-16 04:12:21 +00006457 const size_t NumFields =
6458 std::distance(ClosureClass->field_begin(), ClosureClass->field_end());
Benjamin Krameraad1bdc2017-02-16 14:08:41 +00006459
6460 assert(NumFields == (size_t)std::distance(E->capture_init_begin(),
6461 E->capture_init_end()) &&
6462 "The number of lambda capture initializers should equal the number of "
6463 "fields within the closure type");
6464
Faisal Vali051e3a22017-02-16 04:12:21 +00006465 Result = APValue(APValue::UninitStruct(), /*NumBases*/0, NumFields);
6466 // Iterate through all the lambda's closure object's fields and initialize
6467 // them.
6468 auto *CaptureInitIt = E->capture_init_begin();
6469 const LambdaCapture *CaptureIt = ClosureClass->captures_begin();
6470 bool Success = true;
6471 for (const auto *Field : ClosureClass->fields()) {
6472 assert(CaptureInitIt != E->capture_init_end());
6473 // Get the initializer for this field
6474 Expr *const CurFieldInit = *CaptureInitIt++;
Daniel Jasperffdee092017-05-02 19:21:42 +00006475
Faisal Vali051e3a22017-02-16 04:12:21 +00006476 // If there is no initializer, either this is a VLA or an error has
6477 // occurred.
6478 if (!CurFieldInit)
6479 return Error(E);
6480
6481 APValue &FieldVal = Result.getStructField(Field->getFieldIndex());
6482 if (!EvaluateInPlace(FieldVal, Info, This, CurFieldInit)) {
6483 if (!Info.keepEvaluatingAfterFailure())
6484 return false;
6485 Success = false;
6486 }
6487 ++CaptureIt;
Faisal Valic72a08c2017-01-09 03:02:53 +00006488 }
Faisal Vali051e3a22017-02-16 04:12:21 +00006489 return Success;
Faisal Valic72a08c2017-01-09 03:02:53 +00006490}
6491
Richard Smithd62306a2011-11-10 06:34:14 +00006492static bool EvaluateRecord(const Expr *E, const LValue &This,
6493 APValue &Result, EvalInfo &Info) {
6494 assert(E->isRValue() && E->getType()->isRecordType() &&
Richard Smithd62306a2011-11-10 06:34:14 +00006495 "can't evaluate expression as a record rvalue");
6496 return RecordExprEvaluator(Info, This, Result).Visit(E);
6497}
6498
6499//===----------------------------------------------------------------------===//
Richard Smith027bf112011-11-17 22:56:20 +00006500// Temporary Evaluation
6501//
6502// Temporaries are represented in the AST as rvalues, but generally behave like
6503// lvalues. The full-object of which the temporary is a subobject is implicitly
6504// materialized so that a reference can bind to it.
6505//===----------------------------------------------------------------------===//
6506namespace {
6507class TemporaryExprEvaluator
6508 : public LValueExprEvaluatorBase<TemporaryExprEvaluator> {
6509public:
6510 TemporaryExprEvaluator(EvalInfo &Info, LValue &Result) :
George Burgess IVf9013bf2017-02-10 22:52:29 +00006511 LValueExprEvaluatorBaseTy(Info, Result, false) {}
Richard Smith027bf112011-11-17 22:56:20 +00006512
6513 /// Visit an expression which constructs the value of this temporary.
6514 bool VisitConstructExpr(const Expr *E) {
Richard Smithb228a862012-02-15 02:18:13 +00006515 Result.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00006516 return EvaluateInPlace(Info.CurrentCall->createTemporary(E, false),
6517 Info, Result, E);
Richard Smith027bf112011-11-17 22:56:20 +00006518 }
6519
6520 bool VisitCastExpr(const CastExpr *E) {
6521 switch (E->getCastKind()) {
6522 default:
6523 return LValueExprEvaluatorBaseTy::VisitCastExpr(E);
6524
6525 case CK_ConstructorConversion:
6526 return VisitConstructExpr(E->getSubExpr());
6527 }
6528 }
6529 bool VisitInitListExpr(const InitListExpr *E) {
6530 return VisitConstructExpr(E);
6531 }
6532 bool VisitCXXConstructExpr(const CXXConstructExpr *E) {
6533 return VisitConstructExpr(E);
6534 }
6535 bool VisitCallExpr(const CallExpr *E) {
6536 return VisitConstructExpr(E);
6537 }
Richard Smith513955c2014-12-17 19:24:30 +00006538 bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E) {
6539 return VisitConstructExpr(E);
6540 }
Faisal Valic72a08c2017-01-09 03:02:53 +00006541 bool VisitLambdaExpr(const LambdaExpr *E) {
6542 return VisitConstructExpr(E);
6543 }
Richard Smith027bf112011-11-17 22:56:20 +00006544};
6545} // end anonymous namespace
6546
6547/// Evaluate an expression of record type as a temporary.
6548static bool EvaluateTemporary(const Expr *E, LValue &Result, EvalInfo &Info) {
Richard Smithd0b111c2011-12-19 22:01:37 +00006549 assert(E->isRValue() && E->getType()->isRecordType());
Richard Smith027bf112011-11-17 22:56:20 +00006550 return TemporaryExprEvaluator(Info, Result).Visit(E);
6551}
6552
6553//===----------------------------------------------------------------------===//
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006554// Vector Evaluation
6555//===----------------------------------------------------------------------===//
6556
6557namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006558 class VectorExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006559 : public ExprEvaluatorBase<VectorExprEvaluator> {
Richard Smith2d406342011-10-22 21:10:00 +00006560 APValue &Result;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006561 public:
Mike Stump11289f42009-09-09 15:08:12 +00006562
Richard Smith2d406342011-10-22 21:10:00 +00006563 VectorExprEvaluator(EvalInfo &info, APValue &Result)
6564 : ExprEvaluatorBaseTy(info), Result(Result) {}
Mike Stump11289f42009-09-09 15:08:12 +00006565
Craig Topper9798b932015-09-29 04:30:05 +00006566 bool Success(ArrayRef<APValue> V, const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006567 assert(V.size() == E->getType()->castAs<VectorType>()->getNumElements());
6568 // FIXME: remove this APValue copy.
6569 Result = APValue(V.data(), V.size());
6570 return true;
6571 }
Richard Smith2e312c82012-03-03 22:46:17 +00006572 bool Success(const APValue &V, const Expr *E) {
Richard Smithed5165f2011-11-04 05:33:44 +00006573 assert(V.isVector());
Richard Smith2d406342011-10-22 21:10:00 +00006574 Result = V;
6575 return true;
6576 }
Richard Smithfddd3842011-12-30 21:15:51 +00006577 bool ZeroInitialization(const Expr *E);
Mike Stump11289f42009-09-09 15:08:12 +00006578
Richard Smith2d406342011-10-22 21:10:00 +00006579 bool VisitUnaryReal(const UnaryOperator *E)
Eli Friedman3ae59112009-02-23 04:23:56 +00006580 { return Visit(E->getSubExpr()); }
Richard Smith2d406342011-10-22 21:10:00 +00006581 bool VisitCastExpr(const CastExpr* E);
Richard Smith2d406342011-10-22 21:10:00 +00006582 bool VisitInitListExpr(const InitListExpr *E);
6583 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006584 // FIXME: Missing: unary -, unary ~, binary add/sub/mul/div,
Eli Friedmanc2b50172009-02-22 11:46:18 +00006585 // binary comparisons, binary and/or/xor,
Eli Friedman3ae59112009-02-23 04:23:56 +00006586 // shufflevector, ExtVectorElementExpr
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006587 };
6588} // end anonymous namespace
6589
6590static bool EvaluateVector(const Expr* E, APValue& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00006591 assert(E->isRValue() && E->getType()->isVectorType() &&"not a vector rvalue");
Richard Smith2d406342011-10-22 21:10:00 +00006592 return VectorExprEvaluator(Info, Result).Visit(E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006593}
6594
George Burgess IV533ff002015-12-11 00:23:35 +00006595bool VectorExprEvaluator::VisitCastExpr(const CastExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006596 const VectorType *VTy = E->getType()->castAs<VectorType>();
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006597 unsigned NElts = VTy->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006598
Richard Smith161f09a2011-12-06 22:44:34 +00006599 const Expr *SE = E->getSubExpr();
Nate Begeman2ffd3842009-06-26 18:22:18 +00006600 QualType SETy = SE->getType();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006601
Eli Friedmanc757de22011-03-25 00:43:55 +00006602 switch (E->getCastKind()) {
6603 case CK_VectorSplat: {
Richard Smith2d406342011-10-22 21:10:00 +00006604 APValue Val = APValue();
Eli Friedmanc757de22011-03-25 00:43:55 +00006605 if (SETy->isIntegerType()) {
6606 APSInt IntResult;
6607 if (!EvaluateInteger(SE, IntResult, Info))
George Burgess IV533ff002015-12-11 00:23:35 +00006608 return false;
6609 Val = APValue(std::move(IntResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006610 } else if (SETy->isRealFloatingType()) {
George Burgess IV533ff002015-12-11 00:23:35 +00006611 APFloat FloatResult(0.0);
6612 if (!EvaluateFloat(SE, FloatResult, Info))
6613 return false;
6614 Val = APValue(std::move(FloatResult));
Eli Friedmanc757de22011-03-25 00:43:55 +00006615 } else {
Richard Smith2d406342011-10-22 21:10:00 +00006616 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006617 }
Nate Begemanef1a7fa2009-07-01 07:50:47 +00006618
6619 // Splat and create vector APValue.
Richard Smith2d406342011-10-22 21:10:00 +00006620 SmallVector<APValue, 4> Elts(NElts, Val);
6621 return Success(Elts, E);
Nate Begeman2ffd3842009-06-26 18:22:18 +00006622 }
Eli Friedman803acb32011-12-22 03:51:45 +00006623 case CK_BitCast: {
6624 // Evaluate the operand into an APInt we can extract from.
6625 llvm::APInt SValInt;
6626 if (!EvalAndBitcastToAPInt(Info, SE, SValInt))
6627 return false;
6628 // Extract the elements
6629 QualType EltTy = VTy->getElementType();
6630 unsigned EltSize = Info.Ctx.getTypeSize(EltTy);
6631 bool BigEndian = Info.Ctx.getTargetInfo().isBigEndian();
6632 SmallVector<APValue, 4> Elts;
6633 if (EltTy->isRealFloatingType()) {
6634 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(EltTy);
Eli Friedman803acb32011-12-22 03:51:45 +00006635 unsigned FloatEltSize = EltSize;
Stephan Bergmann17c7f702016-12-14 11:57:17 +00006636 if (&Sem == &APFloat::x87DoubleExtended())
Eli Friedman803acb32011-12-22 03:51:45 +00006637 FloatEltSize = 80;
6638 for (unsigned i = 0; i < NElts; i++) {
6639 llvm::APInt Elt;
6640 if (BigEndian)
6641 Elt = SValInt.rotl(i*EltSize+FloatEltSize).trunc(FloatEltSize);
6642 else
6643 Elt = SValInt.rotr(i*EltSize).trunc(FloatEltSize);
Tim Northover178723a2013-01-22 09:46:51 +00006644 Elts.push_back(APValue(APFloat(Sem, Elt)));
Eli Friedman803acb32011-12-22 03:51:45 +00006645 }
6646 } else if (EltTy->isIntegerType()) {
6647 for (unsigned i = 0; i < NElts; i++) {
6648 llvm::APInt Elt;
6649 if (BigEndian)
6650 Elt = SValInt.rotl(i*EltSize+EltSize).zextOrTrunc(EltSize);
6651 else
6652 Elt = SValInt.rotr(i*EltSize).zextOrTrunc(EltSize);
6653 Elts.push_back(APValue(APSInt(Elt, EltTy->isSignedIntegerType())));
6654 }
6655 } else {
6656 return Error(E);
6657 }
6658 return Success(Elts, E);
6659 }
Eli Friedmanc757de22011-03-25 00:43:55 +00006660 default:
Richard Smith11562c52011-10-28 17:51:58 +00006661 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00006662 }
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006663}
6664
Richard Smith2d406342011-10-22 21:10:00 +00006665bool
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006666VectorExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006667 const VectorType *VT = E->getType()->castAs<VectorType>();
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006668 unsigned NumInits = E->getNumInits();
Eli Friedman3ae59112009-02-23 04:23:56 +00006669 unsigned NumElements = VT->getNumElements();
Mike Stump11289f42009-09-09 15:08:12 +00006670
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006671 QualType EltTy = VT->getElementType();
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006672 SmallVector<APValue, 4> Elements;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006673
Eli Friedmanb9c71292012-01-03 23:24:20 +00006674 // The number of initializers can be less than the number of
6675 // vector elements. For OpenCL, this can be due to nested vector
Daniel Jasperffdee092017-05-02 19:21:42 +00006676 // initialization. For GCC compatibility, missing trailing elements
Eli Friedmanb9c71292012-01-03 23:24:20 +00006677 // should be initialized with zeroes.
6678 unsigned CountInits = 0, CountElts = 0;
6679 while (CountElts < NumElements) {
6680 // Handle nested vector initialization.
Daniel Jasperffdee092017-05-02 19:21:42 +00006681 if (CountInits < NumInits
Eli Friedman1409e6e2013-09-17 04:07:02 +00006682 && E->getInit(CountInits)->getType()->isVectorType()) {
Eli Friedmanb9c71292012-01-03 23:24:20 +00006683 APValue v;
6684 if (!EvaluateVector(E->getInit(CountInits), v, Info))
6685 return Error(E);
6686 unsigned vlen = v.getVectorLength();
Daniel Jasperffdee092017-05-02 19:21:42 +00006687 for (unsigned j = 0; j < vlen; j++)
Eli Friedmanb9c71292012-01-03 23:24:20 +00006688 Elements.push_back(v.getVectorElt(j));
6689 CountElts += vlen;
6690 } else if (EltTy->isIntegerType()) {
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006691 llvm::APSInt sInt(32);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006692 if (CountInits < NumInits) {
6693 if (!EvaluateInteger(E->getInit(CountInits), sInt, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006694 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006695 } else // trailing integer zero.
6696 sInt = Info.Ctx.MakeIntValue(0, EltTy);
6697 Elements.push_back(APValue(sInt));
6698 CountElts++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006699 } else {
6700 llvm::APFloat f(0.0);
Eli Friedmanb9c71292012-01-03 23:24:20 +00006701 if (CountInits < NumInits) {
6702 if (!EvaluateFloat(E->getInit(CountInits), f, Info))
Richard Smithac2f0b12012-03-13 20:58:32 +00006703 return false;
Eli Friedmanb9c71292012-01-03 23:24:20 +00006704 } else // trailing float zero.
6705 f = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy));
6706 Elements.push_back(APValue(f));
6707 CountElts++;
John McCall875679e2010-06-11 17:54:15 +00006708 }
Eli Friedmanb9c71292012-01-03 23:24:20 +00006709 CountInits++;
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006710 }
Richard Smith2d406342011-10-22 21:10:00 +00006711 return Success(Elements, E);
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006712}
6713
Richard Smith2d406342011-10-22 21:10:00 +00006714bool
Richard Smithfddd3842011-12-30 21:15:51 +00006715VectorExprEvaluator::ZeroInitialization(const Expr *E) {
Richard Smith2d406342011-10-22 21:10:00 +00006716 const VectorType *VT = E->getType()->getAs<VectorType>();
Eli Friedman3ae59112009-02-23 04:23:56 +00006717 QualType EltTy = VT->getElementType();
6718 APValue ZeroElement;
6719 if (EltTy->isIntegerType())
6720 ZeroElement = APValue(Info.Ctx.MakeIntValue(0, EltTy));
6721 else
6722 ZeroElement =
6723 APValue(APFloat::getZero(Info.Ctx.getFloatTypeSemantics(EltTy)));
6724
Chris Lattner0e62c1c2011-07-23 10:55:15 +00006725 SmallVector<APValue, 4> Elements(VT->getNumElements(), ZeroElement);
Richard Smith2d406342011-10-22 21:10:00 +00006726 return Success(Elements, E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006727}
6728
Richard Smith2d406342011-10-22 21:10:00 +00006729bool VectorExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Richard Smith4a678122011-10-24 18:44:57 +00006730 VisitIgnoredValue(E->getSubExpr());
Richard Smithfddd3842011-12-30 21:15:51 +00006731 return ZeroInitialization(E);
Eli Friedman3ae59112009-02-23 04:23:56 +00006732}
6733
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00006734//===----------------------------------------------------------------------===//
Richard Smithf3e9e432011-11-07 09:22:26 +00006735// Array Evaluation
6736//===----------------------------------------------------------------------===//
6737
6738namespace {
6739 class ArrayExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006740 : public ExprEvaluatorBase<ArrayExprEvaluator> {
Richard Smithd62306a2011-11-10 06:34:14 +00006741 const LValue &This;
Richard Smithf3e9e432011-11-07 09:22:26 +00006742 APValue &Result;
6743 public:
6744
Richard Smithd62306a2011-11-10 06:34:14 +00006745 ArrayExprEvaluator(EvalInfo &Info, const LValue &This, APValue &Result)
6746 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smithf3e9e432011-11-07 09:22:26 +00006747
6748 bool Success(const APValue &V, const Expr *E) {
Richard Smith14a94132012-02-17 03:35:37 +00006749 assert((V.isArray() || V.isLValue()) &&
6750 "expected array or string literal");
Richard Smithf3e9e432011-11-07 09:22:26 +00006751 Result = V;
6752 return true;
6753 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006754
Richard Smithfddd3842011-12-30 21:15:51 +00006755 bool ZeroInitialization(const Expr *E) {
Richard Smithd62306a2011-11-10 06:34:14 +00006756 const ConstantArrayType *CAT =
6757 Info.Ctx.getAsConstantArrayType(E->getType());
6758 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006759 return Error(E);
Richard Smithd62306a2011-11-10 06:34:14 +00006760
6761 Result = APValue(APValue::UninitArray(), 0,
6762 CAT->getSize().getZExtValue());
6763 if (!Result.hasArrayFiller()) return true;
6764
Richard Smithfddd3842011-12-30 21:15:51 +00006765 // Zero-initialize all elements.
Richard Smithd62306a2011-11-10 06:34:14 +00006766 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006767 Subobject.addArray(Info, E, CAT);
Richard Smithd62306a2011-11-10 06:34:14 +00006768 ImplicitValueInitExpr VIE(CAT->getElementType());
Richard Smithb228a862012-02-15 02:18:13 +00006769 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject, &VIE);
Richard Smithd62306a2011-11-10 06:34:14 +00006770 }
6771
Richard Smith52a980a2015-08-28 02:43:42 +00006772 bool VisitCallExpr(const CallExpr *E) {
6773 return handleCallExpr(E, Result, &This);
6774 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006775 bool VisitInitListExpr(const InitListExpr *E);
Richard Smith410306b2016-12-12 02:53:20 +00006776 bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
Richard Smith027bf112011-11-17 22:56:20 +00006777 bool VisitCXXConstructExpr(const CXXConstructExpr *E);
Richard Smith9543c5e2013-04-22 14:44:29 +00006778 bool VisitCXXConstructExpr(const CXXConstructExpr *E,
6779 const LValue &Subobject,
6780 APValue *Value, QualType Type);
Richard Smithf3e9e432011-11-07 09:22:26 +00006781 };
6782} // end anonymous namespace
6783
Richard Smithd62306a2011-11-10 06:34:14 +00006784static bool EvaluateArray(const Expr *E, const LValue &This,
6785 APValue &Result, EvalInfo &Info) {
Richard Smithfddd3842011-12-30 21:15:51 +00006786 assert(E->isRValue() && E->getType()->isArrayType() && "not an array rvalue");
Richard Smithd62306a2011-11-10 06:34:14 +00006787 return ArrayExprEvaluator(Info, This, Result).Visit(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006788}
6789
6790bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
6791 const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(E->getType());
6792 if (!CAT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00006793 return Error(E);
Richard Smithf3e9e432011-11-07 09:22:26 +00006794
Richard Smithca2cfbf2011-12-22 01:07:19 +00006795 // C++11 [dcl.init.string]p1: A char array [...] can be initialized by [...]
6796 // an appropriately-typed string literal enclosed in braces.
Richard Smith9ec1e482012-04-15 02:50:59 +00006797 if (E->isStringLiteralInit()) {
Richard Smithca2cfbf2011-12-22 01:07:19 +00006798 LValue LV;
6799 if (!EvaluateLValue(E->getInit(0), LV, Info))
6800 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00006801 APValue Val;
Richard Smith14a94132012-02-17 03:35:37 +00006802 LV.moveInto(Val);
6803 return Success(Val, E);
Richard Smithca2cfbf2011-12-22 01:07:19 +00006804 }
6805
Richard Smith253c2a32012-01-27 01:14:48 +00006806 bool Success = true;
6807
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006808 assert((!Result.isArray() || Result.getArrayInitializedElts() == 0) &&
6809 "zero-initialized array shouldn't have any initialized elts");
6810 APValue Filler;
6811 if (Result.isArray() && Result.hasArrayFiller())
6812 Filler = Result.getArrayFiller();
6813
Richard Smith9543c5e2013-04-22 14:44:29 +00006814 unsigned NumEltsToInit = E->getNumInits();
6815 unsigned NumElts = CAT->getSize().getZExtValue();
Craig Topper36250ad2014-05-12 05:36:57 +00006816 const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : nullptr;
Richard Smith9543c5e2013-04-22 14:44:29 +00006817
6818 // If the initializer might depend on the array index, run it for each
6819 // array element. For now, just whitelist non-class value-initialization.
6820 if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
6821 NumEltsToInit = NumElts;
6822
6823 Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006824
6825 // If the array was previously zero-initialized, preserve the
6826 // zero-initialized values.
6827 if (!Filler.isUninit()) {
6828 for (unsigned I = 0, E = Result.getArrayInitializedElts(); I != E; ++I)
6829 Result.getArrayInitializedElt(I) = Filler;
6830 if (Result.hasArrayFiller())
6831 Result.getArrayFiller() = Filler;
6832 }
6833
Richard Smithd62306a2011-11-10 06:34:14 +00006834 LValue Subobject = This;
Richard Smitha8105bc2012-01-06 16:39:00 +00006835 Subobject.addArray(Info, E, CAT);
Richard Smith9543c5e2013-04-22 14:44:29 +00006836 for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
6837 const Expr *Init =
6838 Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
Richard Smithb228a862012-02-15 02:18:13 +00006839 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
Richard Smith9543c5e2013-04-22 14:44:29 +00006840 Info, Subobject, Init) ||
6841 !HandleLValueArrayAdjustment(Info, Init, Subobject,
Richard Smith253c2a32012-01-27 01:14:48 +00006842 CAT->getElementType(), 1)) {
George Burgess IVa145e252016-05-25 22:38:36 +00006843 if (!Info.noteFailure())
Richard Smith253c2a32012-01-27 01:14:48 +00006844 return false;
6845 Success = false;
6846 }
Richard Smithd62306a2011-11-10 06:34:14 +00006847 }
Richard Smithf3e9e432011-11-07 09:22:26 +00006848
Richard Smith9543c5e2013-04-22 14:44:29 +00006849 if (!Result.hasArrayFiller())
6850 return Success;
6851
6852 // If we get here, we have a trivial filler, which we can just evaluate
6853 // once and splat over the rest of the array elements.
6854 assert(FillerExpr && "no array filler for incomplete init list");
6855 return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
6856 FillerExpr) && Success;
Richard Smithf3e9e432011-11-07 09:22:26 +00006857}
6858
Richard Smith410306b2016-12-12 02:53:20 +00006859bool ArrayExprEvaluator::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
6860 if (E->getCommonExpr() &&
6861 !Evaluate(Info.CurrentCall->createTemporary(E->getCommonExpr(), false),
6862 Info, E->getCommonExpr()->getSourceExpr()))
6863 return false;
6864
6865 auto *CAT = cast<ConstantArrayType>(E->getType()->castAsArrayTypeUnsafe());
6866
6867 uint64_t Elements = CAT->getSize().getZExtValue();
6868 Result = APValue(APValue::UninitArray(), Elements, Elements);
6869
6870 LValue Subobject = This;
6871 Subobject.addArray(Info, E, CAT);
6872
6873 bool Success = true;
6874 for (EvalInfo::ArrayInitLoopIndex Index(Info); Index != Elements; ++Index) {
6875 if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
6876 Info, Subobject, E->getSubExpr()) ||
6877 !HandleLValueArrayAdjustment(Info, E, Subobject,
6878 CAT->getElementType(), 1)) {
6879 if (!Info.noteFailure())
6880 return false;
6881 Success = false;
6882 }
6883 }
6884
6885 return Success;
6886}
6887
Richard Smith027bf112011-11-17 22:56:20 +00006888bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
Richard Smith9543c5e2013-04-22 14:44:29 +00006889 return VisitCXXConstructExpr(E, This, &Result, E->getType());
6890}
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006891
Richard Smith9543c5e2013-04-22 14:44:29 +00006892bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
6893 const LValue &Subobject,
6894 APValue *Value,
6895 QualType Type) {
6896 bool HadZeroInit = !Value->isUninit();
6897
6898 if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
6899 unsigned N = CAT->getSize().getZExtValue();
6900
6901 // Preserve the array filler if we had prior zero-initialization.
6902 APValue Filler =
6903 HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
6904 : APValue();
6905
6906 *Value = APValue(APValue::UninitArray(), N, N);
6907
6908 if (HadZeroInit)
6909 for (unsigned I = 0; I != N; ++I)
6910 Value->getArrayInitializedElt(I) = Filler;
6911
6912 // Initialize the elements.
6913 LValue ArrayElt = Subobject;
6914 ArrayElt.addArray(Info, E, CAT);
6915 for (unsigned I = 0; I != N; ++I)
6916 if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
6917 CAT->getElementType()) ||
6918 !HandleLValueArrayAdjustment(Info, E, ArrayElt,
6919 CAT->getElementType(), 1))
6920 return false;
6921
6922 return true;
Richard Smith1b9f2eb2012-07-07 22:48:24 +00006923 }
Richard Smith027bf112011-11-17 22:56:20 +00006924
Richard Smith9543c5e2013-04-22 14:44:29 +00006925 if (!Type->isRecordType())
Richard Smith9fce7bc2012-07-10 22:12:55 +00006926 return Error(E);
6927
Richard Smithb8348f52016-05-12 22:16:28 +00006928 return RecordExprEvaluator(Info, Subobject, *Value)
6929 .VisitCXXConstructExpr(E, Type);
Richard Smith027bf112011-11-17 22:56:20 +00006930}
6931
Richard Smithf3e9e432011-11-07 09:22:26 +00006932//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006933// Integer Evaluation
Richard Smith11562c52011-10-28 17:51:58 +00006934//
6935// As a GNU extension, we support casting pointers to sufficiently-wide integer
6936// types and back in constant folding. Integer values are thus represented
6937// either as an integer-valued APValue, or as an lvalue-valued APValue.
Chris Lattner05706e882008-07-11 18:11:29 +00006938//===----------------------------------------------------------------------===//
Chris Lattner05706e882008-07-11 18:11:29 +00006939
6940namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00006941class IntExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00006942 : public ExprEvaluatorBase<IntExprEvaluator> {
Richard Smith2e312c82012-03-03 22:46:17 +00006943 APValue &Result;
Anders Carlsson0a1707c2008-07-08 05:13:58 +00006944public:
Richard Smith2e312c82012-03-03 22:46:17 +00006945 IntExprEvaluator(EvalInfo &info, APValue &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00006946 : ExprEvaluatorBaseTy(info), Result(result) {}
Chris Lattner05706e882008-07-11 18:11:29 +00006947
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006948 bool Success(const llvm::APSInt &SI, const Expr *E, APValue &Result) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006949 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006950 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006951 assert(SI.isSigned() == E->getType()->isSignedIntegerOrEnumerationType() &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006952 "Invalid evaluation result.");
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00006953 assert(SI.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006954 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006955 Result = APValue(SI);
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006956 return true;
6957 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006958 bool Success(const llvm::APSInt &SI, const Expr *E) {
6959 return Success(SI, E, Result);
6960 }
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006961
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006962 bool Success(const llvm::APInt &I, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006963 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006964 "Invalid evaluation result.");
Daniel Dunbarca097ad2009-02-19 20:17:33 +00006965 assert(I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) &&
Daniel Dunbare3c92bc2009-02-19 18:37:50 +00006966 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006967 Result = APValue(APSInt(I));
Douglas Gregor6ab2fa82011-05-20 16:38:50 +00006968 Result.getInt().setIsUnsigned(
6969 E->getType()->isUnsignedIntegerOrEnumerationType());
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006970 return true;
6971 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006972 bool Success(const llvm::APInt &I, const Expr *E) {
6973 return Success(I, E, Result);
6974 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006975
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006976 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
Daniel Jasperffdee092017-05-02 19:21:42 +00006977 assert(E->getType()->isIntegralOrEnumerationType() &&
Douglas Gregorb90df602010-06-16 00:17:44 +00006978 "Invalid evaluation result.");
Richard Smith2e312c82012-03-03 22:46:17 +00006979 Result = APValue(Info.Ctx.MakeIntValue(Value, E->getType()));
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006980 return true;
6981 }
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00006982 bool Success(uint64_t Value, const Expr *E) {
6983 return Success(Value, E, Result);
6984 }
Daniel Dunbar8aafc892009-02-19 09:06:44 +00006985
Ken Dyckdbc01912011-03-11 02:13:43 +00006986 bool Success(CharUnits Size, const Expr *E) {
6987 return Success(Size.getQuantity(), E);
6988 }
6989
Richard Smith2e312c82012-03-03 22:46:17 +00006990 bool Success(const APValue &V, const Expr *E) {
Eli Friedmanb1bc3682012-01-05 23:59:40 +00006991 if (V.isLValue() || V.isAddrLabelDiff()) {
Richard Smith9c8d1c52011-10-29 22:55:55 +00006992 Result = V;
6993 return true;
6994 }
Peter Collingbournee9200682011-05-13 03:29:01 +00006995 return Success(V.getInt(), E);
Chris Lattnerfac05ae2008-11-12 07:43:42 +00006996 }
Mike Stump11289f42009-09-09 15:08:12 +00006997
Richard Smithfddd3842011-12-30 21:15:51 +00006998 bool ZeroInitialization(const Expr *E) { return Success(0, E); }
Richard Smith4ce706a2011-10-11 21:43:33 +00006999
Peter Collingbournee9200682011-05-13 03:29:01 +00007000 //===--------------------------------------------------------------------===//
7001 // Visitor Methods
7002 //===--------------------------------------------------------------------===//
Anders Carlsson0a1707c2008-07-08 05:13:58 +00007003
Chris Lattner7174bf32008-07-12 00:38:25 +00007004 bool VisitIntegerLiteral(const IntegerLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007005 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007006 }
7007 bool VisitCharacterLiteral(const CharacterLiteral *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007008 return Success(E->getValue(), E);
Chris Lattner7174bf32008-07-12 00:38:25 +00007009 }
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007010
7011 bool CheckReferencedDecl(const Expr *E, const Decl *D);
7012 bool VisitDeclRefExpr(const DeclRefExpr *E) {
Peter Collingbournee9200682011-05-13 03:29:01 +00007013 if (CheckReferencedDecl(E, E->getDecl()))
7014 return true;
7015
7016 return ExprEvaluatorBaseTy::VisitDeclRefExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007017 }
7018 bool VisitMemberExpr(const MemberExpr *E) {
7019 if (CheckReferencedDecl(E, E->getMemberDecl())) {
David Majnemere9807b22016-02-26 04:23:19 +00007020 VisitIgnoredBaseExpression(E->getBase());
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007021 return true;
7022 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007023
7024 return ExprEvaluatorBaseTy::VisitMemberExpr(E);
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007025 }
7026
Peter Collingbournee9200682011-05-13 03:29:01 +00007027 bool VisitCallExpr(const CallExpr *E);
Richard Smith6328cbd2016-11-16 00:57:23 +00007028 bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinOp);
Chris Lattnere13042c2008-07-11 19:10:17 +00007029 bool VisitBinaryOperator(const BinaryOperator *E);
Douglas Gregor882211c2010-04-28 22:16:22 +00007030 bool VisitOffsetOfExpr(const OffsetOfExpr *E);
Chris Lattnere13042c2008-07-11 19:10:17 +00007031 bool VisitUnaryOperator(const UnaryOperator *E);
Anders Carlsson374b93d2008-07-08 05:49:43 +00007032
Peter Collingbournee9200682011-05-13 03:29:01 +00007033 bool VisitCastExpr(const CastExpr* E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00007034 bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
Sebastian Redl6f282892008-11-11 17:56:53 +00007035
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007036 bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
Daniel Dunbar8aafc892009-02-19 09:06:44 +00007037 return Success(E->getValue(), E);
Anders Carlsson9f9e4242008-11-16 19:01:22 +00007038 }
Mike Stump11289f42009-09-09 15:08:12 +00007039
Ted Kremeneke65b0862012-03-06 20:05:56 +00007040 bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
7041 return Success(E->getValue(), E);
7042 }
Richard Smith410306b2016-12-12 02:53:20 +00007043
7044 bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
7045 if (Info.ArrayInitIndex == uint64_t(-1)) {
7046 // We were asked to evaluate this subexpression independent of the
7047 // enclosing ArrayInitLoopExpr. We can't do that.
7048 Info.FFDiag(E);
7049 return false;
7050 }
7051 return Success(Info.ArrayInitIndex, E);
7052 }
Daniel Jasperffdee092017-05-02 19:21:42 +00007053
Richard Smith4ce706a2011-10-11 21:43:33 +00007054 // Note, GNU defines __null as an integer, not a pointer.
Anders Carlsson39def3a2008-12-21 22:39:40 +00007055 bool VisitGNUNullExpr(const GNUNullExpr *E) {
Richard Smithfddd3842011-12-30 21:15:51 +00007056 return ZeroInitialization(E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007057 }
7058
Douglas Gregor29c42f22012-02-24 07:38:34 +00007059 bool VisitTypeTraitExpr(const TypeTraitExpr *E) {
7060 return Success(E->getValue(), E);
7061 }
7062
John Wiegley6242b6a2011-04-28 00:16:57 +00007063 bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
7064 return Success(E->getValue(), E);
7065 }
7066
John Wiegleyf9f65842011-04-25 06:54:41 +00007067 bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
7068 return Success(E->getValue(), E);
7069 }
7070
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00007071 bool VisitUnaryReal(const UnaryOperator *E);
Eli Friedman4e7a2412009-02-27 04:45:43 +00007072 bool VisitUnaryImag(const UnaryOperator *E);
7073
Sebastian Redl5f0180d2010-09-10 20:55:47 +00007074 bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
Douglas Gregor820ba7b2011-01-04 17:33:58 +00007075 bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
Sebastian Redl12757ab2011-09-24 17:48:14 +00007076
Eli Friedman4e7a2412009-02-27 04:45:43 +00007077 // FIXME: Missing: array subscript of vector, member of vector
Anders Carlsson9c181652008-07-08 14:35:21 +00007078};
Chris Lattner05706e882008-07-11 18:11:29 +00007079} // end anonymous namespace
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007080
Richard Smith11562c52011-10-28 17:51:58 +00007081/// EvaluateIntegerOrLValue - Evaluate an rvalue integral-typed expression, and
7082/// produce either the integer value or a pointer.
7083///
7084/// GCC has a heinous extension which folds casts between pointer types and
7085/// pointer-sized integral types. We support this by allowing the evaluation of
7086/// an integer rvalue to produce a pointer (represented as an lvalue) instead.
7087/// Some simple arithmetic on such values is supported (they are treated much
7088/// like char*).
Richard Smith2e312c82012-03-03 22:46:17 +00007089static bool EvaluateIntegerOrLValue(const Expr *E, APValue &Result,
Richard Smith0b0a0b62011-10-29 20:57:55 +00007090 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00007091 assert(E->isRValue() && E->getType()->isIntegralOrEnumerationType());
Peter Collingbournee9200682011-05-13 03:29:01 +00007092 return IntExprEvaluator(Info, Result).Visit(E);
Daniel Dunbarce399542009-02-20 18:22:23 +00007093}
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007094
Richard Smithf57d8cb2011-12-09 22:58:01 +00007095static bool EvaluateInteger(const Expr *E, APSInt &Result, EvalInfo &Info) {
Richard Smith2e312c82012-03-03 22:46:17 +00007096 APValue Val;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007097 if (!EvaluateIntegerOrLValue(E, Val, Info))
Daniel Dunbarce399542009-02-20 18:22:23 +00007098 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00007099 if (!Val.isInt()) {
7100 // FIXME: It would be better to produce the diagnostic for casting
7101 // a pointer to an integer.
Faisal Valie690b7a2016-07-02 22:34:24 +00007102 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smithf57d8cb2011-12-09 22:58:01 +00007103 return false;
7104 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00007105 Result = Val.getInt();
7106 return true;
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007107}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007108
Richard Smithf57d8cb2011-12-09 22:58:01 +00007109/// Check whether the given declaration can be directly converted to an integral
7110/// rvalue. If not, no diagnostic is produced; there are other things we can
7111/// try.
Eli Friedmanfb8a93f2009-11-24 05:28:59 +00007112bool IntExprEvaluator::CheckReferencedDecl(const Expr* E, const Decl* D) {
Chris Lattner7174bf32008-07-12 00:38:25 +00007113 // Enums are integer constant exprs.
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007114 if (const EnumConstantDecl *ECD = dyn_cast<EnumConstantDecl>(D)) {
Abramo Bagnara9ae292d2011-07-02 13:13:53 +00007115 // Check for signedness/width mismatches between E type and ECD value.
7116 bool SameSign = (ECD->getInitVal().isSigned()
7117 == E->getType()->isSignedIntegerOrEnumerationType());
7118 bool SameWidth = (ECD->getInitVal().getBitWidth()
7119 == Info.Ctx.getIntWidth(E->getType()));
7120 if (SameSign && SameWidth)
7121 return Success(ECD->getInitVal(), E);
7122 else {
7123 // Get rid of mismatch (otherwise Success assertions will fail)
7124 // by computing a new value matching the type of E.
7125 llvm::APSInt Val = ECD->getInitVal();
7126 if (!SameSign)
7127 Val.setIsSigned(!ECD->getInitVal().isSigned());
7128 if (!SameWidth)
7129 Val = Val.extOrTrunc(Info.Ctx.getIntWidth(E->getType()));
7130 return Success(Val, E);
7131 }
Abramo Bagnara2caedf42011-06-30 09:36:05 +00007132 }
Peter Collingbournee9200682011-05-13 03:29:01 +00007133 return false;
Chris Lattner7174bf32008-07-12 00:38:25 +00007134}
7135
Chris Lattner86ee2862008-10-06 06:40:35 +00007136/// EvaluateBuiltinClassifyType - Evaluate __builtin_classify_type the same way
7137/// as GCC.
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007138static int EvaluateBuiltinClassifyType(const CallExpr *E,
7139 const LangOptions &LangOpts) {
Chris Lattner86ee2862008-10-06 06:40:35 +00007140 // The following enum mimics the values returned by GCC.
Sebastian Redl0f8b23f2009-03-16 23:22:08 +00007141 // FIXME: Does GCC differ between lvalue and rvalue references here?
Chris Lattner86ee2862008-10-06 06:40:35 +00007142 enum gcc_type_class {
7143 no_type_class = -1,
7144 void_type_class, integer_type_class, char_type_class,
7145 enumeral_type_class, boolean_type_class,
7146 pointer_type_class, reference_type_class, offset_type_class,
7147 real_type_class, complex_type_class,
7148 function_type_class, method_type_class,
7149 record_type_class, union_type_class,
7150 array_type_class, string_type_class,
7151 lang_type_class
7152 };
Mike Stump11289f42009-09-09 15:08:12 +00007153
7154 // If no argument was supplied, default to "no_type_class". This isn't
Chris Lattner86ee2862008-10-06 06:40:35 +00007155 // ideal, however it is what gcc does.
7156 if (E->getNumArgs() == 0)
7157 return no_type_class;
Mike Stump11289f42009-09-09 15:08:12 +00007158
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007159 QualType CanTy = E->getArg(0)->getType().getCanonicalType();
7160 const BuiltinType *BT = dyn_cast<BuiltinType>(CanTy);
7161
7162 switch (CanTy->getTypeClass()) {
7163#define TYPE(ID, BASE)
7164#define DEPENDENT_TYPE(ID, BASE) case Type::ID:
7165#define NON_CANONICAL_TYPE(ID, BASE) case Type::ID:
7166#define NON_CANONICAL_UNLESS_DEPENDENT_TYPE(ID, BASE) case Type::ID:
7167#include "clang/AST/TypeNodes.def"
7168 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7169
7170 case Type::Builtin:
7171 switch (BT->getKind()) {
7172#define BUILTIN_TYPE(ID, SINGLETON_ID)
7173#define SIGNED_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return integer_type_class;
7174#define FLOATING_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: return real_type_class;
7175#define PLACEHOLDER_TYPE(ID, SINGLETON_ID) case BuiltinType::ID: break;
7176#include "clang/AST/BuiltinTypes.def"
7177 case BuiltinType::Void:
7178 return void_type_class;
7179
7180 case BuiltinType::Bool:
7181 return boolean_type_class;
7182
7183 case BuiltinType::Char_U: // gcc doesn't appear to use char_type_class
7184 case BuiltinType::UChar:
7185 case BuiltinType::UShort:
7186 case BuiltinType::UInt:
7187 case BuiltinType::ULong:
7188 case BuiltinType::ULongLong:
7189 case BuiltinType::UInt128:
7190 return integer_type_class;
7191
7192 case BuiltinType::NullPtr:
7193 return pointer_type_class;
7194
7195 case BuiltinType::WChar_U:
7196 case BuiltinType::Char16:
7197 case BuiltinType::Char32:
7198 case BuiltinType::ObjCId:
7199 case BuiltinType::ObjCClass:
7200 case BuiltinType::ObjCSel:
Alexey Bader954ba212016-04-08 13:40:33 +00007201#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
7202 case BuiltinType::Id:
Alexey Baderb62f1442016-04-13 08:33:41 +00007203#include "clang/Basic/OpenCLImageTypes.def"
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007204 case BuiltinType::OCLSampler:
7205 case BuiltinType::OCLEvent:
7206 case BuiltinType::OCLClkEvent:
7207 case BuiltinType::OCLQueue:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007208 case BuiltinType::OCLReserveID:
7209 case BuiltinType::Dependent:
7210 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7211 };
7212
7213 case Type::Enum:
7214 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7215 break;
7216
7217 case Type::Pointer:
Chris Lattner86ee2862008-10-06 06:40:35 +00007218 return pointer_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007219 break;
7220
7221 case Type::MemberPointer:
7222 if (CanTy->isMemberDataPointerType())
7223 return offset_type_class;
7224 else {
7225 // We expect member pointers to be either data or function pointers,
7226 // nothing else.
7227 assert(CanTy->isMemberFunctionPointerType());
7228 return method_type_class;
7229 }
7230
7231 case Type::Complex:
Chris Lattner86ee2862008-10-06 06:40:35 +00007232 return complex_type_class;
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007233
7234 case Type::FunctionNoProto:
7235 case Type::FunctionProto:
7236 return LangOpts.CPlusPlus ? function_type_class : pointer_type_class;
7237
7238 case Type::Record:
7239 if (const RecordType *RT = CanTy->getAs<RecordType>()) {
7240 switch (RT->getDecl()->getTagKind()) {
7241 case TagTypeKind::TTK_Struct:
7242 case TagTypeKind::TTK_Class:
7243 case TagTypeKind::TTK_Interface:
7244 return record_type_class;
7245
7246 case TagTypeKind::TTK_Enum:
7247 return LangOpts.CPlusPlus ? enumeral_type_class : integer_type_class;
7248
7249 case TagTypeKind::TTK_Union:
7250 return union_type_class;
7251 }
7252 }
David Blaikie83d382b2011-09-23 05:06:16 +00007253 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007254
7255 case Type::ConstantArray:
7256 case Type::VariableArray:
7257 case Type::IncompleteArray:
7258 return LangOpts.CPlusPlus ? array_type_class : pointer_type_class;
7259
7260 case Type::BlockPointer:
7261 case Type::LValueReference:
7262 case Type::RValueReference:
7263 case Type::Vector:
7264 case Type::ExtVector:
7265 case Type::Auto:
Richard Smith600b5262017-01-26 20:40:47 +00007266 case Type::DeducedTemplateSpecialization:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007267 case Type::ObjCObject:
7268 case Type::ObjCInterface:
7269 case Type::ObjCObjectPointer:
7270 case Type::Pipe:
7271 case Type::Atomic:
7272 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
7273 }
7274
7275 llvm_unreachable("CallExpr::isBuiltinClassifyType(): unimplemented type");
Chris Lattner86ee2862008-10-06 06:40:35 +00007276}
7277
Richard Smith5fab0c92011-12-28 19:48:30 +00007278/// EvaluateBuiltinConstantPForLValue - Determine the result of
7279/// __builtin_constant_p when applied to the given lvalue.
7280///
7281/// An lvalue is only "constant" if it is a pointer or reference to the first
7282/// character of a string literal.
7283template<typename LValue>
7284static bool EvaluateBuiltinConstantPForLValue(const LValue &LV) {
Douglas Gregorf31cee62012-03-11 02:23:56 +00007285 const Expr *E = LV.getLValueBase().template dyn_cast<const Expr*>();
Richard Smith5fab0c92011-12-28 19:48:30 +00007286 return E && isa<StringLiteral>(E) && LV.getLValueOffset().isZero();
7287}
7288
7289/// EvaluateBuiltinConstantP - Evaluate __builtin_constant_p as similarly to
7290/// GCC as we can manage.
7291static bool EvaluateBuiltinConstantP(ASTContext &Ctx, const Expr *Arg) {
7292 QualType ArgType = Arg->getType();
7293
7294 // __builtin_constant_p always has one operand. The rules which gcc follows
7295 // are not precisely documented, but are as follows:
7296 //
7297 // - If the operand is of integral, floating, complex or enumeration type,
7298 // and can be folded to a known value of that type, it returns 1.
7299 // - If the operand and can be folded to a pointer to the first character
7300 // of a string literal (or such a pointer cast to an integral type), it
7301 // returns 1.
7302 //
7303 // Otherwise, it returns 0.
7304 //
7305 // FIXME: GCC also intends to return 1 for literals of aggregate types, but
7306 // its support for this does not currently work.
7307 if (ArgType->isIntegralOrEnumerationType()) {
7308 Expr::EvalResult Result;
7309 if (!Arg->EvaluateAsRValue(Result, Ctx) || Result.HasSideEffects)
7310 return false;
7311
7312 APValue &V = Result.Val;
7313 if (V.getKind() == APValue::Int)
7314 return true;
Richard Smith0c6124b2015-12-03 01:36:22 +00007315 if (V.getKind() == APValue::LValue)
7316 return EvaluateBuiltinConstantPForLValue(V);
Richard Smith5fab0c92011-12-28 19:48:30 +00007317 } else if (ArgType->isFloatingType() || ArgType->isAnyComplexType()) {
7318 return Arg->isEvaluatable(Ctx);
7319 } else if (ArgType->isPointerType() || Arg->isGLValue()) {
7320 LValue LV;
7321 Expr::EvalStatus Status;
Richard Smith6d4c6582013-11-05 22:18:15 +00007322 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
Richard Smith5fab0c92011-12-28 19:48:30 +00007323 if ((Arg->isGLValue() ? EvaluateLValue(Arg, LV, Info)
7324 : EvaluatePointer(Arg, LV, Info)) &&
7325 !Status.HasSideEffects)
7326 return EvaluateBuiltinConstantPForLValue(LV);
7327 }
7328
7329 // Anything else isn't considered to be sufficiently constant.
7330 return false;
7331}
7332
John McCall95007602010-05-10 23:27:23 +00007333/// Retrieves the "underlying object type" of the given expression,
7334/// as used by __builtin_object_size.
George Burgess IVbdb5b262015-08-19 02:19:07 +00007335static QualType getObjectType(APValue::LValueBase B) {
Richard Smithce40ad62011-11-12 22:28:03 +00007336 if (const ValueDecl *D = B.dyn_cast<const ValueDecl*>()) {
7337 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
John McCall95007602010-05-10 23:27:23 +00007338 return VD->getType();
Richard Smithce40ad62011-11-12 22:28:03 +00007339 } else if (const Expr *E = B.get<const Expr*>()) {
7340 if (isa<CompoundLiteralExpr>(E))
7341 return E->getType();
John McCall95007602010-05-10 23:27:23 +00007342 }
7343
7344 return QualType();
7345}
7346
George Burgess IV3a03fab2015-09-04 21:28:13 +00007347/// A more selective version of E->IgnoreParenCasts for
George Burgess IVe3763372016-12-22 02:50:20 +00007348/// tryEvaluateBuiltinObjectSize. This ignores some casts/parens that serve only
George Burgess IVb40cd562015-09-04 22:36:18 +00007349/// to change the type of E.
George Burgess IV3a03fab2015-09-04 21:28:13 +00007350/// Ex. For E = `(short*)((char*)(&foo))`, returns `&foo`
7351///
7352/// Always returns an RValue with a pointer representation.
7353static const Expr *ignorePointerCastsAndParens(const Expr *E) {
7354 assert(E->isRValue() && E->getType()->hasPointerRepresentation());
7355
7356 auto *NoParens = E->IgnoreParens();
7357 auto *Cast = dyn_cast<CastExpr>(NoParens);
George Burgess IVb40cd562015-09-04 22:36:18 +00007358 if (Cast == nullptr)
7359 return NoParens;
7360
7361 // We only conservatively allow a few kinds of casts, because this code is
7362 // inherently a simple solution that seeks to support the common case.
7363 auto CastKind = Cast->getCastKind();
7364 if (CastKind != CK_NoOp && CastKind != CK_BitCast &&
7365 CastKind != CK_AddressSpaceConversion)
George Burgess IV3a03fab2015-09-04 21:28:13 +00007366 return NoParens;
7367
7368 auto *SubExpr = Cast->getSubExpr();
7369 if (!SubExpr->getType()->hasPointerRepresentation() || !SubExpr->isRValue())
7370 return NoParens;
7371 return ignorePointerCastsAndParens(SubExpr);
7372}
7373
George Burgess IVa51c4072015-10-16 01:49:01 +00007374/// Checks to see if the given LValue's Designator is at the end of the LValue's
7375/// record layout. e.g.
7376/// struct { struct { int a, b; } fst, snd; } obj;
7377/// obj.fst // no
7378/// obj.snd // yes
7379/// obj.fst.a // no
7380/// obj.fst.b // no
7381/// obj.snd.a // no
7382/// obj.snd.b // yes
7383///
7384/// Please note: this function is specialized for how __builtin_object_size
7385/// views "objects".
George Burgess IV4168d752016-06-27 19:40:41 +00007386///
Richard Smith6f4f0f12017-10-20 22:56:25 +00007387/// If this encounters an invalid RecordDecl or otherwise cannot determine the
7388/// correct result, it will always return true.
George Burgess IVa51c4072015-10-16 01:49:01 +00007389static bool isDesignatorAtObjectEnd(const ASTContext &Ctx, const LValue &LVal) {
7390 assert(!LVal.Designator.Invalid);
7391
George Burgess IV4168d752016-06-27 19:40:41 +00007392 auto IsLastOrInvalidFieldDecl = [&Ctx](const FieldDecl *FD, bool &Invalid) {
7393 const RecordDecl *Parent = FD->getParent();
7394 Invalid = Parent->isInvalidDecl();
7395 if (Invalid || Parent->isUnion())
George Burgess IVa51c4072015-10-16 01:49:01 +00007396 return true;
George Burgess IV4168d752016-06-27 19:40:41 +00007397 const ASTRecordLayout &Layout = Ctx.getASTRecordLayout(Parent);
George Burgess IVa51c4072015-10-16 01:49:01 +00007398 return FD->getFieldIndex() + 1 == Layout.getFieldCount();
7399 };
7400
7401 auto &Base = LVal.getLValueBase();
7402 if (auto *ME = dyn_cast_or_null<MemberExpr>(Base.dyn_cast<const Expr *>())) {
7403 if (auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007404 bool Invalid;
7405 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7406 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007407 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(ME->getMemberDecl())) {
George Burgess IV4168d752016-06-27 19:40:41 +00007408 for (auto *FD : IFD->chain()) {
7409 bool Invalid;
7410 if (!IsLastOrInvalidFieldDecl(cast<FieldDecl>(FD), Invalid))
7411 return Invalid;
7412 }
George Burgess IVa51c4072015-10-16 01:49:01 +00007413 }
7414 }
7415
George Burgess IVe3763372016-12-22 02:50:20 +00007416 unsigned I = 0;
George Burgess IVa51c4072015-10-16 01:49:01 +00007417 QualType BaseType = getType(Base);
Daniel Jasperffdee092017-05-02 19:21:42 +00007418 if (LVal.Designator.FirstEntryIsAnUnsizedArray) {
Richard Smith6f4f0f12017-10-20 22:56:25 +00007419 // If we don't know the array bound, conservatively assume we're looking at
7420 // the final array element.
George Burgess IVe3763372016-12-22 02:50:20 +00007421 ++I;
7422 BaseType = BaseType->castAs<PointerType>()->getPointeeType();
7423 }
7424
7425 for (unsigned E = LVal.Designator.Entries.size(); I != E; ++I) {
7426 const auto &Entry = LVal.Designator.Entries[I];
George Burgess IVa51c4072015-10-16 01:49:01 +00007427 if (BaseType->isArrayType()) {
7428 // Because __builtin_object_size treats arrays as objects, we can ignore
7429 // the index iff this is the last array in the Designator.
7430 if (I + 1 == E)
7431 return true;
George Burgess IVe3763372016-12-22 02:50:20 +00007432 const auto *CAT = cast<ConstantArrayType>(Ctx.getAsArrayType(BaseType));
7433 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007434 if (Index + 1 != CAT->getSize())
7435 return false;
7436 BaseType = CAT->getElementType();
7437 } else if (BaseType->isAnyComplexType()) {
George Burgess IVe3763372016-12-22 02:50:20 +00007438 const auto *CT = BaseType->castAs<ComplexType>();
7439 uint64_t Index = Entry.ArrayIndex;
George Burgess IVa51c4072015-10-16 01:49:01 +00007440 if (Index != 1)
7441 return false;
7442 BaseType = CT->getElementType();
George Burgess IVe3763372016-12-22 02:50:20 +00007443 } else if (auto *FD = getAsField(Entry)) {
George Burgess IV4168d752016-06-27 19:40:41 +00007444 bool Invalid;
7445 if (!IsLastOrInvalidFieldDecl(FD, Invalid))
7446 return Invalid;
George Burgess IVa51c4072015-10-16 01:49:01 +00007447 BaseType = FD->getType();
7448 } else {
George Burgess IVe3763372016-12-22 02:50:20 +00007449 assert(getAsBaseClass(Entry) && "Expecting cast to a base class");
George Burgess IVa51c4072015-10-16 01:49:01 +00007450 return false;
7451 }
7452 }
7453 return true;
7454}
7455
George Burgess IVe3763372016-12-22 02:50:20 +00007456/// Tests to see if the LValue has a user-specified designator (that isn't
7457/// necessarily valid). Note that this always returns 'true' if the LValue has
7458/// an unsized array as its first designator entry, because there's currently no
7459/// way to tell if the user typed *foo or foo[0].
George Burgess IVa51c4072015-10-16 01:49:01 +00007460static bool refersToCompleteObject(const LValue &LVal) {
George Burgess IVe3763372016-12-22 02:50:20 +00007461 if (LVal.Designator.Invalid)
George Burgess IVa51c4072015-10-16 01:49:01 +00007462 return false;
7463
George Burgess IVe3763372016-12-22 02:50:20 +00007464 if (!LVal.Designator.Entries.empty())
7465 return LVal.Designator.isMostDerivedAnUnsizedArray();
7466
George Burgess IVa51c4072015-10-16 01:49:01 +00007467 if (!LVal.InvalidBase)
7468 return true;
7469
George Burgess IVe3763372016-12-22 02:50:20 +00007470 // If `E` is a MemberExpr, then the first part of the designator is hiding in
7471 // the LValueBase.
7472 const auto *E = LVal.Base.dyn_cast<const Expr *>();
7473 return !E || !isa<MemberExpr>(E);
George Burgess IVa51c4072015-10-16 01:49:01 +00007474}
7475
George Burgess IVe3763372016-12-22 02:50:20 +00007476/// Attempts to detect a user writing into a piece of memory that's impossible
7477/// to figure out the size of by just using types.
7478static bool isUserWritingOffTheEnd(const ASTContext &Ctx, const LValue &LVal) {
7479 const SubobjectDesignator &Designator = LVal.Designator;
7480 // Notes:
7481 // - Users can only write off of the end when we have an invalid base. Invalid
7482 // bases imply we don't know where the memory came from.
7483 // - We used to be a bit more aggressive here; we'd only be conservative if
7484 // the array at the end was flexible, or if it had 0 or 1 elements. This
7485 // broke some common standard library extensions (PR30346), but was
7486 // otherwise seemingly fine. It may be useful to reintroduce this behavior
7487 // with some sort of whitelist. OTOH, it seems that GCC is always
7488 // conservative with the last element in structs (if it's an array), so our
7489 // current behavior is more compatible than a whitelisting approach would
7490 // be.
7491 return LVal.InvalidBase &&
7492 Designator.Entries.size() == Designator.MostDerivedPathLength &&
7493 Designator.MostDerivedIsArrayElement &&
7494 isDesignatorAtObjectEnd(Ctx, LVal);
7495}
7496
7497/// Converts the given APInt to CharUnits, assuming the APInt is unsigned.
7498/// Fails if the conversion would cause loss of precision.
7499static bool convertUnsignedAPIntToCharUnits(const llvm::APInt &Int,
7500 CharUnits &Result) {
7501 auto CharUnitsMax = std::numeric_limits<CharUnits::QuantityType>::max();
7502 if (Int.ugt(CharUnitsMax))
7503 return false;
7504 Result = CharUnits::fromQuantity(Int.getZExtValue());
7505 return true;
7506}
7507
7508/// Helper for tryEvaluateBuiltinObjectSize -- Given an LValue, this will
7509/// determine how many bytes exist from the beginning of the object to either
7510/// the end of the current subobject, or the end of the object itself, depending
7511/// on what the LValue looks like + the value of Type.
George Burgess IVa7470272016-12-20 01:05:42 +00007512///
George Burgess IVe3763372016-12-22 02:50:20 +00007513/// If this returns false, the value of Result is undefined.
7514static bool determineEndOffset(EvalInfo &Info, SourceLocation ExprLoc,
7515 unsigned Type, const LValue &LVal,
7516 CharUnits &EndOffset) {
7517 bool DetermineForCompleteObject = refersToCompleteObject(LVal);
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007518
George Burgess IV7fb7e362017-01-03 23:35:19 +00007519 auto CheckedHandleSizeof = [&](QualType Ty, CharUnits &Result) {
7520 if (Ty.isNull() || Ty->isIncompleteType() || Ty->isFunctionType())
7521 return false;
7522 return HandleSizeof(Info, ExprLoc, Ty, Result);
7523 };
7524
George Burgess IVe3763372016-12-22 02:50:20 +00007525 // We want to evaluate the size of the entire object. This is a valid fallback
7526 // for when Type=1 and the designator is invalid, because we're asked for an
7527 // upper-bound.
7528 if (!(Type & 1) || LVal.Designator.Invalid || DetermineForCompleteObject) {
7529 // Type=3 wants a lower bound, so we can't fall back to this.
7530 if (Type == 3 && !DetermineForCompleteObject)
George Burgess IVa7470272016-12-20 01:05:42 +00007531 return false;
George Burgess IVe3763372016-12-22 02:50:20 +00007532
7533 llvm::APInt APEndOffset;
7534 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7535 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7536 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7537
7538 if (LVal.InvalidBase)
7539 return false;
7540
7541 QualType BaseTy = getObjectType(LVal.getLValueBase());
George Burgess IV7fb7e362017-01-03 23:35:19 +00007542 return CheckedHandleSizeof(BaseTy, EndOffset);
George Burgess IVa7470272016-12-20 01:05:42 +00007543 }
7544
George Burgess IVe3763372016-12-22 02:50:20 +00007545 // We want to evaluate the size of a subobject.
7546 const SubobjectDesignator &Designator = LVal.Designator;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007547
7548 // The following is a moderately common idiom in C:
7549 //
7550 // struct Foo { int a; char c[1]; };
7551 // struct Foo *F = (struct Foo *)malloc(sizeof(struct Foo) + strlen(Bar));
7552 // strcpy(&F->c[0], Bar);
7553 //
George Burgess IVe3763372016-12-22 02:50:20 +00007554 // In order to not break too much legacy code, we need to support it.
7555 if (isUserWritingOffTheEnd(Info.Ctx, LVal)) {
7556 // If we can resolve this to an alloc_size call, we can hand that back,
7557 // because we know for certain how many bytes there are to write to.
7558 llvm::APInt APEndOffset;
7559 if (isBaseAnAllocSizeCall(LVal.getLValueBase()) &&
7560 getBytesReturnedByAllocSizeCall(Info.Ctx, LVal, APEndOffset))
7561 return convertUnsignedAPIntToCharUnits(APEndOffset, EndOffset);
7562
7563 // If we cannot determine the size of the initial allocation, then we can't
7564 // given an accurate upper-bound. However, we are still able to give
7565 // conservative lower-bounds for Type=3.
7566 if (Type == 1)
7567 return false;
7568 }
7569
7570 CharUnits BytesPerElem;
George Burgess IV7fb7e362017-01-03 23:35:19 +00007571 if (!CheckedHandleSizeof(Designator.MostDerivedType, BytesPerElem))
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007572 return false;
7573
George Burgess IVe3763372016-12-22 02:50:20 +00007574 // According to the GCC documentation, we want the size of the subobject
7575 // denoted by the pointer. But that's not quite right -- what we actually
7576 // want is the size of the immediately-enclosing array, if there is one.
7577 int64_t ElemsRemaining;
7578 if (Designator.MostDerivedIsArrayElement &&
7579 Designator.Entries.size() == Designator.MostDerivedPathLength) {
7580 uint64_t ArraySize = Designator.getMostDerivedArraySize();
7581 uint64_t ArrayIndex = Designator.Entries.back().ArrayIndex;
7582 ElemsRemaining = ArraySize <= ArrayIndex ? 0 : ArraySize - ArrayIndex;
7583 } else {
7584 ElemsRemaining = Designator.isOnePastTheEnd() ? 0 : 1;
7585 }
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007586
George Burgess IVe3763372016-12-22 02:50:20 +00007587 EndOffset = LVal.getLValueOffset() + BytesPerElem * ElemsRemaining;
7588 return true;
Chandler Carruthd7738fe2016-12-20 08:28:19 +00007589}
7590
George Burgess IVe3763372016-12-22 02:50:20 +00007591/// \brief Tries to evaluate the __builtin_object_size for @p E. If successful,
7592/// returns true and stores the result in @p Size.
7593///
7594/// If @p WasError is non-null, this will report whether the failure to evaluate
7595/// is to be treated as an Error in IntExprEvaluator.
7596static bool tryEvaluateBuiltinObjectSize(const Expr *E, unsigned Type,
7597 EvalInfo &Info, uint64_t &Size) {
7598 // Determine the denoted object.
7599 LValue LVal;
7600 {
7601 // The operand of __builtin_object_size is never evaluated for side-effects.
7602 // If there are any, but we can determine the pointed-to object anyway, then
7603 // ignore the side-effects.
7604 SpeculativeEvaluationRAII SpeculativeEval(Info);
7605 FoldOffsetRAII Fold(Info);
7606
7607 if (E->isGLValue()) {
7608 // It's possible for us to be given GLValues if we're called via
7609 // Expr::tryEvaluateObjectSize.
7610 APValue RVal;
7611 if (!EvaluateAsRValue(Info, E, RVal))
7612 return false;
7613 LVal.setFrom(Info.Ctx, RVal);
George Burgess IVf9013bf2017-02-10 22:52:29 +00007614 } else if (!EvaluatePointer(ignorePointerCastsAndParens(E), LVal, Info,
7615 /*InvalidBaseOK=*/true))
George Burgess IVe3763372016-12-22 02:50:20 +00007616 return false;
7617 }
7618
7619 // If we point to before the start of the object, there are no accessible
7620 // bytes.
7621 if (LVal.getLValueOffset().isNegative()) {
7622 Size = 0;
7623 return true;
7624 }
7625
7626 CharUnits EndOffset;
7627 if (!determineEndOffset(Info, E->getExprLoc(), Type, LVal, EndOffset))
7628 return false;
7629
7630 // If we've fallen outside of the end offset, just pretend there's nothing to
7631 // write to/read from.
7632 if (EndOffset <= LVal.getLValueOffset())
7633 Size = 0;
7634 else
7635 Size = (EndOffset - LVal.getLValueOffset()).getQuantity();
7636 return true;
John McCall95007602010-05-10 23:27:23 +00007637}
7638
Peter Collingbournee9200682011-05-13 03:29:01 +00007639bool IntExprEvaluator::VisitCallExpr(const CallExpr *E) {
Richard Smith6328cbd2016-11-16 00:57:23 +00007640 if (unsigned BuiltinOp = E->getBuiltinCallee())
7641 return VisitBuiltinCallExpr(E, BuiltinOp);
7642
7643 return ExprEvaluatorBaseTy::VisitCallExpr(E);
7644}
7645
7646bool IntExprEvaluator::VisitBuiltinCallExpr(const CallExpr *E,
7647 unsigned BuiltinOp) {
Alp Tokera724cff2013-12-28 21:59:02 +00007648 switch (unsigned BuiltinOp = E->getBuiltinCallee()) {
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007649 default:
Peter Collingbournee9200682011-05-13 03:29:01 +00007650 return ExprEvaluatorBaseTy::VisitCallExpr(E);
Mike Stump722cedf2009-10-26 18:35:08 +00007651
7652 case Builtin::BI__builtin_object_size: {
George Burgess IVbdb5b262015-08-19 02:19:07 +00007653 // The type was checked when we built the expression.
7654 unsigned Type =
7655 E->getArg(1)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7656 assert(Type <= 3 && "unexpected type");
7657
George Burgess IVe3763372016-12-22 02:50:20 +00007658 uint64_t Size;
7659 if (tryEvaluateBuiltinObjectSize(E->getArg(0), Type, Info, Size))
7660 return Success(Size, E);
Mike Stump722cedf2009-10-26 18:35:08 +00007661
George Burgess IV3e3bb95b2015-12-02 21:58:08 +00007662 if (E->getArg(0)->HasSideEffects(Info.Ctx))
George Burgess IVbdb5b262015-08-19 02:19:07 +00007663 return Success((Type & 2) ? 0 : -1, E);
Mike Stump876387b2009-10-27 22:09:17 +00007664
Richard Smith01ade172012-05-23 04:13:20 +00007665 // Expression had no side effects, but we couldn't statically determine the
7666 // size of the referenced object.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007667 switch (Info.EvalMode) {
7668 case EvalInfo::EM_ConstantExpression:
7669 case EvalInfo::EM_PotentialConstantExpression:
7670 case EvalInfo::EM_ConstantFold:
7671 case EvalInfo::EM_EvaluateForOverflow:
7672 case EvalInfo::EM_IgnoreSideEffects:
George Burgess IVe3763372016-12-22 02:50:20 +00007673 case EvalInfo::EM_OffsetFold:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007674 // Leave it to IR generation.
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007675 return Error(E);
7676 case EvalInfo::EM_ConstantExpressionUnevaluated:
7677 case EvalInfo::EM_PotentialConstantExpressionUnevaluated:
George Burgess IVbdb5b262015-08-19 02:19:07 +00007678 // Reduce it to a constant now.
7679 return Success((Type & 2) ? 0 : -1, E);
Nick Lewycky35a6ef42014-01-11 02:50:57 +00007680 }
Richard Smithcb2ba5a2016-07-18 22:37:35 +00007681
7682 llvm_unreachable("unexpected EvalMode");
Mike Stump722cedf2009-10-26 18:35:08 +00007683 }
7684
Benjamin Kramera801f4a2012-10-06 14:42:22 +00007685 case Builtin::BI__builtin_bswap16:
Richard Smith80ac9ef2012-09-28 20:20:52 +00007686 case Builtin::BI__builtin_bswap32:
7687 case Builtin::BI__builtin_bswap64: {
7688 APSInt Val;
7689 if (!EvaluateInteger(E->getArg(0), Val, Info))
7690 return false;
7691
7692 return Success(Val.byteSwap(), E);
7693 }
7694
Richard Smith8889a3d2013-06-13 06:26:32 +00007695 case Builtin::BI__builtin_classify_type:
Andrey Bokhanko5f6588e2016-02-15 10:39:04 +00007696 return Success(EvaluateBuiltinClassifyType(E, Info.getLangOpts()), E);
Richard Smith8889a3d2013-06-13 06:26:32 +00007697
7698 // FIXME: BI__builtin_clrsb
7699 // FIXME: BI__builtin_clrsbl
7700 // FIXME: BI__builtin_clrsbll
7701
Richard Smith80b3c8e2013-06-13 05:04:16 +00007702 case Builtin::BI__builtin_clz:
7703 case Builtin::BI__builtin_clzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007704 case Builtin::BI__builtin_clzll:
7705 case Builtin::BI__builtin_clzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007706 APSInt Val;
7707 if (!EvaluateInteger(E->getArg(0), Val, Info))
7708 return false;
7709 if (!Val)
7710 return Error(E);
7711
7712 return Success(Val.countLeadingZeros(), E);
7713 }
7714
Richard Smith8889a3d2013-06-13 06:26:32 +00007715 case Builtin::BI__builtin_constant_p:
7716 return Success(EvaluateBuiltinConstantP(Info.Ctx, E->getArg(0)), E);
7717
Richard Smith80b3c8e2013-06-13 05:04:16 +00007718 case Builtin::BI__builtin_ctz:
7719 case Builtin::BI__builtin_ctzl:
Anders Carlsson1a9fe3d2014-07-07 15:53:44 +00007720 case Builtin::BI__builtin_ctzll:
7721 case Builtin::BI__builtin_ctzs: {
Richard Smith80b3c8e2013-06-13 05:04:16 +00007722 APSInt Val;
7723 if (!EvaluateInteger(E->getArg(0), Val, Info))
7724 return false;
7725 if (!Val)
7726 return Error(E);
7727
7728 return Success(Val.countTrailingZeros(), E);
7729 }
7730
Richard Smith8889a3d2013-06-13 06:26:32 +00007731 case Builtin::BI__builtin_eh_return_data_regno: {
7732 int Operand = E->getArg(0)->EvaluateKnownConstInt(Info.Ctx).getZExtValue();
7733 Operand = Info.Ctx.getTargetInfo().getEHDataRegisterNumber(Operand);
7734 return Success(Operand, E);
7735 }
7736
7737 case Builtin::BI__builtin_expect:
7738 return Visit(E->getArg(0));
7739
7740 case Builtin::BI__builtin_ffs:
7741 case Builtin::BI__builtin_ffsl:
7742 case Builtin::BI__builtin_ffsll: {
7743 APSInt Val;
7744 if (!EvaluateInteger(E->getArg(0), Val, Info))
7745 return false;
7746
7747 unsigned N = Val.countTrailingZeros();
7748 return Success(N == Val.getBitWidth() ? 0 : N + 1, E);
7749 }
7750
7751 case Builtin::BI__builtin_fpclassify: {
7752 APFloat Val(0.0);
7753 if (!EvaluateFloat(E->getArg(5), Val, Info))
7754 return false;
7755 unsigned Arg;
7756 switch (Val.getCategory()) {
7757 case APFloat::fcNaN: Arg = 0; break;
7758 case APFloat::fcInfinity: Arg = 1; break;
7759 case APFloat::fcNormal: Arg = Val.isDenormal() ? 3 : 2; break;
7760 case APFloat::fcZero: Arg = 4; break;
7761 }
7762 return Visit(E->getArg(Arg));
7763 }
7764
7765 case Builtin::BI__builtin_isinf_sign: {
7766 APFloat Val(0.0);
Richard Smithab341c62013-06-13 06:31:13 +00007767 return EvaluateFloat(E->getArg(0), Val, Info) &&
Richard Smith8889a3d2013-06-13 06:26:32 +00007768 Success(Val.isInfinity() ? (Val.isNegative() ? -1 : 1) : 0, E);
7769 }
7770
Richard Smithea3019d2013-10-15 19:07:14 +00007771 case Builtin::BI__builtin_isinf: {
7772 APFloat Val(0.0);
7773 return EvaluateFloat(E->getArg(0), Val, Info) &&
7774 Success(Val.isInfinity() ? 1 : 0, E);
7775 }
7776
7777 case Builtin::BI__builtin_isfinite: {
7778 APFloat Val(0.0);
7779 return EvaluateFloat(E->getArg(0), Val, Info) &&
7780 Success(Val.isFinite() ? 1 : 0, E);
7781 }
7782
7783 case Builtin::BI__builtin_isnan: {
7784 APFloat Val(0.0);
7785 return EvaluateFloat(E->getArg(0), Val, Info) &&
7786 Success(Val.isNaN() ? 1 : 0, E);
7787 }
7788
7789 case Builtin::BI__builtin_isnormal: {
7790 APFloat Val(0.0);
7791 return EvaluateFloat(E->getArg(0), Val, Info) &&
7792 Success(Val.isNormal() ? 1 : 0, E);
7793 }
7794
Richard Smith8889a3d2013-06-13 06:26:32 +00007795 case Builtin::BI__builtin_parity:
7796 case Builtin::BI__builtin_parityl:
7797 case Builtin::BI__builtin_parityll: {
7798 APSInt Val;
7799 if (!EvaluateInteger(E->getArg(0), Val, Info))
7800 return false;
7801
7802 return Success(Val.countPopulation() % 2, E);
7803 }
7804
Richard Smith80b3c8e2013-06-13 05:04:16 +00007805 case Builtin::BI__builtin_popcount:
7806 case Builtin::BI__builtin_popcountl:
7807 case Builtin::BI__builtin_popcountll: {
7808 APSInt Val;
7809 if (!EvaluateInteger(E->getArg(0), Val, Info))
7810 return false;
7811
7812 return Success(Val.countPopulation(), E);
7813 }
7814
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007815 case Builtin::BIstrlen:
Richard Smith8110c9d2016-11-29 19:45:17 +00007816 case Builtin::BIwcslen:
Richard Smith9cf080f2012-01-18 03:06:12 +00007817 // A call to strlen is not a constant expression.
Richard Smith2bf7fdb2013-01-02 11:42:31 +00007818 if (Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00007819 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
Richard Smith8110c9d2016-11-29 19:45:17 +00007820 << /*isConstexpr*/0 << /*isConstructor*/0
7821 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smith9cf080f2012-01-18 03:06:12 +00007822 else
Richard Smithce1ec5e2012-03-15 04:53:45 +00007823 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
Richard Smith9cf080f2012-01-18 03:06:12 +00007824 // Fall through.
Richard Smith8110c9d2016-11-29 19:45:17 +00007825 case Builtin::BI__builtin_strlen:
7826 case Builtin::BI__builtin_wcslen: {
Richard Smithe6c19f22013-11-15 02:10:04 +00007827 // As an extension, we support __builtin_strlen() as a constant expression,
7828 // and support folding strlen() to a constant.
7829 LValue String;
7830 if (!EvaluatePointer(E->getArg(0), String, Info))
7831 return false;
7832
Richard Smith8110c9d2016-11-29 19:45:17 +00007833 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7834
Richard Smithe6c19f22013-11-15 02:10:04 +00007835 // Fast path: if it's a string literal, search the string value.
7836 if (const StringLiteral *S = dyn_cast_or_null<StringLiteral>(
7837 String.getLValueBase().dyn_cast<const Expr *>())) {
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007838 // The string literal may have embedded null characters. Find the first
7839 // one and truncate there.
Richard Smithe6c19f22013-11-15 02:10:04 +00007840 StringRef Str = S->getBytes();
7841 int64_t Off = String.Offset.getQuantity();
7842 if (Off >= 0 && (uint64_t)Off <= (uint64_t)Str.size() &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007843 S->getCharByteWidth() == 1 &&
7844 // FIXME: Add fast-path for wchar_t too.
7845 Info.Ctx.hasSameUnqualifiedType(CharTy, Info.Ctx.CharTy)) {
Richard Smithe6c19f22013-11-15 02:10:04 +00007846 Str = Str.substr(Off);
7847
7848 StringRef::size_type Pos = Str.find(0);
7849 if (Pos != StringRef::npos)
7850 Str = Str.substr(0, Pos);
7851
7852 return Success(Str.size(), E);
7853 }
7854
7855 // Fall through to slow path to issue appropriate diagnostic.
Douglas Gregor6a6dac22010-09-10 06:27:15 +00007856 }
Richard Smithe6c19f22013-11-15 02:10:04 +00007857
7858 // Slow path: scan the bytes of the string looking for the terminating 0.
Richard Smithe6c19f22013-11-15 02:10:04 +00007859 for (uint64_t Strlen = 0; /**/; ++Strlen) {
7860 APValue Char;
7861 if (!handleLValueToRValueConversion(Info, E, CharTy, String, Char) ||
7862 !Char.isInt())
7863 return false;
7864 if (!Char.getInt())
7865 return Success(Strlen, E);
7866 if (!HandleLValueArrayAdjustment(Info, E, String, CharTy, 1))
7867 return false;
7868 }
7869 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007870
Richard Smithe151bab2016-11-11 23:43:35 +00007871 case Builtin::BIstrcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007872 case Builtin::BIwcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007873 case Builtin::BIstrncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007874 case Builtin::BIwcsncmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007875 case Builtin::BImemcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007876 case Builtin::BIwmemcmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007877 // A call to strlen is not a constant expression.
7878 if (Info.getLangOpts().CPlusPlus11)
7879 Info.CCEDiag(E, diag::note_constexpr_invalid_function)
7880 << /*isConstexpr*/0 << /*isConstructor*/0
Richard Smith8110c9d2016-11-29 19:45:17 +00007881 << (std::string("'") + Info.Ctx.BuiltinInfo.getName(BuiltinOp) + "'");
Richard Smithe151bab2016-11-11 23:43:35 +00007882 else
7883 Info.CCEDiag(E, diag::note_invalid_subexpr_in_const_expr);
7884 // Fall through.
7885 case Builtin::BI__builtin_strcmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007886 case Builtin::BI__builtin_wcscmp:
Richard Smithe151bab2016-11-11 23:43:35 +00007887 case Builtin::BI__builtin_strncmp:
Richard Smith8110c9d2016-11-29 19:45:17 +00007888 case Builtin::BI__builtin_wcsncmp:
7889 case Builtin::BI__builtin_memcmp:
7890 case Builtin::BI__builtin_wmemcmp: {
Richard Smithe151bab2016-11-11 23:43:35 +00007891 LValue String1, String2;
7892 if (!EvaluatePointer(E->getArg(0), String1, Info) ||
7893 !EvaluatePointer(E->getArg(1), String2, Info))
7894 return false;
Richard Smith8110c9d2016-11-29 19:45:17 +00007895
7896 QualType CharTy = E->getArg(0)->getType()->getPointeeType();
7897
Richard Smithe151bab2016-11-11 23:43:35 +00007898 uint64_t MaxLength = uint64_t(-1);
7899 if (BuiltinOp != Builtin::BIstrcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007900 BuiltinOp != Builtin::BIwcscmp &&
7901 BuiltinOp != Builtin::BI__builtin_strcmp &&
7902 BuiltinOp != Builtin::BI__builtin_wcscmp) {
Richard Smithe151bab2016-11-11 23:43:35 +00007903 APSInt N;
7904 if (!EvaluateInteger(E->getArg(2), N, Info))
7905 return false;
7906 MaxLength = N.getExtValue();
7907 }
7908 bool StopAtNull = (BuiltinOp != Builtin::BImemcmp &&
Richard Smith8110c9d2016-11-29 19:45:17 +00007909 BuiltinOp != Builtin::BIwmemcmp &&
7910 BuiltinOp != Builtin::BI__builtin_memcmp &&
7911 BuiltinOp != Builtin::BI__builtin_wmemcmp);
Richard Smithe151bab2016-11-11 23:43:35 +00007912 for (; MaxLength; --MaxLength) {
7913 APValue Char1, Char2;
7914 if (!handleLValueToRValueConversion(Info, E, CharTy, String1, Char1) ||
7915 !handleLValueToRValueConversion(Info, E, CharTy, String2, Char2) ||
7916 !Char1.isInt() || !Char2.isInt())
7917 return false;
7918 if (Char1.getInt() != Char2.getInt())
7919 return Success(Char1.getInt() < Char2.getInt() ? -1 : 1, E);
7920 if (StopAtNull && !Char1.getInt())
7921 return Success(0, E);
7922 assert(!(StopAtNull && !Char2.getInt()));
7923 if (!HandleLValueArrayAdjustment(Info, E, String1, CharTy, 1) ||
7924 !HandleLValueArrayAdjustment(Info, E, String2, CharTy, 1))
7925 return false;
7926 }
7927 // We hit the strncmp / memcmp limit.
7928 return Success(0, E);
7929 }
7930
Richard Smith01ba47d2012-04-13 00:45:38 +00007931 case Builtin::BI__atomic_always_lock_free:
Richard Smithb1e36c62012-04-11 17:55:32 +00007932 case Builtin::BI__atomic_is_lock_free:
7933 case Builtin::BI__c11_atomic_is_lock_free: {
Eli Friedmana4c26022011-10-17 21:44:23 +00007934 APSInt SizeVal;
7935 if (!EvaluateInteger(E->getArg(0), SizeVal, Info))
7936 return false;
7937
7938 // For __atomic_is_lock_free(sizeof(_Atomic(T))), if the size is a power
7939 // of two less than the maximum inline atomic width, we know it is
7940 // lock-free. If the size isn't a power of two, or greater than the
7941 // maximum alignment where we promote atomics, we know it is not lock-free
7942 // (at least not in the sense of atomic_is_lock_free). Otherwise,
7943 // the answer can only be determined at runtime; for example, 16-byte
7944 // atomics have lock-free implementations on some, but not all,
7945 // x86-64 processors.
7946
7947 // Check power-of-two.
7948 CharUnits Size = CharUnits::fromQuantity(SizeVal.getZExtValue());
Richard Smith01ba47d2012-04-13 00:45:38 +00007949 if (Size.isPowerOfTwo()) {
7950 // Check against inlining width.
7951 unsigned InlineWidthBits =
7952 Info.Ctx.getTargetInfo().getMaxAtomicInlineWidth();
7953 if (Size <= Info.Ctx.toCharUnitsFromBits(InlineWidthBits)) {
7954 if (BuiltinOp == Builtin::BI__c11_atomic_is_lock_free ||
7955 Size == CharUnits::One() ||
7956 E->getArg(1)->isNullPointerConstant(Info.Ctx,
7957 Expr::NPC_NeverValueDependent))
7958 // OK, we will inline appropriately-aligned operations of this size,
7959 // and _Atomic(T) is appropriately-aligned.
7960 return Success(1, E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007961
Richard Smith01ba47d2012-04-13 00:45:38 +00007962 QualType PointeeType = E->getArg(1)->IgnoreImpCasts()->getType()->
7963 castAs<PointerType>()->getPointeeType();
7964 if (!PointeeType->isIncompleteType() &&
7965 Info.Ctx.getTypeAlignInChars(PointeeType) >= Size) {
7966 // OK, we will inline operations on this object.
7967 return Success(1, E);
7968 }
7969 }
7970 }
Eli Friedmana4c26022011-10-17 21:44:23 +00007971
Richard Smith01ba47d2012-04-13 00:45:38 +00007972 return BuiltinOp == Builtin::BI__atomic_always_lock_free ?
7973 Success(0, E) : Error(E);
Eli Friedmana4c26022011-10-17 21:44:23 +00007974 }
Jonas Hahnfeld23604a82017-10-17 14:28:14 +00007975 case Builtin::BIomp_is_initial_device:
7976 // We can decide statically which value the runtime would return if called.
7977 return Success(Info.getLangOpts().OpenMPIsDevice ? 0 : 1, E);
Chris Lattner4deaa4e2008-10-06 05:28:25 +00007978 }
Chris Lattner7174bf32008-07-12 00:38:25 +00007979}
Anders Carlsson4a3585b2008-07-08 15:34:11 +00007980
Richard Smith8b3497e2011-10-31 01:37:14 +00007981static bool HasSameBase(const LValue &A, const LValue &B) {
7982 if (!A.getLValueBase())
7983 return !B.getLValueBase();
7984 if (!B.getLValueBase())
7985 return false;
7986
Richard Smithce40ad62011-11-12 22:28:03 +00007987 if (A.getLValueBase().getOpaqueValue() !=
7988 B.getLValueBase().getOpaqueValue()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00007989 const Decl *ADecl = GetLValueBaseDecl(A);
7990 if (!ADecl)
7991 return false;
7992 const Decl *BDecl = GetLValueBaseDecl(B);
Richard Smith80815602011-11-07 05:07:52 +00007993 if (!BDecl || ADecl->getCanonicalDecl() != BDecl->getCanonicalDecl())
Richard Smith8b3497e2011-10-31 01:37:14 +00007994 return false;
7995 }
7996
7997 return IsGlobalLValue(A.getLValueBase()) ||
Richard Smithb228a862012-02-15 02:18:13 +00007998 A.getLValueCallIndex() == B.getLValueCallIndex();
Richard Smith8b3497e2011-10-31 01:37:14 +00007999}
8000
Richard Smithd20f1e62014-10-21 23:01:04 +00008001/// \brief Determine whether this is a pointer past the end of the complete
8002/// object referred to by the lvalue.
8003static bool isOnePastTheEndOfCompleteObject(const ASTContext &Ctx,
8004 const LValue &LV) {
8005 // A null pointer can be viewed as being "past the end" but we don't
8006 // choose to look at it that way here.
8007 if (!LV.getLValueBase())
8008 return false;
8009
8010 // If the designator is valid and refers to a subobject, we're not pointing
8011 // past the end.
8012 if (!LV.getLValueDesignator().Invalid &&
8013 !LV.getLValueDesignator().isOnePastTheEnd())
8014 return false;
8015
David Majnemerc378ca52015-08-29 08:32:55 +00008016 // A pointer to an incomplete type might be past-the-end if the type's size is
8017 // zero. We cannot tell because the type is incomplete.
8018 QualType Ty = getType(LV.getLValueBase());
8019 if (Ty->isIncompleteType())
8020 return true;
8021
Richard Smithd20f1e62014-10-21 23:01:04 +00008022 // We're a past-the-end pointer if we point to the byte after the object,
8023 // no matter what our type or path is.
David Majnemerc378ca52015-08-29 08:32:55 +00008024 auto Size = Ctx.getTypeSizeInChars(Ty);
Richard Smithd20f1e62014-10-21 23:01:04 +00008025 return LV.getLValueOffset() == Size;
8026}
8027
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008028namespace {
Richard Smith11562c52011-10-28 17:51:58 +00008029
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008030/// \brief Data recursive integer evaluator of certain binary operators.
8031///
8032/// We use a data recursive algorithm for binary operators so that we are able
8033/// to handle extreme cases of chained binary operators without causing stack
8034/// overflow.
8035class DataRecursiveIntBinOpEvaluator {
8036 struct EvalResult {
8037 APValue Val;
8038 bool Failed;
8039
8040 EvalResult() : Failed(false) { }
8041
8042 void swap(EvalResult &RHS) {
8043 Val.swap(RHS.Val);
8044 Failed = RHS.Failed;
8045 RHS.Failed = false;
8046 }
8047 };
8048
8049 struct Job {
8050 const Expr *E;
8051 EvalResult LHSResult; // meaningful only for binary operator expression.
8052 enum { AnyExprKind, BinOpKind, BinOpVisitedLHSKind } Kind;
Craig Topper36250ad2014-05-12 05:36:57 +00008053
David Blaikie73726062015-08-12 23:09:24 +00008054 Job() = default;
Benjamin Kramer33e97602016-10-21 18:55:07 +00008055 Job(Job &&) = default;
David Blaikie73726062015-08-12 23:09:24 +00008056
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008057 void startSpeculativeEval(EvalInfo &Info) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008058 SpecEvalRAII = SpeculativeEvaluationRAII(Info);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008059 }
George Burgess IV8c892b52016-05-25 22:31:54 +00008060
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008061 private:
George Burgess IV8c892b52016-05-25 22:31:54 +00008062 SpeculativeEvaluationRAII SpecEvalRAII;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008063 };
8064
8065 SmallVector<Job, 16> Queue;
8066
8067 IntExprEvaluator &IntEval;
8068 EvalInfo &Info;
8069 APValue &FinalResult;
8070
8071public:
8072 DataRecursiveIntBinOpEvaluator(IntExprEvaluator &IntEval, APValue &Result)
8073 : IntEval(IntEval), Info(IntEval.getEvalInfo()), FinalResult(Result) { }
8074
8075 /// \brief True if \param E is a binary operator that we are going to handle
8076 /// data recursively.
8077 /// We handle binary operators that are comma, logical, or that have operands
8078 /// with integral or enumeration type.
8079 static bool shouldEnqueue(const BinaryOperator *E) {
8080 return E->getOpcode() == BO_Comma ||
8081 E->isLogicalOp() ||
Richard Smith3a09d8b2016-06-04 00:22:31 +00008082 (E->isRValue() &&
8083 E->getType()->isIntegralOrEnumerationType() &&
8084 E->getLHS()->getType()->isIntegralOrEnumerationType() &&
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008085 E->getRHS()->getType()->isIntegralOrEnumerationType());
Eli Friedman5a332ea2008-11-13 06:09:17 +00008086 }
8087
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008088 bool Traverse(const BinaryOperator *E) {
8089 enqueue(E);
8090 EvalResult PrevResult;
Richard Trieuba4d0872012-03-21 23:30:30 +00008091 while (!Queue.empty())
8092 process(PrevResult);
8093
8094 if (PrevResult.Failed) return false;
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008095
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008096 FinalResult.swap(PrevResult.Val);
8097 return true;
8098 }
8099
8100private:
8101 bool Success(uint64_t Value, const Expr *E, APValue &Result) {
8102 return IntEval.Success(Value, E, Result);
8103 }
8104 bool Success(const APSInt &Value, const Expr *E, APValue &Result) {
8105 return IntEval.Success(Value, E, Result);
8106 }
8107 bool Error(const Expr *E) {
8108 return IntEval.Error(E);
8109 }
8110 bool Error(const Expr *E, diag::kind D) {
8111 return IntEval.Error(E, D);
8112 }
8113
8114 OptionalDiagnostic CCEDiag(const Expr *E, diag::kind D) {
8115 return Info.CCEDiag(E, D);
8116 }
8117
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008118 // \brief Returns true if visiting the RHS is necessary, false otherwise.
8119 bool VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008120 bool &SuppressRHSDiags);
8121
8122 bool VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8123 const BinaryOperator *E, APValue &Result);
8124
8125 void EvaluateExpr(const Expr *E, EvalResult &Result) {
8126 Result.Failed = !Evaluate(Result.Val, Info, E);
8127 if (Result.Failed)
8128 Result.Val = APValue();
8129 }
8130
Richard Trieuba4d0872012-03-21 23:30:30 +00008131 void process(EvalResult &Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008132
8133 void enqueue(const Expr *E) {
8134 E = E->IgnoreParens();
8135 Queue.resize(Queue.size()+1);
8136 Queue.back().E = E;
8137 Queue.back().Kind = Job::AnyExprKind;
8138 }
8139};
8140
Alexander Kornienkoab9db512015-06-22 23:07:51 +00008141}
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008142
8143bool DataRecursiveIntBinOpEvaluator::
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008144 VisitBinOpLHSOnly(EvalResult &LHSResult, const BinaryOperator *E,
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008145 bool &SuppressRHSDiags) {
8146 if (E->getOpcode() == BO_Comma) {
8147 // Ignore LHS but note if we could not evaluate it.
8148 if (LHSResult.Failed)
Richard Smith4e66f1f2013-11-06 02:19:10 +00008149 return Info.noteSideEffect();
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008150 return true;
8151 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008152
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008153 if (E->isLogicalOp()) {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008154 bool LHSAsBool;
8155 if (!LHSResult.Failed && HandleConversionToBool(LHSResult.Val, LHSAsBool)) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008156 // We were able to evaluate the LHS, see if we can get away with not
8157 // evaluating the RHS: 0 && X -> 0, 1 || X -> 1
Richard Smith4e66f1f2013-11-06 02:19:10 +00008158 if (LHSAsBool == (E->getOpcode() == BO_LOr)) {
8159 Success(LHSAsBool, E, LHSResult.Val);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008160 return false; // Ignore RHS
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008161 }
8162 } else {
Richard Smith4e66f1f2013-11-06 02:19:10 +00008163 LHSResult.Failed = true;
8164
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008165 // Since we weren't able to evaluate the left hand side, it
George Burgess IV8c892b52016-05-25 22:31:54 +00008166 // might have had side effects.
Richard Smith4e66f1f2013-11-06 02:19:10 +00008167 if (!Info.noteSideEffect())
8168 return false;
8169
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008170 // We can't evaluate the LHS; however, sometimes the result
8171 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8172 // Don't ignore RHS and suppress diagnostics from this arm.
8173 SuppressRHSDiags = true;
8174 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008175
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008176 return true;
8177 }
Richard Smith4e66f1f2013-11-06 02:19:10 +00008178
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008179 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8180 E->getRHS()->getType()->isIntegralOrEnumerationType());
Richard Smith4e66f1f2013-11-06 02:19:10 +00008181
George Burgess IVa145e252016-05-25 22:38:36 +00008182 if (LHSResult.Failed && !Info.noteFailure())
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008183 return false; // Ignore RHS;
8184
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008185 return true;
8186}
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008187
Benjamin Kramerf6021ec2017-03-21 21:35:04 +00008188static void addOrSubLValueAsInteger(APValue &LVal, const APSInt &Index,
8189 bool IsSub) {
Richard Smithd6cc1982017-01-31 02:23:02 +00008190 // Compute the new offset in the appropriate width, wrapping at 64 bits.
8191 // FIXME: When compiling for a 32-bit target, we should use 32-bit
8192 // offsets.
8193 assert(!LVal.hasLValuePath() && "have designator for integer lvalue");
8194 CharUnits &Offset = LVal.getLValueOffset();
8195 uint64_t Offset64 = Offset.getQuantity();
8196 uint64_t Index64 = Index.extOrTrunc(64).getZExtValue();
8197 Offset = CharUnits::fromQuantity(IsSub ? Offset64 - Index64
8198 : Offset64 + Index64);
8199}
8200
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008201bool DataRecursiveIntBinOpEvaluator::
8202 VisitBinOp(const EvalResult &LHSResult, const EvalResult &RHSResult,
8203 const BinaryOperator *E, APValue &Result) {
8204 if (E->getOpcode() == BO_Comma) {
8205 if (RHSResult.Failed)
8206 return false;
8207 Result = RHSResult.Val;
8208 return true;
8209 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008210
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008211 if (E->isLogicalOp()) {
8212 bool lhsResult, rhsResult;
8213 bool LHSIsOK = HandleConversionToBool(LHSResult.Val, lhsResult);
8214 bool RHSIsOK = HandleConversionToBool(RHSResult.Val, rhsResult);
Daniel Jasperffdee092017-05-02 19:21:42 +00008215
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008216 if (LHSIsOK) {
8217 if (RHSIsOK) {
8218 if (E->getOpcode() == BO_LOr)
8219 return Success(lhsResult || rhsResult, E, Result);
8220 else
8221 return Success(lhsResult && rhsResult, E, Result);
8222 }
8223 } else {
8224 if (RHSIsOK) {
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008225 // We can't evaluate the LHS; however, sometimes the result
8226 // is determined by the RHS: X && 0 -> 0, X || 1 -> 1.
8227 if (rhsResult == (E->getOpcode() == BO_LOr))
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008228 return Success(rhsResult, E, Result);
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008229 }
8230 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008231
Argyrios Kyrtzidis8d4677a2012-02-25 23:21:37 +00008232 return false;
8233 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008234
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008235 assert(E->getLHS()->getType()->isIntegralOrEnumerationType() &&
8236 E->getRHS()->getType()->isIntegralOrEnumerationType());
Daniel Jasperffdee092017-05-02 19:21:42 +00008237
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008238 if (LHSResult.Failed || RHSResult.Failed)
8239 return false;
Daniel Jasperffdee092017-05-02 19:21:42 +00008240
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008241 const APValue &LHSVal = LHSResult.Val;
8242 const APValue &RHSVal = RHSResult.Val;
Daniel Jasperffdee092017-05-02 19:21:42 +00008243
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008244 // Handle cases like (unsigned long)&a + 4.
8245 if (E->isAdditiveOp() && LHSVal.isLValue() && RHSVal.isInt()) {
8246 Result = LHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008247 addOrSubLValueAsInteger(Result, RHSVal.getInt(), E->getOpcode() == BO_Sub);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008248 return true;
8249 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008250
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008251 // Handle cases like 4 + (unsigned long)&a
8252 if (E->getOpcode() == BO_Add &&
8253 RHSVal.isLValue() && LHSVal.isInt()) {
8254 Result = RHSVal;
Richard Smithd6cc1982017-01-31 02:23:02 +00008255 addOrSubLValueAsInteger(Result, LHSVal.getInt(), /*IsSub*/false);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008256 return true;
8257 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008258
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008259 if (E->getOpcode() == BO_Sub && LHSVal.isLValue() && RHSVal.isLValue()) {
8260 // Handle (intptr_t)&&A - (intptr_t)&&B.
8261 if (!LHSVal.getLValueOffset().isZero() ||
8262 !RHSVal.getLValueOffset().isZero())
8263 return false;
8264 const Expr *LHSExpr = LHSVal.getLValueBase().dyn_cast<const Expr*>();
8265 const Expr *RHSExpr = RHSVal.getLValueBase().dyn_cast<const Expr*>();
8266 if (!LHSExpr || !RHSExpr)
8267 return false;
8268 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8269 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8270 if (!LHSAddrExpr || !RHSAddrExpr)
8271 return false;
8272 // Make sure both labels come from the same function.
8273 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8274 RHSAddrExpr->getLabel()->getDeclContext())
8275 return false;
8276 Result = APValue(LHSAddrExpr, RHSAddrExpr);
8277 return true;
8278 }
Richard Smith43e77732013-05-07 04:50:00 +00008279
8280 // All the remaining cases expect both operands to be an integer
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008281 if (!LHSVal.isInt() || !RHSVal.isInt())
8282 return Error(E);
Richard Smith43e77732013-05-07 04:50:00 +00008283
8284 // Set up the width and signedness manually, in case it can't be deduced
8285 // from the operation we're performing.
8286 // FIXME: Don't do this in the cases where we can deduce it.
8287 APSInt Value(Info.Ctx.getIntWidth(E->getType()),
8288 E->getType()->isUnsignedIntegerOrEnumerationType());
8289 if (!handleIntIntBinOp(Info, E, LHSVal.getInt(), E->getOpcode(),
8290 RHSVal.getInt(), Value))
8291 return false;
8292 return Success(Value, E, Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008293}
8294
Richard Trieuba4d0872012-03-21 23:30:30 +00008295void DataRecursiveIntBinOpEvaluator::process(EvalResult &Result) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008296 Job &job = Queue.back();
Daniel Jasperffdee092017-05-02 19:21:42 +00008297
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008298 switch (job.Kind) {
8299 case Job::AnyExprKind: {
8300 if (const BinaryOperator *Bop = dyn_cast<BinaryOperator>(job.E)) {
8301 if (shouldEnqueue(Bop)) {
8302 job.Kind = Job::BinOpKind;
8303 enqueue(Bop->getLHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008304 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008305 }
8306 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008307
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008308 EvaluateExpr(job.E, Result);
8309 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008310 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008311 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008312
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008313 case Job::BinOpKind: {
8314 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008315 bool SuppressRHSDiags = false;
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008316 if (!VisitBinOpLHSOnly(Result, Bop, SuppressRHSDiags)) {
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008317 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008318 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008319 }
8320 if (SuppressRHSDiags)
8321 job.startSpeculativeEval(Info);
Argyrios Kyrtzidis5957b702012-03-22 02:13:06 +00008322 job.LHSResult.swap(Result);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008323 job.Kind = Job::BinOpVisitedLHSKind;
8324 enqueue(Bop->getRHS());
Richard Trieuba4d0872012-03-21 23:30:30 +00008325 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008326 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008327
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008328 case Job::BinOpVisitedLHSKind: {
8329 const BinaryOperator *Bop = cast<BinaryOperator>(job.E);
8330 EvalResult RHS;
8331 RHS.swap(Result);
Richard Trieuba4d0872012-03-21 23:30:30 +00008332 Result.Failed = !VisitBinOp(job.LHSResult, RHS, Bop, Result.Val);
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008333 Queue.pop_back();
Richard Trieuba4d0872012-03-21 23:30:30 +00008334 return;
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008335 }
8336 }
Daniel Jasperffdee092017-05-02 19:21:42 +00008337
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008338 llvm_unreachable("Invalid Job::Kind!");
8339}
8340
George Burgess IV8c892b52016-05-25 22:31:54 +00008341namespace {
8342/// Used when we determine that we should fail, but can keep evaluating prior to
8343/// noting that we had a failure.
8344class DelayedNoteFailureRAII {
8345 EvalInfo &Info;
8346 bool NoteFailure;
8347
8348public:
8349 DelayedNoteFailureRAII(EvalInfo &Info, bool NoteFailure = true)
8350 : Info(Info), NoteFailure(NoteFailure) {}
8351 ~DelayedNoteFailureRAII() {
8352 if (NoteFailure) {
8353 bool ContinueAfterFailure = Info.noteFailure();
8354 (void)ContinueAfterFailure;
8355 assert(ContinueAfterFailure &&
8356 "Shouldn't have kept evaluating on failure.");
8357 }
8358 }
8359};
8360}
8361
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008362bool IntExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
George Burgess IV8c892b52016-05-25 22:31:54 +00008363 // We don't call noteFailure immediately because the assignment happens after
8364 // we evaluate LHS and RHS.
Josh Magee4d1a79b2015-02-04 21:50:20 +00008365 if (!Info.keepEvaluatingAfterFailure() && E->isAssignmentOp())
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008366 return Error(E);
8367
George Burgess IV8c892b52016-05-25 22:31:54 +00008368 DelayedNoteFailureRAII MaybeNoteFailureLater(Info, E->isAssignmentOp());
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008369 if (DataRecursiveIntBinOpEvaluator::shouldEnqueue(E))
8370 return DataRecursiveIntBinOpEvaluator(*this, Result).Traverse(E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008371
Anders Carlssonacc79812008-11-16 07:17:21 +00008372 QualType LHSTy = E->getLHS()->getType();
8373 QualType RHSTy = E->getRHS()->getType();
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008374
Chandler Carruthb29a7432014-10-11 11:03:30 +00008375 if (LHSTy->isAnyComplexType() || RHSTy->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00008376 ComplexValue LHS, RHS;
Chandler Carruthb29a7432014-10-11 11:03:30 +00008377 bool LHSOK;
Josh Magee4d1a79b2015-02-04 21:50:20 +00008378 if (E->isAssignmentOp()) {
8379 LValue LV;
8380 EvaluateLValue(E->getLHS(), LV, Info);
8381 LHSOK = false;
8382 } else if (LHSTy->isRealFloatingType()) {
Chandler Carruthb29a7432014-10-11 11:03:30 +00008383 LHSOK = EvaluateFloat(E->getLHS(), LHS.FloatReal, Info);
8384 if (LHSOK) {
8385 LHS.makeComplexFloat();
8386 LHS.FloatImag = APFloat(LHS.FloatReal.getSemantics());
8387 }
8388 } else {
8389 LHSOK = EvaluateComplex(E->getLHS(), LHS, Info);
8390 }
George Burgess IVa145e252016-05-25 22:38:36 +00008391 if (!LHSOK && !Info.noteFailure())
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008392 return false;
8393
Chandler Carruthb29a7432014-10-11 11:03:30 +00008394 if (E->getRHS()->getType()->isRealFloatingType()) {
8395 if (!EvaluateFloat(E->getRHS(), RHS.FloatReal, Info) || !LHSOK)
8396 return false;
8397 RHS.makeComplexFloat();
8398 RHS.FloatImag = APFloat(RHS.FloatReal.getSemantics());
8399 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008400 return false;
8401
8402 if (LHS.isComplexFloat()) {
Mike Stump11289f42009-09-09 15:08:12 +00008403 APFloat::cmpResult CR_r =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008404 LHS.getComplexFloatReal().compare(RHS.getComplexFloatReal());
Mike Stump11289f42009-09-09 15:08:12 +00008405 APFloat::cmpResult CR_i =
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008406 LHS.getComplexFloatImag().compare(RHS.getComplexFloatImag());
8407
John McCalle3027922010-08-25 11:45:40 +00008408 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008409 return Success((CR_r == APFloat::cmpEqual &&
8410 CR_i == APFloat::cmpEqual), E);
8411 else {
John McCalle3027922010-08-25 11:45:40 +00008412 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008413 "Invalid complex comparison.");
Mike Stump11289f42009-09-09 15:08:12 +00008414 return Success(((CR_r == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008415 CR_r == APFloat::cmpLessThan ||
8416 CR_r == APFloat::cmpUnordered) ||
Mike Stump11289f42009-09-09 15:08:12 +00008417 (CR_i == APFloat::cmpGreaterThan ||
Mon P Wang75c645c2010-04-29 05:53:29 +00008418 CR_i == APFloat::cmpLessThan ||
8419 CR_i == APFloat::cmpUnordered)), E);
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008420 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008421 } else {
John McCalle3027922010-08-25 11:45:40 +00008422 if (E->getOpcode() == BO_EQ)
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008423 return Success((LHS.getComplexIntReal() == RHS.getComplexIntReal() &&
8424 LHS.getComplexIntImag() == RHS.getComplexIntImag()), E);
8425 else {
John McCalle3027922010-08-25 11:45:40 +00008426 assert(E->getOpcode() == BO_NE &&
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008427 "Invalid compex comparison.");
8428 return Success((LHS.getComplexIntReal() != RHS.getComplexIntReal() ||
8429 LHS.getComplexIntImag() != RHS.getComplexIntImag()), E);
8430 }
Daniel Dunbar74f2425b2009-01-29 06:43:41 +00008431 }
8432 }
Mike Stump11289f42009-09-09 15:08:12 +00008433
Anders Carlssonacc79812008-11-16 07:17:21 +00008434 if (LHSTy->isRealFloatingType() &&
8435 RHSTy->isRealFloatingType()) {
8436 APFloat RHS(0.0), LHS(0.0);
Mike Stump11289f42009-09-09 15:08:12 +00008437
Richard Smith253c2a32012-01-27 01:14:48 +00008438 bool LHSOK = EvaluateFloat(E->getRHS(), RHS, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008439 if (!LHSOK && !Info.noteFailure())
Anders Carlssonacc79812008-11-16 07:17:21 +00008440 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008441
Richard Smith253c2a32012-01-27 01:14:48 +00008442 if (!EvaluateFloat(E->getLHS(), LHS, Info) || !LHSOK)
Anders Carlssonacc79812008-11-16 07:17:21 +00008443 return false;
Mike Stump11289f42009-09-09 15:08:12 +00008444
Anders Carlssonacc79812008-11-16 07:17:21 +00008445 APFloat::cmpResult CR = LHS.compare(RHS);
Anders Carlsson899c7052008-11-16 22:46:56 +00008446
Anders Carlssonacc79812008-11-16 07:17:21 +00008447 switch (E->getOpcode()) {
8448 default:
David Blaikie83d382b2011-09-23 05:06:16 +00008449 llvm_unreachable("Invalid binary operator!");
John McCalle3027922010-08-25 11:45:40 +00008450 case BO_LT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008451 return Success(CR == APFloat::cmpLessThan, E);
John McCalle3027922010-08-25 11:45:40 +00008452 case BO_GT:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008453 return Success(CR == APFloat::cmpGreaterThan, E);
John McCalle3027922010-08-25 11:45:40 +00008454 case BO_LE:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008455 return Success(CR == APFloat::cmpLessThan || CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008456 case BO_GE:
Mike Stump11289f42009-09-09 15:08:12 +00008457 return Success(CR == APFloat::cmpGreaterThan || CR == APFloat::cmpEqual,
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008458 E);
John McCalle3027922010-08-25 11:45:40 +00008459 case BO_EQ:
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008460 return Success(CR == APFloat::cmpEqual, E);
John McCalle3027922010-08-25 11:45:40 +00008461 case BO_NE:
Mike Stump11289f42009-09-09 15:08:12 +00008462 return Success(CR == APFloat::cmpGreaterThan
Mon P Wang75c645c2010-04-29 05:53:29 +00008463 || CR == APFloat::cmpLessThan
8464 || CR == APFloat::cmpUnordered, E);
Anders Carlssonacc79812008-11-16 07:17:21 +00008465 }
Anders Carlssonacc79812008-11-16 07:17:21 +00008466 }
Mike Stump11289f42009-09-09 15:08:12 +00008467
Eli Friedmana38da572009-04-28 19:17:36 +00008468 if (LHSTy->isPointerType() && RHSTy->isPointerType()) {
Richard Smith8b3497e2011-10-31 01:37:14 +00008469 if (E->getOpcode() == BO_Sub || E->isComparisonOp()) {
Richard Smith253c2a32012-01-27 01:14:48 +00008470 LValue LHSValue, RHSValue;
8471
8472 bool LHSOK = EvaluatePointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008473 if (!LHSOK && !Info.noteFailure())
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008474 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008475
Richard Smith253c2a32012-01-27 01:14:48 +00008476 if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008477 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008478
Richard Smith8b3497e2011-10-31 01:37:14 +00008479 // Reject differing bases from the normal codepath; we special-case
8480 // comparisons to null.
8481 if (!HasSameBase(LHSValue, RHSValue)) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008482 if (E->getOpcode() == BO_Sub) {
8483 // Handle &&A - &&B.
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008484 if (!LHSValue.Offset.isZero() || !RHSValue.Offset.isZero())
Richard Smith0c6124b2015-12-03 01:36:22 +00008485 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008486 const Expr *LHSExpr = LHSValue.Base.dyn_cast<const Expr*>();
Benjamin Kramerdaa096122012-10-03 14:15:39 +00008487 const Expr *RHSExpr = RHSValue.Base.dyn_cast<const Expr*>();
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008488 if (!LHSExpr || !RHSExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008489 return Error(E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008490 const AddrLabelExpr *LHSAddrExpr = dyn_cast<AddrLabelExpr>(LHSExpr);
8491 const AddrLabelExpr *RHSAddrExpr = dyn_cast<AddrLabelExpr>(RHSExpr);
8492 if (!LHSAddrExpr || !RHSAddrExpr)
Richard Smith0c6124b2015-12-03 01:36:22 +00008493 return Error(E);
Eli Friedmanb1bc3682012-01-05 23:59:40 +00008494 // Make sure both labels come from the same function.
8495 if (LHSAddrExpr->getLabel()->getDeclContext() !=
8496 RHSAddrExpr->getLabel()->getDeclContext())
Richard Smith0c6124b2015-12-03 01:36:22 +00008497 return Error(E);
8498 return Success(APValue(LHSAddrExpr, RHSAddrExpr), E);
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008499 }
Richard Smith83c68212011-10-31 05:11:32 +00008500 // Inequalities and subtractions between unrelated pointers have
8501 // unspecified or undefined behavior.
Eli Friedman334046a2009-06-14 02:17:33 +00008502 if (!E->isEqualityOp())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008503 return Error(E);
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008504 // A constant address may compare equal to the address of a symbol.
8505 // The one exception is that address of an object cannot compare equal
Eli Friedman42fbd622011-10-31 22:54:30 +00008506 // to a null pointer constant.
Eli Friedmanc6be94b2011-10-31 22:28:05 +00008507 if ((!LHSValue.Base && !LHSValue.Offset.isZero()) ||
8508 (!RHSValue.Base && !RHSValue.Offset.isZero()))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008509 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008510 // It's implementation-defined whether distinct literals will have
Richard Smith7bb00672012-02-01 01:42:44 +00008511 // distinct addresses. In clang, the result of such a comparison is
8512 // unspecified, so it is not a constant expression. However, we do know
8513 // that the address of a literal will be non-null.
Richard Smithe9e20dd32011-11-04 01:10:57 +00008514 if ((IsLiteralLValue(LHSValue) || IsLiteralLValue(RHSValue)) &&
8515 LHSValue.Base && RHSValue.Base)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008516 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008517 // We can't tell whether weak symbols will end up pointing to the same
8518 // object.
8519 if (IsWeakLValue(LHSValue) || IsWeakLValue(RHSValue))
Richard Smithf57d8cb2011-12-09 22:58:01 +00008520 return Error(E);
Richard Smithd20f1e62014-10-21 23:01:04 +00008521 // We can't compare the address of the start of one object with the
8522 // past-the-end address of another object, per C++ DR1652.
8523 if ((LHSValue.Base && LHSValue.Offset.isZero() &&
8524 isOnePastTheEndOfCompleteObject(Info.Ctx, RHSValue)) ||
8525 (RHSValue.Base && RHSValue.Offset.isZero() &&
8526 isOnePastTheEndOfCompleteObject(Info.Ctx, LHSValue)))
8527 return Error(E);
David Majnemerb5116032014-12-09 23:32:34 +00008528 // We can't tell whether an object is at the same address as another
8529 // zero sized object.
David Majnemer27db3582014-12-11 19:36:24 +00008530 if ((RHSValue.Base && isZeroSized(LHSValue)) ||
8531 (LHSValue.Base && isZeroSized(RHSValue)))
David Majnemerb5116032014-12-09 23:32:34 +00008532 return Error(E);
Richard Smith83c68212011-10-31 05:11:32 +00008533 // Pointers with different bases cannot represent the same object.
Eli Friedman42fbd622011-10-31 22:54:30 +00008534 // (Note that clang defaults to -fmerge-all-constants, which can
8535 // lead to inconsistent results for comparisons involving the address
8536 // of a constant; this generally doesn't matter in practice.)
Richard Smith83c68212011-10-31 05:11:32 +00008537 return Success(E->getOpcode() == BO_NE, E);
Eli Friedman334046a2009-06-14 02:17:33 +00008538 }
Eli Friedman64004332009-03-23 04:38:34 +00008539
Richard Smith1b470412012-02-01 08:10:20 +00008540 const CharUnits &LHSOffset = LHSValue.getLValueOffset();
8541 const CharUnits &RHSOffset = RHSValue.getLValueOffset();
8542
Richard Smith84f6dcf2012-02-02 01:16:57 +00008543 SubobjectDesignator &LHSDesignator = LHSValue.getLValueDesignator();
8544 SubobjectDesignator &RHSDesignator = RHSValue.getLValueDesignator();
8545
John McCalle3027922010-08-25 11:45:40 +00008546 if (E->getOpcode() == BO_Sub) {
Richard Smith84f6dcf2012-02-02 01:16:57 +00008547 // C++11 [expr.add]p6:
8548 // Unless both pointers point to elements of the same array object, or
8549 // one past the last element of the array object, the behavior is
8550 // undefined.
8551 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8552 !AreElementsOfSameArray(getType(LHSValue.Base),
8553 LHSDesignator, RHSDesignator))
8554 CCEDiag(E, diag::note_constexpr_pointer_subtraction_not_same_array);
8555
Chris Lattner882bdf22010-04-20 17:13:14 +00008556 QualType Type = E->getLHS()->getType();
8557 QualType ElementType = Type->getAs<PointerType>()->getPointeeType();
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008558
Richard Smithd62306a2011-11-10 06:34:14 +00008559 CharUnits ElementSize;
Richard Smith17100ba2012-02-16 02:46:34 +00008560 if (!HandleSizeof(Info, E->getExprLoc(), ElementType, ElementSize))
Richard Smithd62306a2011-11-10 06:34:14 +00008561 return false;
Eli Friedman64004332009-03-23 04:38:34 +00008562
Richard Smith84c6b3d2013-09-10 21:34:14 +00008563 // As an extension, a type may have zero size (empty struct or union in
8564 // C, array of zero length). Pointer subtraction in such cases has
8565 // undefined behavior, so is not constant.
8566 if (ElementSize.isZero()) {
Faisal Valie690b7a2016-07-02 22:34:24 +00008567 Info.FFDiag(E, diag::note_constexpr_pointer_subtraction_zero_size)
Richard Smith84c6b3d2013-09-10 21:34:14 +00008568 << ElementType;
8569 return false;
8570 }
8571
Richard Smith1b470412012-02-01 08:10:20 +00008572 // FIXME: LLVM and GCC both compute LHSOffset - RHSOffset at runtime,
8573 // and produce incorrect results when it overflows. Such behavior
8574 // appears to be non-conforming, but is common, so perhaps we should
8575 // assume the standard intended for such cases to be undefined behavior
8576 // and check for them.
Richard Smith8b3497e2011-10-31 01:37:14 +00008577
Richard Smith1b470412012-02-01 08:10:20 +00008578 // Compute (LHSOffset - RHSOffset) / Size carefully, checking for
8579 // overflow in the final conversion to ptrdiff_t.
8580 APSInt LHS(
8581 llvm::APInt(65, (int64_t)LHSOffset.getQuantity(), true), false);
8582 APSInt RHS(
8583 llvm::APInt(65, (int64_t)RHSOffset.getQuantity(), true), false);
8584 APSInt ElemSize(
8585 llvm::APInt(65, (int64_t)ElementSize.getQuantity(), true), false);
8586 APSInt TrueResult = (LHS - RHS) / ElemSize;
8587 APSInt Result = TrueResult.trunc(Info.Ctx.getIntWidth(E->getType()));
8588
Richard Smith0c6124b2015-12-03 01:36:22 +00008589 if (Result.extend(65) != TrueResult &&
8590 !HandleOverflow(Info, E, TrueResult, E->getType()))
8591 return false;
Richard Smith1b470412012-02-01 08:10:20 +00008592 return Success(Result, E);
8593 }
Richard Smithde21b242012-01-31 06:41:30 +00008594
8595 // C++11 [expr.rel]p3:
8596 // Pointers to void (after pointer conversions) can be compared, with a
8597 // result defined as follows: If both pointers represent the same
8598 // address or are both the null pointer value, the result is true if the
8599 // operator is <= or >= and false otherwise; otherwise the result is
8600 // unspecified.
8601 // We interpret this as applying to pointers to *cv* void.
8602 if (LHSTy->isVoidPointerType() && LHSOffset != RHSOffset &&
Richard Smith84f6dcf2012-02-02 01:16:57 +00008603 E->isRelationalOp())
Richard Smithde21b242012-01-31 06:41:30 +00008604 CCEDiag(E, diag::note_constexpr_void_comparison);
8605
Richard Smith84f6dcf2012-02-02 01:16:57 +00008606 // C++11 [expr.rel]p2:
8607 // - If two pointers point to non-static data members of the same object,
8608 // or to subobjects or array elements fo such members, recursively, the
8609 // pointer to the later declared member compares greater provided the
8610 // two members have the same access control and provided their class is
8611 // not a union.
8612 // [...]
8613 // - Otherwise pointer comparisons are unspecified.
8614 if (!LHSDesignator.Invalid && !RHSDesignator.Invalid &&
8615 E->isRelationalOp()) {
8616 bool WasArrayIndex;
8617 unsigned Mismatch =
8618 FindDesignatorMismatch(getType(LHSValue.Base), LHSDesignator,
8619 RHSDesignator, WasArrayIndex);
8620 // At the point where the designators diverge, the comparison has a
8621 // specified value if:
8622 // - we are comparing array indices
8623 // - we are comparing fields of a union, or fields with the same access
8624 // Otherwise, the result is unspecified and thus the comparison is not a
8625 // constant expression.
8626 if (!WasArrayIndex && Mismatch < LHSDesignator.Entries.size() &&
8627 Mismatch < RHSDesignator.Entries.size()) {
8628 const FieldDecl *LF = getAsField(LHSDesignator.Entries[Mismatch]);
8629 const FieldDecl *RF = getAsField(RHSDesignator.Entries[Mismatch]);
8630 if (!LF && !RF)
8631 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_classes);
8632 else if (!LF)
8633 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8634 << getAsBaseClass(LHSDesignator.Entries[Mismatch])
8635 << RF->getParent() << RF;
8636 else if (!RF)
8637 CCEDiag(E, diag::note_constexpr_pointer_comparison_base_field)
8638 << getAsBaseClass(RHSDesignator.Entries[Mismatch])
8639 << LF->getParent() << LF;
8640 else if (!LF->getParent()->isUnion() &&
8641 LF->getAccess() != RF->getAccess())
8642 CCEDiag(E, diag::note_constexpr_pointer_comparison_differing_access)
8643 << LF << LF->getAccess() << RF << RF->getAccess()
8644 << LF->getParent();
8645 }
8646 }
8647
Eli Friedman6c31cb42012-04-16 04:30:08 +00008648 // The comparison here must be unsigned, and performed with the same
8649 // width as the pointer.
Eli Friedman6c31cb42012-04-16 04:30:08 +00008650 unsigned PtrSize = Info.Ctx.getTypeSize(LHSTy);
8651 uint64_t CompareLHS = LHSOffset.getQuantity();
8652 uint64_t CompareRHS = RHSOffset.getQuantity();
8653 assert(PtrSize <= 64 && "Unexpected pointer width");
8654 uint64_t Mask = ~0ULL >> (64 - PtrSize);
8655 CompareLHS &= Mask;
8656 CompareRHS &= Mask;
8657
Eli Friedman2f5b7c52012-04-16 19:23:57 +00008658 // If there is a base and this is a relational operator, we can only
8659 // compare pointers within the object in question; otherwise, the result
8660 // depends on where the object is located in memory.
8661 if (!LHSValue.Base.isNull() && E->isRelationalOp()) {
8662 QualType BaseTy = getType(LHSValue.Base);
8663 if (BaseTy->isIncompleteType())
8664 return Error(E);
8665 CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);
8666 uint64_t OffsetLimit = Size.getQuantity();
8667 if (CompareLHS > OffsetLimit || CompareRHS > OffsetLimit)
8668 return Error(E);
8669 }
8670
Richard Smith8b3497e2011-10-31 01:37:14 +00008671 switch (E->getOpcode()) {
8672 default: llvm_unreachable("missing comparison operator");
Eli Friedman6c31cb42012-04-16 04:30:08 +00008673 case BO_LT: return Success(CompareLHS < CompareRHS, E);
8674 case BO_GT: return Success(CompareLHS > CompareRHS, E);
8675 case BO_LE: return Success(CompareLHS <= CompareRHS, E);
8676 case BO_GE: return Success(CompareLHS >= CompareRHS, E);
8677 case BO_EQ: return Success(CompareLHS == CompareRHS, E);
8678 case BO_NE: return Success(CompareLHS != CompareRHS, E);
Eli Friedmana38da572009-04-28 19:17:36 +00008679 }
Anders Carlsson9f9e4242008-11-16 19:01:22 +00008680 }
8681 }
Richard Smith7bb00672012-02-01 01:42:44 +00008682
8683 if (LHSTy->isMemberPointerType()) {
8684 assert(E->isEqualityOp() && "unexpected member pointer operation");
8685 assert(RHSTy->isMemberPointerType() && "invalid comparison");
8686
8687 MemberPtr LHSValue, RHSValue;
8688
8689 bool LHSOK = EvaluateMemberPointer(E->getLHS(), LHSValue, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00008690 if (!LHSOK && !Info.noteFailure())
Richard Smith7bb00672012-02-01 01:42:44 +00008691 return false;
8692
8693 if (!EvaluateMemberPointer(E->getRHS(), RHSValue, Info) || !LHSOK)
8694 return false;
8695
8696 // C++11 [expr.eq]p2:
8697 // If both operands are null, they compare equal. Otherwise if only one is
8698 // null, they compare unequal.
8699 if (!LHSValue.getDecl() || !RHSValue.getDecl()) {
8700 bool Equal = !LHSValue.getDecl() && !RHSValue.getDecl();
8701 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8702 }
8703
8704 // Otherwise if either is a pointer to a virtual member function, the
8705 // result is unspecified.
8706 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(LHSValue.getDecl()))
8707 if (MD->isVirtual())
8708 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8709 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(RHSValue.getDecl()))
8710 if (MD->isVirtual())
8711 CCEDiag(E, diag::note_constexpr_compare_virtual_mem_ptr) << MD;
8712
8713 // Otherwise they compare equal if and only if they would refer to the
8714 // same member of the same most derived object or the same subobject if
8715 // they were dereferenced with a hypothetical object of the associated
8716 // class type.
8717 bool Equal = LHSValue == RHSValue;
8718 return Success(E->getOpcode() == BO_EQ ? Equal : !Equal, E);
8719 }
8720
Richard Smithab44d9b2012-02-14 22:35:28 +00008721 if (LHSTy->isNullPtrType()) {
8722 assert(E->isComparisonOp() && "unexpected nullptr operation");
8723 assert(RHSTy->isNullPtrType() && "missing pointer conversion");
8724 // C++11 [expr.rel]p4, [expr.eq]p3: If two operands of type std::nullptr_t
8725 // are compared, the result is true of the operator is <=, >= or ==, and
8726 // false otherwise.
8727 BinaryOperator::Opcode Opcode = E->getOpcode();
8728 return Success(Opcode == BO_EQ || Opcode == BO_LE || Opcode == BO_GE, E);
8729 }
8730
Argyrios Kyrtzidis57595e42012-03-15 18:07:16 +00008731 assert((!LHSTy->isIntegralOrEnumerationType() ||
8732 !RHSTy->isIntegralOrEnumerationType()) &&
8733 "DataRecursiveIntBinOpEvaluator should have handled integral types");
8734 // We can't continue from here for non-integral types.
8735 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Anders Carlsson9c181652008-07-08 14:35:21 +00008736}
8737
Peter Collingbournee190dee2011-03-11 19:24:49 +00008738/// VisitUnaryExprOrTypeTraitExpr - Evaluate a sizeof, alignof or vec_step with
8739/// a result as the expression's type.
8740bool IntExprEvaluator::VisitUnaryExprOrTypeTraitExpr(
8741 const UnaryExprOrTypeTraitExpr *E) {
8742 switch(E->getKind()) {
8743 case UETT_AlignOf: {
Chris Lattner24aeeab2009-01-24 21:09:06 +00008744 if (E->isArgumentType())
Hal Finkel0dd05d42014-10-03 17:18:37 +00008745 return Success(GetAlignOfType(Info, E->getArgumentType()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008746 else
Hal Finkel0dd05d42014-10-03 17:18:37 +00008747 return Success(GetAlignOfExpr(Info, E->getArgumentExpr()), E);
Chris Lattner24aeeab2009-01-24 21:09:06 +00008748 }
Eli Friedman64004332009-03-23 04:38:34 +00008749
Peter Collingbournee190dee2011-03-11 19:24:49 +00008750 case UETT_VecStep: {
8751 QualType Ty = E->getTypeOfArgument();
Sebastian Redl6f282892008-11-11 17:56:53 +00008752
Peter Collingbournee190dee2011-03-11 19:24:49 +00008753 if (Ty->isVectorType()) {
Ted Kremenek28831752012-08-23 20:46:57 +00008754 unsigned n = Ty->castAs<VectorType>()->getNumElements();
Eli Friedman64004332009-03-23 04:38:34 +00008755
Peter Collingbournee190dee2011-03-11 19:24:49 +00008756 // The vec_step built-in functions that take a 3-component
8757 // vector return 4. (OpenCL 1.1 spec 6.11.12)
8758 if (n == 3)
8759 n = 4;
Eli Friedman2aa38fe2009-01-24 22:19:05 +00008760
Peter Collingbournee190dee2011-03-11 19:24:49 +00008761 return Success(n, E);
8762 } else
8763 return Success(1, E);
8764 }
8765
8766 case UETT_SizeOf: {
8767 QualType SrcTy = E->getTypeOfArgument();
8768 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
8769 // the result is the size of the referenced type."
Peter Collingbournee190dee2011-03-11 19:24:49 +00008770 if (const ReferenceType *Ref = SrcTy->getAs<ReferenceType>())
8771 SrcTy = Ref->getPointeeType();
8772
Richard Smithd62306a2011-11-10 06:34:14 +00008773 CharUnits Sizeof;
Richard Smith17100ba2012-02-16 02:46:34 +00008774 if (!HandleSizeof(Info, E->getExprLoc(), SrcTy, Sizeof))
Peter Collingbournee190dee2011-03-11 19:24:49 +00008775 return false;
Richard Smithd62306a2011-11-10 06:34:14 +00008776 return Success(Sizeof, E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008777 }
Alexey Bataev00396512015-07-02 03:40:19 +00008778 case UETT_OpenMPRequiredSimdAlign:
8779 assert(E->isArgumentType());
8780 return Success(
8781 Info.Ctx.toCharUnitsFromBits(
8782 Info.Ctx.getOpenMPDefaultSimdAlign(E->getArgumentType()))
8783 .getQuantity(),
8784 E);
Peter Collingbournee190dee2011-03-11 19:24:49 +00008785 }
8786
8787 llvm_unreachable("unknown expr/type trait");
Chris Lattnerf8d7f722008-07-11 21:24:13 +00008788}
8789
Peter Collingbournee9200682011-05-13 03:29:01 +00008790bool IntExprEvaluator::VisitOffsetOfExpr(const OffsetOfExpr *OOE) {
Douglas Gregor882211c2010-04-28 22:16:22 +00008791 CharUnits Result;
Peter Collingbournee9200682011-05-13 03:29:01 +00008792 unsigned n = OOE->getNumComponents();
Douglas Gregor882211c2010-04-28 22:16:22 +00008793 if (n == 0)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008794 return Error(OOE);
Peter Collingbournee9200682011-05-13 03:29:01 +00008795 QualType CurrentType = OOE->getTypeSourceInfo()->getType();
Douglas Gregor882211c2010-04-28 22:16:22 +00008796 for (unsigned i = 0; i != n; ++i) {
James Y Knight7281c352015-12-29 22:31:18 +00008797 OffsetOfNode ON = OOE->getComponent(i);
Douglas Gregor882211c2010-04-28 22:16:22 +00008798 switch (ON.getKind()) {
James Y Knight7281c352015-12-29 22:31:18 +00008799 case OffsetOfNode::Array: {
Peter Collingbournee9200682011-05-13 03:29:01 +00008800 const Expr *Idx = OOE->getIndexExpr(ON.getArrayExprIndex());
Douglas Gregor882211c2010-04-28 22:16:22 +00008801 APSInt IdxResult;
8802 if (!EvaluateInteger(Idx, IdxResult, Info))
8803 return false;
8804 const ArrayType *AT = Info.Ctx.getAsArrayType(CurrentType);
8805 if (!AT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008806 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008807 CurrentType = AT->getElementType();
8808 CharUnits ElementSize = Info.Ctx.getTypeSizeInChars(CurrentType);
8809 Result += IdxResult.getSExtValue() * ElementSize;
Richard Smith861b5b52013-05-07 23:34:45 +00008810 break;
Douglas Gregor882211c2010-04-28 22:16:22 +00008811 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008812
James Y Knight7281c352015-12-29 22:31:18 +00008813 case OffsetOfNode::Field: {
Douglas Gregor882211c2010-04-28 22:16:22 +00008814 FieldDecl *MemberDecl = ON.getField();
8815 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008816 if (!RT)
8817 return Error(OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008818 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008819 if (RD->isInvalidDecl()) return false;
Douglas Gregor882211c2010-04-28 22:16:22 +00008820 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
John McCall4e819612011-01-20 07:57:12 +00008821 unsigned i = MemberDecl->getFieldIndex();
Douglas Gregord1702062010-04-29 00:18:15 +00008822 assert(i < RL.getFieldCount() && "offsetof field in wrong type");
Ken Dyck86a7fcc2011-01-18 01:56:16 +00008823 Result += Info.Ctx.toCharUnitsFromBits(RL.getFieldOffset(i));
Douglas Gregor882211c2010-04-28 22:16:22 +00008824 CurrentType = MemberDecl->getType().getNonReferenceType();
8825 break;
8826 }
Richard Smithf57d8cb2011-12-09 22:58:01 +00008827
James Y Knight7281c352015-12-29 22:31:18 +00008828 case OffsetOfNode::Identifier:
Douglas Gregor882211c2010-04-28 22:16:22 +00008829 llvm_unreachable("dependent __builtin_offsetof");
Richard Smithf57d8cb2011-12-09 22:58:01 +00008830
James Y Knight7281c352015-12-29 22:31:18 +00008831 case OffsetOfNode::Base: {
Douglas Gregord1702062010-04-29 00:18:15 +00008832 CXXBaseSpecifier *BaseSpec = ON.getBase();
8833 if (BaseSpec->isVirtual())
Richard Smithf57d8cb2011-12-09 22:58:01 +00008834 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008835
8836 // Find the layout of the class whose base we are looking into.
8837 const RecordType *RT = CurrentType->getAs<RecordType>();
Richard Smithf57d8cb2011-12-09 22:58:01 +00008838 if (!RT)
8839 return Error(OOE);
Douglas Gregord1702062010-04-29 00:18:15 +00008840 RecordDecl *RD = RT->getDecl();
John McCalld7bca762012-05-01 00:38:49 +00008841 if (RD->isInvalidDecl()) return false;
Douglas Gregord1702062010-04-29 00:18:15 +00008842 const ASTRecordLayout &RL = Info.Ctx.getASTRecordLayout(RD);
8843
8844 // Find the base class itself.
8845 CurrentType = BaseSpec->getType();
8846 const RecordType *BaseRT = CurrentType->getAs<RecordType>();
8847 if (!BaseRT)
Richard Smithf57d8cb2011-12-09 22:58:01 +00008848 return Error(OOE);
Daniel Jasperffdee092017-05-02 19:21:42 +00008849
Douglas Gregord1702062010-04-29 00:18:15 +00008850 // Add the offset to the base.
Ken Dyck02155cb2011-01-26 02:17:08 +00008851 Result += RL.getBaseClassOffset(cast<CXXRecordDecl>(BaseRT->getDecl()));
Douglas Gregord1702062010-04-29 00:18:15 +00008852 break;
8853 }
Douglas Gregor882211c2010-04-28 22:16:22 +00008854 }
8855 }
Peter Collingbournee9200682011-05-13 03:29:01 +00008856 return Success(Result, OOE);
Douglas Gregor882211c2010-04-28 22:16:22 +00008857}
8858
Chris Lattnere13042c2008-07-11 19:10:17 +00008859bool IntExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00008860 switch (E->getOpcode()) {
8861 default:
8862 // Address, indirect, pre/post inc/dec, etc are not valid constant exprs.
8863 // See C99 6.6p3.
8864 return Error(E);
8865 case UO_Extension:
8866 // FIXME: Should extension allow i-c-e extension expressions in its scope?
8867 // If so, we could clear the diagnostic ID.
8868 return Visit(E->getSubExpr());
8869 case UO_Plus:
8870 // The result is just the value.
8871 return Visit(E->getSubExpr());
8872 case UO_Minus: {
8873 if (!Visit(E->getSubExpr()))
8874 return false;
8875 if (!Result.isInt()) return Error(E);
Richard Smithfe800032012-01-31 04:08:20 +00008876 const APSInt &Value = Result.getInt();
Richard Smith0c6124b2015-12-03 01:36:22 +00008877 if (Value.isSigned() && Value.isMinSignedValue() &&
8878 !HandleOverflow(Info, E, -Value.extend(Value.getBitWidth() + 1),
8879 E->getType()))
8880 return false;
Richard Smithfe800032012-01-31 04:08:20 +00008881 return Success(-Value, E);
Richard Smithf57d8cb2011-12-09 22:58:01 +00008882 }
8883 case UO_Not: {
8884 if (!Visit(E->getSubExpr()))
8885 return false;
8886 if (!Result.isInt()) return Error(E);
8887 return Success(~Result.getInt(), E);
8888 }
8889 case UO_LNot: {
Eli Friedman5a332ea2008-11-13 06:09:17 +00008890 bool bres;
Richard Smith11562c52011-10-28 17:51:58 +00008891 if (!EvaluateAsBooleanCondition(E->getSubExpr(), bres, Info))
Eli Friedman5a332ea2008-11-13 06:09:17 +00008892 return false;
Daniel Dunbar8aafc892009-02-19 09:06:44 +00008893 return Success(!bres, E);
Eli Friedman5a332ea2008-11-13 06:09:17 +00008894 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008895 }
Anders Carlsson9c181652008-07-08 14:35:21 +00008896}
Mike Stump11289f42009-09-09 15:08:12 +00008897
Chris Lattner477c4be2008-07-12 01:15:53 +00008898/// HandleCast - This is used to evaluate implicit or explicit casts where the
8899/// result type is integer.
Peter Collingbournee9200682011-05-13 03:29:01 +00008900bool IntExprEvaluator::VisitCastExpr(const CastExpr *E) {
8901 const Expr *SubExpr = E->getSubExpr();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008902 QualType DestType = E->getType();
Daniel Dunbarcf04aa12009-02-19 22:16:29 +00008903 QualType SrcType = SubExpr->getType();
Anders Carlsson27b8c5c2008-11-30 18:14:57 +00008904
Eli Friedmanc757de22011-03-25 00:43:55 +00008905 switch (E->getCastKind()) {
Eli Friedmanc757de22011-03-25 00:43:55 +00008906 case CK_BaseToDerived:
8907 case CK_DerivedToBase:
8908 case CK_UncheckedDerivedToBase:
8909 case CK_Dynamic:
8910 case CK_ToUnion:
8911 case CK_ArrayToPointerDecay:
8912 case CK_FunctionToPointerDecay:
8913 case CK_NullToPointer:
8914 case CK_NullToMemberPointer:
8915 case CK_BaseToDerivedMemberPointer:
8916 case CK_DerivedToBaseMemberPointer:
John McCallc62bb392012-02-15 01:22:51 +00008917 case CK_ReinterpretMemberPointer:
Eli Friedmanc757de22011-03-25 00:43:55 +00008918 case CK_ConstructorConversion:
8919 case CK_IntegralToPointer:
8920 case CK_ToVoid:
8921 case CK_VectorSplat:
8922 case CK_IntegralToFloating:
8923 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00008924 case CK_CPointerToObjCPointerCast:
8925 case CK_BlockPointerToObjCPointerCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008926 case CK_AnyPointerToBlockPointerCast:
8927 case CK_ObjCObjectLValueCast:
8928 case CK_FloatingRealToComplex:
8929 case CK_FloatingComplexToReal:
8930 case CK_FloatingComplexCast:
8931 case CK_FloatingComplexToIntegralComplex:
8932 case CK_IntegralRealToComplex:
8933 case CK_IntegralComplexCast:
8934 case CK_IntegralComplexToFloatingComplex:
Eli Friedman34866c72012-08-31 00:14:07 +00008935 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00008936 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00008937 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00008938 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00008939 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00008940 case CK_IntToOCLSampler:
Eli Friedmanc757de22011-03-25 00:43:55 +00008941 llvm_unreachable("invalid cast kind for integral value");
8942
Eli Friedman9faf2f92011-03-25 19:07:11 +00008943 case CK_BitCast:
Eli Friedmanc757de22011-03-25 00:43:55 +00008944 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00008945 case CK_LValueBitCast:
John McCall2d637d22011-09-10 06:18:15 +00008946 case CK_ARCProduceObject:
8947 case CK_ARCConsumeObject:
8948 case CK_ARCReclaimReturnedObject:
8949 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00008950 case CK_CopyAndAutoreleaseBlockObject:
Richard Smithf57d8cb2011-12-09 22:58:01 +00008951 return Error(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008952
Richard Smith4ef685b2012-01-17 21:17:26 +00008953 case CK_UserDefinedConversion:
Eli Friedmanc757de22011-03-25 00:43:55 +00008954 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00008955 case CK_AtomicToNonAtomic:
Eli Friedmanc757de22011-03-25 00:43:55 +00008956 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00008957 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedmanc757de22011-03-25 00:43:55 +00008958
8959 case CK_MemberPointerToBoolean:
8960 case CK_PointerToBoolean:
8961 case CK_IntegralToBoolean:
8962 case CK_FloatingToBoolean:
George Burgess IVdf1ed002016-01-13 01:52:39 +00008963 case CK_BooleanToSignedIntegral:
Eli Friedmanc757de22011-03-25 00:43:55 +00008964 case CK_FloatingComplexToBoolean:
8965 case CK_IntegralComplexToBoolean: {
Eli Friedman9a156e52008-11-12 09:44:48 +00008966 bool BoolResult;
Richard Smith11562c52011-10-28 17:51:58 +00008967 if (!EvaluateAsBooleanCondition(SubExpr, BoolResult, Info))
Eli Friedman9a156e52008-11-12 09:44:48 +00008968 return false;
George Burgess IVdf1ed002016-01-13 01:52:39 +00008969 uint64_t IntResult = BoolResult;
8970 if (BoolResult && E->getCastKind() == CK_BooleanToSignedIntegral)
8971 IntResult = (uint64_t)-1;
8972 return Success(IntResult, E);
Eli Friedman9a156e52008-11-12 09:44:48 +00008973 }
8974
Eli Friedmanc757de22011-03-25 00:43:55 +00008975 case CK_IntegralCast: {
Chris Lattner477c4be2008-07-12 01:15:53 +00008976 if (!Visit(SubExpr))
Chris Lattnere13042c2008-07-11 19:10:17 +00008977 return false;
Daniel Dunbarb6f953e2009-01-29 06:16:07 +00008978
Eli Friedman742421e2009-02-20 01:15:07 +00008979 if (!Result.isInt()) {
Eli Friedmanfd5e54d2012-01-04 23:13:47 +00008980 // Allow casts of address-of-label differences if they are no-ops
8981 // or narrowing. (The narrowing case isn't actually guaranteed to
8982 // be constant-evaluatable except in some narrow cases which are hard
8983 // to detect here. We let it through on the assumption the user knows
8984 // what they are doing.)
8985 if (Result.isAddrLabelDiff())
8986 return Info.Ctx.getTypeSize(DestType) <= Info.Ctx.getTypeSize(SrcType);
Eli Friedman742421e2009-02-20 01:15:07 +00008987 // Only allow casts of lvalues if they are lossless.
8988 return Info.Ctx.getTypeSize(DestType) == Info.Ctx.getTypeSize(SrcType);
8989 }
Daniel Dunbarca097ad2009-02-19 20:17:33 +00008990
Richard Smith911e1422012-01-30 22:27:01 +00008991 return Success(HandleIntToIntCast(Info, E, DestType, SrcType,
8992 Result.getInt()), E);
Chris Lattner477c4be2008-07-12 01:15:53 +00008993 }
Mike Stump11289f42009-09-09 15:08:12 +00008994
Eli Friedmanc757de22011-03-25 00:43:55 +00008995 case CK_PointerToIntegral: {
Richard Smith6d6ecc32011-12-12 12:46:16 +00008996 CCEDiag(E, diag::note_constexpr_invalid_cast) << 2;
8997
John McCall45d55e42010-05-07 21:00:08 +00008998 LValue LV;
Chris Lattnercdf34e72008-07-11 22:52:41 +00008999 if (!EvaluatePointer(SubExpr, LV, Info))
Chris Lattnere13042c2008-07-11 19:10:17 +00009000 return false;
Eli Friedman9a156e52008-11-12 09:44:48 +00009001
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009002 if (LV.getLValueBase()) {
9003 // Only allow based lvalue casts if they are lossless.
Richard Smith911e1422012-01-30 22:27:01 +00009004 // FIXME: Allow a larger integer size than the pointer size, and allow
9005 // narrowing back down to pointer width in subsequent integral casts.
9006 // FIXME: Check integer type's active bits, not its type size.
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009007 if (Info.Ctx.getTypeSize(DestType) != Info.Ctx.getTypeSize(SrcType))
Richard Smithf57d8cb2011-12-09 22:58:01 +00009008 return Error(E);
Eli Friedman9a156e52008-11-12 09:44:48 +00009009
Richard Smithcf74da72011-11-16 07:18:12 +00009010 LV.Designator.setInvalid();
John McCall45d55e42010-05-07 21:00:08 +00009011 LV.moveInto(Result);
Daniel Dunbar1c8560d2009-02-19 22:24:01 +00009012 return true;
9013 }
9014
Yaxun Liu402804b2016-12-15 08:09:08 +00009015 uint64_t V;
9016 if (LV.isNullPointer())
9017 V = Info.Ctx.getTargetNullPointerValue(SrcType);
9018 else
9019 V = LV.getLValueOffset().getQuantity();
9020
9021 APSInt AsInt = Info.Ctx.MakeIntValue(V, SrcType);
Richard Smith911e1422012-01-30 22:27:01 +00009022 return Success(HandleIntToIntCast(Info, E, DestType, SrcType, AsInt), E);
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009023 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009024
Eli Friedmanc757de22011-03-25 00:43:55 +00009025 case CK_IntegralComplexToReal: {
John McCall93d91dc2010-05-07 17:22:02 +00009026 ComplexValue C;
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009027 if (!EvaluateComplex(SubExpr, C, Info))
9028 return false;
Eli Friedmanc757de22011-03-25 00:43:55 +00009029 return Success(C.getComplexIntReal(), E);
Eli Friedmand3a5a9d2009-04-22 19:23:09 +00009030 }
Eli Friedmanc2b50172009-02-22 11:46:18 +00009031
Eli Friedmanc757de22011-03-25 00:43:55 +00009032 case CK_FloatingToIntegral: {
9033 APFloat F(0.0);
9034 if (!EvaluateFloat(SubExpr, F, Info))
9035 return false;
Chris Lattner477c4be2008-07-12 01:15:53 +00009036
Richard Smith357362d2011-12-13 06:39:58 +00009037 APSInt Value;
9038 if (!HandleFloatToIntCast(Info, E, SrcType, F, DestType, Value))
9039 return false;
9040 return Success(Value, E);
Eli Friedmanc757de22011-03-25 00:43:55 +00009041 }
9042 }
Mike Stump11289f42009-09-09 15:08:12 +00009043
Eli Friedmanc757de22011-03-25 00:43:55 +00009044 llvm_unreachable("unknown cast resulting in integral value");
Anders Carlsson9c181652008-07-08 14:35:21 +00009045}
Anders Carlssonb5ad0212008-07-08 14:30:00 +00009046
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009047bool IntExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
9048 if (E->getSubExpr()->getType()->isAnyComplexType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009049 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009050 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9051 return false;
9052 if (!LV.isComplexInt())
9053 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009054 return Success(LV.getComplexIntReal(), E);
9055 }
9056
9057 return Visit(E->getSubExpr());
9058}
9059
Eli Friedman4e7a2412009-02-27 04:45:43 +00009060bool IntExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009061 if (E->getSubExpr()->getType()->isComplexIntegerType()) {
John McCall93d91dc2010-05-07 17:22:02 +00009062 ComplexValue LV;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009063 if (!EvaluateComplex(E->getSubExpr(), LV, Info))
9064 return false;
9065 if (!LV.isComplexInt())
9066 return Error(E);
Eli Friedmana1c7b6c2009-02-28 03:59:05 +00009067 return Success(LV.getComplexIntImag(), E);
9068 }
9069
Richard Smith4a678122011-10-24 18:44:57 +00009070 VisitIgnoredValue(E->getSubExpr());
Eli Friedman4e7a2412009-02-27 04:45:43 +00009071 return Success(0, E);
9072}
9073
Douglas Gregor820ba7b2011-01-04 17:33:58 +00009074bool IntExprEvaluator::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
9075 return Success(E->getPackLength(), E);
9076}
9077
Sebastian Redl5f0180d2010-09-10 20:55:47 +00009078bool IntExprEvaluator::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
9079 return Success(E->getValue(), E);
9080}
9081
Chris Lattner05706e882008-07-11 18:11:29 +00009082//===----------------------------------------------------------------------===//
Eli Friedman24c01542008-08-22 00:06:13 +00009083// Float Evaluation
9084//===----------------------------------------------------------------------===//
9085
9086namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009087class FloatExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009088 : public ExprEvaluatorBase<FloatExprEvaluator> {
Eli Friedman24c01542008-08-22 00:06:13 +00009089 APFloat &Result;
9090public:
9091 FloatExprEvaluator(EvalInfo &info, APFloat &result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009092 : ExprEvaluatorBaseTy(info), Result(result) {}
Eli Friedman24c01542008-08-22 00:06:13 +00009093
Richard Smith2e312c82012-03-03 22:46:17 +00009094 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009095 Result = V.getFloat();
9096 return true;
9097 }
Eli Friedman24c01542008-08-22 00:06:13 +00009098
Richard Smithfddd3842011-12-30 21:15:51 +00009099 bool ZeroInitialization(const Expr *E) {
Richard Smith4ce706a2011-10-11 21:43:33 +00009100 Result = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(E->getType()));
9101 return true;
9102 }
9103
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009104 bool VisitCallExpr(const CallExpr *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009105
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009106 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedman24c01542008-08-22 00:06:13 +00009107 bool VisitBinaryOperator(const BinaryOperator *E);
9108 bool VisitFloatingLiteral(const FloatingLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009109 bool VisitCastExpr(const CastExpr *E);
Eli Friedmanc2b50172009-02-22 11:46:18 +00009110
John McCallb1fb0d32010-05-07 22:08:54 +00009111 bool VisitUnaryReal(const UnaryOperator *E);
9112 bool VisitUnaryImag(const UnaryOperator *E);
Eli Friedman449fe542009-03-23 04:56:01 +00009113
Richard Smithfddd3842011-12-30 21:15:51 +00009114 // FIXME: Missing: array subscript of vector, member of vector
Eli Friedman24c01542008-08-22 00:06:13 +00009115};
9116} // end anonymous namespace
9117
9118static bool EvaluateFloat(const Expr* E, APFloat& Result, EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009119 assert(E->isRValue() && E->getType()->isRealFloatingType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009120 return FloatExprEvaluator(Info, Result).Visit(E);
Eli Friedman24c01542008-08-22 00:06:13 +00009121}
9122
Jay Foad39c79802011-01-12 09:06:06 +00009123static bool TryEvaluateBuiltinNaN(const ASTContext &Context,
John McCall16291492010-02-28 13:00:19 +00009124 QualType ResultTy,
9125 const Expr *Arg,
9126 bool SNaN,
9127 llvm::APFloat &Result) {
9128 const StringLiteral *S = dyn_cast<StringLiteral>(Arg->IgnoreParenCasts());
9129 if (!S) return false;
9130
9131 const llvm::fltSemantics &Sem = Context.getFloatTypeSemantics(ResultTy);
9132
9133 llvm::APInt fill;
9134
9135 // Treat empty strings as if they were zero.
9136 if (S->getString().empty())
9137 fill = llvm::APInt(32, 0);
9138 else if (S->getString().getAsInteger(0, fill))
9139 return false;
9140
Petar Jovanovicd55ae6b2015-02-26 18:19:22 +00009141 if (Context.getTargetInfo().isNan2008()) {
9142 if (SNaN)
9143 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9144 else
9145 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9146 } else {
9147 // Prior to IEEE 754-2008, architectures were allowed to choose whether
9148 // the first bit of their significand was set for qNaN or sNaN. MIPS chose
9149 // a different encoding to what became a standard in 2008, and for pre-
9150 // 2008 revisions, MIPS interpreted sNaN-2008 as qNan and qNaN-2008 as
9151 // sNaN. This is now known as "legacy NaN" encoding.
9152 if (SNaN)
9153 Result = llvm::APFloat::getQNaN(Sem, false, &fill);
9154 else
9155 Result = llvm::APFloat::getSNaN(Sem, false, &fill);
9156 }
9157
John McCall16291492010-02-28 13:00:19 +00009158 return true;
9159}
9160
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009161bool FloatExprEvaluator::VisitCallExpr(const CallExpr *E) {
Alp Tokera724cff2013-12-28 21:59:02 +00009162 switch (E->getBuiltinCallee()) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009163 default:
9164 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9165
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009166 case Builtin::BI__builtin_huge_val:
9167 case Builtin::BI__builtin_huge_valf:
9168 case Builtin::BI__builtin_huge_vall:
9169 case Builtin::BI__builtin_inf:
9170 case Builtin::BI__builtin_inff:
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009171 case Builtin::BI__builtin_infl: {
9172 const llvm::fltSemantics &Sem =
9173 Info.Ctx.getFloatTypeSemantics(E->getType());
Chris Lattner37346e02008-10-06 05:53:16 +00009174 Result = llvm::APFloat::getInf(Sem);
9175 return true;
Daniel Dunbar1be9f882008-10-14 05:41:12 +00009176 }
Mike Stump11289f42009-09-09 15:08:12 +00009177
John McCall16291492010-02-28 13:00:19 +00009178 case Builtin::BI__builtin_nans:
9179 case Builtin::BI__builtin_nansf:
9180 case Builtin::BI__builtin_nansl:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009181 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9182 true, Result))
9183 return Error(E);
9184 return true;
John McCall16291492010-02-28 13:00:19 +00009185
Chris Lattner0b7282e2008-10-06 06:31:58 +00009186 case Builtin::BI__builtin_nan:
9187 case Builtin::BI__builtin_nanf:
9188 case Builtin::BI__builtin_nanl:
Mike Stump2346cd22009-05-30 03:56:50 +00009189 // If this is __builtin_nan() turn this into a nan, otherwise we
Chris Lattner0b7282e2008-10-06 06:31:58 +00009190 // can't constant fold it.
Richard Smithf57d8cb2011-12-09 22:58:01 +00009191 if (!TryEvaluateBuiltinNaN(Info.Ctx, E->getType(), E->getArg(0),
9192 false, Result))
9193 return Error(E);
9194 return true;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009195
9196 case Builtin::BI__builtin_fabs:
9197 case Builtin::BI__builtin_fabsf:
9198 case Builtin::BI__builtin_fabsl:
9199 if (!EvaluateFloat(E->getArg(0), Result, Info))
9200 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009201
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009202 if (Result.isNegative())
9203 Result.changeSign();
9204 return true;
9205
Richard Smith8889a3d2013-06-13 06:26:32 +00009206 // FIXME: Builtin::BI__builtin_powi
9207 // FIXME: Builtin::BI__builtin_powif
9208 // FIXME: Builtin::BI__builtin_powil
9209
Mike Stump11289f42009-09-09 15:08:12 +00009210 case Builtin::BI__builtin_copysign:
9211 case Builtin::BI__builtin_copysignf:
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009212 case Builtin::BI__builtin_copysignl: {
9213 APFloat RHS(0.);
9214 if (!EvaluateFloat(E->getArg(0), Result, Info) ||
9215 !EvaluateFloat(E->getArg(1), RHS, Info))
9216 return false;
9217 Result.copySign(RHS);
9218 return true;
9219 }
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009220 }
9221}
9222
John McCallb1fb0d32010-05-07 22:08:54 +00009223bool FloatExprEvaluator::VisitUnaryReal(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009224 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9225 ComplexValue CV;
9226 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9227 return false;
9228 Result = CV.FloatReal;
9229 return true;
9230 }
9231
9232 return Visit(E->getSubExpr());
John McCallb1fb0d32010-05-07 22:08:54 +00009233}
9234
9235bool FloatExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
Eli Friedman95719532010-08-14 20:52:13 +00009236 if (E->getSubExpr()->getType()->isAnyComplexType()) {
9237 ComplexValue CV;
9238 if (!EvaluateComplex(E->getSubExpr(), CV, Info))
9239 return false;
9240 Result = CV.FloatImag;
9241 return true;
9242 }
9243
Richard Smith4a678122011-10-24 18:44:57 +00009244 VisitIgnoredValue(E->getSubExpr());
Eli Friedman95719532010-08-14 20:52:13 +00009245 const llvm::fltSemantics &Sem = Info.Ctx.getFloatTypeSemantics(E->getType());
9246 Result = llvm::APFloat::getZero(Sem);
John McCallb1fb0d32010-05-07 22:08:54 +00009247 return true;
9248}
9249
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009250bool FloatExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009251 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009252 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009253 case UO_Plus:
Richard Smith390cd492011-10-30 23:17:09 +00009254 return EvaluateFloat(E->getSubExpr(), Result, Info);
John McCalle3027922010-08-25 11:45:40 +00009255 case UO_Minus:
Richard Smith390cd492011-10-30 23:17:09 +00009256 if (!EvaluateFloat(E->getSubExpr(), Result, Info))
9257 return false;
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009258 Result.changeSign();
9259 return true;
9260 }
9261}
Chris Lattner4deaa4e2008-10-06 05:28:25 +00009262
Eli Friedman24c01542008-08-22 00:06:13 +00009263bool FloatExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009264 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
9265 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
Eli Friedman141fbf32009-11-16 04:25:37 +00009266
Daniel Dunbarc3d79cf2008-10-16 03:51:50 +00009267 APFloat RHS(0.0);
Richard Smith253c2a32012-01-27 01:14:48 +00009268 bool LHSOK = EvaluateFloat(E->getLHS(), Result, Info);
George Burgess IVa145e252016-05-25 22:38:36 +00009269 if (!LHSOK && !Info.noteFailure())
Eli Friedman24c01542008-08-22 00:06:13 +00009270 return false;
Richard Smith861b5b52013-05-07 23:34:45 +00009271 return EvaluateFloat(E->getRHS(), RHS, Info) && LHSOK &&
9272 handleFloatFloatBinOp(Info, E, Result, E->getOpcode(), RHS);
Eli Friedman24c01542008-08-22 00:06:13 +00009273}
9274
9275bool FloatExprEvaluator::VisitFloatingLiteral(const FloatingLiteral *E) {
9276 Result = E->getValue();
9277 return true;
9278}
9279
Peter Collingbournee9200682011-05-13 03:29:01 +00009280bool FloatExprEvaluator::VisitCastExpr(const CastExpr *E) {
9281 const Expr* SubExpr = E->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00009282
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009283 switch (E->getCastKind()) {
9284 default:
Richard Smith11562c52011-10-28 17:51:58 +00009285 return ExprEvaluatorBaseTy::VisitCastExpr(E);
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009286
9287 case CK_IntegralToFloating: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009288 APSInt IntResult;
Richard Smith357362d2011-12-13 06:39:58 +00009289 return EvaluateInteger(SubExpr, IntResult, Info) &&
9290 HandleIntToFloatCast(Info, E, SubExpr->getType(), IntResult,
9291 E->getType(), Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009292 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009293
9294 case CK_FloatingCast: {
Eli Friedman9a156e52008-11-12 09:44:48 +00009295 if (!Visit(SubExpr))
9296 return false;
Richard Smith357362d2011-12-13 06:39:58 +00009297 return HandleFloatToFloatCast(Info, E, SubExpr->getType(), E->getType(),
9298 Result);
Eli Friedman9a156e52008-11-12 09:44:48 +00009299 }
John McCalld7646252010-11-14 08:17:51 +00009300
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009301 case CK_FloatingComplexToReal: {
John McCalld7646252010-11-14 08:17:51 +00009302 ComplexValue V;
9303 if (!EvaluateComplex(SubExpr, V, Info))
9304 return false;
9305 Result = V.getComplexFloatReal();
9306 return true;
9307 }
Eli Friedman8bfbe3a2011-03-25 00:54:52 +00009308 }
Eli Friedman9a156e52008-11-12 09:44:48 +00009309}
9310
Eli Friedman24c01542008-08-22 00:06:13 +00009311//===----------------------------------------------------------------------===//
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009312// Complex Evaluation (for float and integer)
Anders Carlsson537969c2008-11-16 20:27:53 +00009313//===----------------------------------------------------------------------===//
9314
9315namespace {
Benjamin Kramer26222b62009-11-28 19:03:38 +00009316class ComplexExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009317 : public ExprEvaluatorBase<ComplexExprEvaluator> {
John McCall93d91dc2010-05-07 17:22:02 +00009318 ComplexValue &Result;
Mike Stump11289f42009-09-09 15:08:12 +00009319
Anders Carlsson537969c2008-11-16 20:27:53 +00009320public:
John McCall93d91dc2010-05-07 17:22:02 +00009321 ComplexExprEvaluator(EvalInfo &info, ComplexValue &Result)
Peter Collingbournee9200682011-05-13 03:29:01 +00009322 : ExprEvaluatorBaseTy(info), Result(Result) {}
9323
Richard Smith2e312c82012-03-03 22:46:17 +00009324 bool Success(const APValue &V, const Expr *e) {
Peter Collingbournee9200682011-05-13 03:29:01 +00009325 Result.setFrom(V);
9326 return true;
9327 }
Mike Stump11289f42009-09-09 15:08:12 +00009328
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009329 bool ZeroInitialization(const Expr *E);
9330
Anders Carlsson537969c2008-11-16 20:27:53 +00009331 //===--------------------------------------------------------------------===//
9332 // Visitor Methods
9333 //===--------------------------------------------------------------------===//
9334
Peter Collingbournee9200682011-05-13 03:29:01 +00009335 bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
Peter Collingbournee9200682011-05-13 03:29:01 +00009336 bool VisitCastExpr(const CastExpr *E);
John McCall93d91dc2010-05-07 17:22:02 +00009337 bool VisitBinaryOperator(const BinaryOperator *E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009338 bool VisitUnaryOperator(const UnaryOperator *E);
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009339 bool VisitInitListExpr(const InitListExpr *E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009340};
9341} // end anonymous namespace
9342
John McCall93d91dc2010-05-07 17:22:02 +00009343static bool EvaluateComplex(const Expr *E, ComplexValue &Result,
9344 EvalInfo &Info) {
Richard Smith11562c52011-10-28 17:51:58 +00009345 assert(E->isRValue() && E->getType()->isAnyComplexType());
Peter Collingbournee9200682011-05-13 03:29:01 +00009346 return ComplexExprEvaluator(Info, Result).Visit(E);
Anders Carlsson537969c2008-11-16 20:27:53 +00009347}
9348
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009349bool ComplexExprEvaluator::ZeroInitialization(const Expr *E) {
Ted Kremenek28831752012-08-23 20:46:57 +00009350 QualType ElemTy = E->getType()->castAs<ComplexType>()->getElementType();
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009351 if (ElemTy->isRealFloatingType()) {
9352 Result.makeComplexFloat();
9353 APFloat Zero = APFloat::getZero(Info.Ctx.getFloatTypeSemantics(ElemTy));
9354 Result.FloatReal = Zero;
9355 Result.FloatImag = Zero;
9356 } else {
9357 Result.makeComplexInt();
9358 APSInt Zero = Info.Ctx.MakeIntValue(0, ElemTy);
9359 Result.IntReal = Zero;
9360 Result.IntImag = Zero;
9361 }
9362 return true;
9363}
9364
Peter Collingbournee9200682011-05-13 03:29:01 +00009365bool ComplexExprEvaluator::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
9366 const Expr* SubExpr = E->getSubExpr();
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009367
9368 if (SubExpr->getType()->isRealFloatingType()) {
9369 Result.makeComplexFloat();
9370 APFloat &Imag = Result.FloatImag;
9371 if (!EvaluateFloat(SubExpr, Imag, Info))
9372 return false;
9373
9374 Result.FloatReal = APFloat(Imag.getSemantics());
9375 return true;
9376 } else {
9377 assert(SubExpr->getType()->isIntegerType() &&
9378 "Unexpected imaginary literal.");
9379
9380 Result.makeComplexInt();
9381 APSInt &Imag = Result.IntImag;
9382 if (!EvaluateInteger(SubExpr, Imag, Info))
9383 return false;
9384
9385 Result.IntReal = APSInt(Imag.getBitWidth(), !Imag.isSigned());
9386 return true;
9387 }
9388}
9389
Peter Collingbournee9200682011-05-13 03:29:01 +00009390bool ComplexExprEvaluator::VisitCastExpr(const CastExpr *E) {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009391
John McCallfcef3cf2010-12-14 17:51:41 +00009392 switch (E->getCastKind()) {
9393 case CK_BitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009394 case CK_BaseToDerived:
9395 case CK_DerivedToBase:
9396 case CK_UncheckedDerivedToBase:
9397 case CK_Dynamic:
9398 case CK_ToUnion:
9399 case CK_ArrayToPointerDecay:
9400 case CK_FunctionToPointerDecay:
9401 case CK_NullToPointer:
9402 case CK_NullToMemberPointer:
9403 case CK_BaseToDerivedMemberPointer:
9404 case CK_DerivedToBaseMemberPointer:
9405 case CK_MemberPointerToBoolean:
John McCallc62bb392012-02-15 01:22:51 +00009406 case CK_ReinterpretMemberPointer:
John McCallfcef3cf2010-12-14 17:51:41 +00009407 case CK_ConstructorConversion:
9408 case CK_IntegralToPointer:
9409 case CK_PointerToIntegral:
9410 case CK_PointerToBoolean:
9411 case CK_ToVoid:
9412 case CK_VectorSplat:
9413 case CK_IntegralCast:
George Burgess IVdf1ed002016-01-13 01:52:39 +00009414 case CK_BooleanToSignedIntegral:
John McCallfcef3cf2010-12-14 17:51:41 +00009415 case CK_IntegralToBoolean:
9416 case CK_IntegralToFloating:
9417 case CK_FloatingToIntegral:
9418 case CK_FloatingToBoolean:
9419 case CK_FloatingCast:
John McCall9320b872011-09-09 05:25:32 +00009420 case CK_CPointerToObjCPointerCast:
9421 case CK_BlockPointerToObjCPointerCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009422 case CK_AnyPointerToBlockPointerCast:
9423 case CK_ObjCObjectLValueCast:
9424 case CK_FloatingComplexToReal:
9425 case CK_FloatingComplexToBoolean:
9426 case CK_IntegralComplexToReal:
9427 case CK_IntegralComplexToBoolean:
John McCall2d637d22011-09-10 06:18:15 +00009428 case CK_ARCProduceObject:
9429 case CK_ARCConsumeObject:
9430 case CK_ARCReclaimReturnedObject:
9431 case CK_ARCExtendBlockObject:
Douglas Gregored90df32012-02-22 05:02:47 +00009432 case CK_CopyAndAutoreleaseBlockObject:
Eli Friedman34866c72012-08-31 00:14:07 +00009433 case CK_BuiltinFnToFnPtr:
Guy Benyei1b4fb3e2013-01-20 12:31:11 +00009434 case CK_ZeroToOCLEvent:
Egor Churaev89831422016-12-23 14:55:49 +00009435 case CK_ZeroToOCLQueue:
Richard Smitha23ab512013-05-23 00:30:41 +00009436 case CK_NonAtomicToAtomic:
David Tweede1468322013-12-11 13:39:46 +00009437 case CK_AddressSpaceConversion:
Yaxun Liu0bc4b2d2016-07-28 19:26:30 +00009438 case CK_IntToOCLSampler:
John McCallfcef3cf2010-12-14 17:51:41 +00009439 llvm_unreachable("invalid cast kind for complex value");
John McCallc5e62b42010-11-13 09:02:35 +00009440
John McCallfcef3cf2010-12-14 17:51:41 +00009441 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +00009442 case CK_AtomicToNonAtomic:
John McCallfcef3cf2010-12-14 17:51:41 +00009443 case CK_NoOp:
Richard Smith11562c52011-10-28 17:51:58 +00009444 return ExprEvaluatorBaseTy::VisitCastExpr(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009445
9446 case CK_Dependent:
Eli Friedmanc757de22011-03-25 00:43:55 +00009447 case CK_LValueBitCast:
John McCallfcef3cf2010-12-14 17:51:41 +00009448 case CK_UserDefinedConversion:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009449 return Error(E);
John McCallfcef3cf2010-12-14 17:51:41 +00009450
9451 case CK_FloatingRealToComplex: {
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009452 APFloat &Real = Result.FloatReal;
John McCallfcef3cf2010-12-14 17:51:41 +00009453 if (!EvaluateFloat(E->getSubExpr(), Real, Info))
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009454 return false;
9455
John McCallfcef3cf2010-12-14 17:51:41 +00009456 Result.makeComplexFloat();
9457 Result.FloatImag = APFloat(Real.getSemantics());
9458 return true;
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009459 }
9460
John McCallfcef3cf2010-12-14 17:51:41 +00009461 case CK_FloatingComplexCast: {
9462 if (!Visit(E->getSubExpr()))
9463 return false;
9464
9465 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9466 QualType From
9467 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9468
Richard Smith357362d2011-12-13 06:39:58 +00009469 return HandleFloatToFloatCast(Info, E, From, To, Result.FloatReal) &&
9470 HandleFloatToFloatCast(Info, E, From, To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009471 }
9472
9473 case CK_FloatingComplexToIntegralComplex: {
9474 if (!Visit(E->getSubExpr()))
9475 return false;
9476
9477 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9478 QualType From
9479 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9480 Result.makeComplexInt();
Richard Smith357362d2011-12-13 06:39:58 +00009481 return HandleFloatToIntCast(Info, E, From, Result.FloatReal,
9482 To, Result.IntReal) &&
9483 HandleFloatToIntCast(Info, E, From, Result.FloatImag,
9484 To, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009485 }
9486
9487 case CK_IntegralRealToComplex: {
9488 APSInt &Real = Result.IntReal;
9489 if (!EvaluateInteger(E->getSubExpr(), Real, Info))
9490 return false;
9491
9492 Result.makeComplexInt();
9493 Result.IntImag = APSInt(Real.getBitWidth(), !Real.isSigned());
9494 return true;
9495 }
9496
9497 case CK_IntegralComplexCast: {
9498 if (!Visit(E->getSubExpr()))
9499 return false;
9500
9501 QualType To = E->getType()->getAs<ComplexType>()->getElementType();
9502 QualType From
9503 = E->getSubExpr()->getType()->getAs<ComplexType>()->getElementType();
9504
Richard Smith911e1422012-01-30 22:27:01 +00009505 Result.IntReal = HandleIntToIntCast(Info, E, To, From, Result.IntReal);
9506 Result.IntImag = HandleIntToIntCast(Info, E, To, From, Result.IntImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009507 return true;
9508 }
9509
9510 case CK_IntegralComplexToFloatingComplex: {
9511 if (!Visit(E->getSubExpr()))
9512 return false;
9513
Ted Kremenek28831752012-08-23 20:46:57 +00009514 QualType To = E->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009515 QualType From
Ted Kremenek28831752012-08-23 20:46:57 +00009516 = E->getSubExpr()->getType()->castAs<ComplexType>()->getElementType();
John McCallfcef3cf2010-12-14 17:51:41 +00009517 Result.makeComplexFloat();
Richard Smith357362d2011-12-13 06:39:58 +00009518 return HandleIntToFloatCast(Info, E, From, Result.IntReal,
9519 To, Result.FloatReal) &&
9520 HandleIntToFloatCast(Info, E, From, Result.IntImag,
9521 To, Result.FloatImag);
John McCallfcef3cf2010-12-14 17:51:41 +00009522 }
9523 }
9524
9525 llvm_unreachable("unknown cast resulting in complex value");
Eli Friedmanc3e9df32010-08-16 23:27:44 +00009526}
9527
John McCall93d91dc2010-05-07 17:22:02 +00009528bool ComplexExprEvaluator::VisitBinaryOperator(const BinaryOperator *E) {
Richard Smith027bf112011-11-17 22:56:20 +00009529 if (E->isPtrMemOp() || E->isAssignmentOp() || E->getOpcode() == BO_Comma)
Richard Smith10f4d062011-11-16 17:22:48 +00009530 return ExprEvaluatorBaseTy::VisitBinaryOperator(E);
9531
Chandler Carrutha216cad2014-10-11 00:57:18 +00009532 // Track whether the LHS or RHS is real at the type system level. When this is
9533 // the case we can simplify our evaluation strategy.
9534 bool LHSReal = false, RHSReal = false;
9535
9536 bool LHSOK;
9537 if (E->getLHS()->getType()->isRealFloatingType()) {
9538 LHSReal = true;
9539 APFloat &Real = Result.FloatReal;
9540 LHSOK = EvaluateFloat(E->getLHS(), Real, Info);
9541 if (LHSOK) {
9542 Result.makeComplexFloat();
9543 Result.FloatImag = APFloat(Real.getSemantics());
9544 }
9545 } else {
9546 LHSOK = Visit(E->getLHS());
9547 }
George Burgess IVa145e252016-05-25 22:38:36 +00009548 if (!LHSOK && !Info.noteFailure())
John McCall93d91dc2010-05-07 17:22:02 +00009549 return false;
Mike Stump11289f42009-09-09 15:08:12 +00009550
John McCall93d91dc2010-05-07 17:22:02 +00009551 ComplexValue RHS;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009552 if (E->getRHS()->getType()->isRealFloatingType()) {
9553 RHSReal = true;
9554 APFloat &Real = RHS.FloatReal;
9555 if (!EvaluateFloat(E->getRHS(), Real, Info) || !LHSOK)
9556 return false;
9557 RHS.makeComplexFloat();
9558 RHS.FloatImag = APFloat(Real.getSemantics());
9559 } else if (!EvaluateComplex(E->getRHS(), RHS, Info) || !LHSOK)
John McCall93d91dc2010-05-07 17:22:02 +00009560 return false;
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009561
Chandler Carrutha216cad2014-10-11 00:57:18 +00009562 assert(!(LHSReal && RHSReal) &&
9563 "Cannot have both operands of a complex operation be real.");
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009564 switch (E->getOpcode()) {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009565 default: return Error(E);
John McCalle3027922010-08-25 11:45:40 +00009566 case BO_Add:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009567 if (Result.isComplexFloat()) {
9568 Result.getComplexFloatReal().add(RHS.getComplexFloatReal(),
9569 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009570 if (LHSReal)
9571 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9572 else if (!RHSReal)
9573 Result.getComplexFloatImag().add(RHS.getComplexFloatImag(),
9574 APFloat::rmNearestTiesToEven);
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009575 } else {
9576 Result.getComplexIntReal() += RHS.getComplexIntReal();
9577 Result.getComplexIntImag() += RHS.getComplexIntImag();
9578 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009579 break;
John McCalle3027922010-08-25 11:45:40 +00009580 case BO_Sub:
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009581 if (Result.isComplexFloat()) {
9582 Result.getComplexFloatReal().subtract(RHS.getComplexFloatReal(),
9583 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009584 if (LHSReal) {
9585 Result.getComplexFloatImag() = RHS.getComplexFloatImag();
9586 Result.getComplexFloatImag().changeSign();
9587 } else if (!RHSReal) {
9588 Result.getComplexFloatImag().subtract(RHS.getComplexFloatImag(),
9589 APFloat::rmNearestTiesToEven);
9590 }
Daniel Dunbarf50e60b2009-01-28 22:24:07 +00009591 } else {
9592 Result.getComplexIntReal() -= RHS.getComplexIntReal();
9593 Result.getComplexIntImag() -= RHS.getComplexIntImag();
9594 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009595 break;
John McCalle3027922010-08-25 11:45:40 +00009596 case BO_Mul:
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009597 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009598 // This is an implementation of complex multiplication according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009599 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009600 // following naming scheme:
9601 // (a + ib) * (c + id)
John McCall93d91dc2010-05-07 17:22:02 +00009602 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009603 APFloat &A = LHS.getComplexFloatReal();
9604 APFloat &B = LHS.getComplexFloatImag();
9605 APFloat &C = RHS.getComplexFloatReal();
9606 APFloat &D = RHS.getComplexFloatImag();
9607 APFloat &ResR = Result.getComplexFloatReal();
9608 APFloat &ResI = Result.getComplexFloatImag();
9609 if (LHSReal) {
9610 assert(!RHSReal && "Cannot have two real operands for a complex op!");
9611 ResR = A * C;
9612 ResI = A * D;
9613 } else if (RHSReal) {
9614 ResR = C * A;
9615 ResI = C * B;
9616 } else {
9617 // In the fully general case, we need to handle NaNs and infinities
9618 // robustly.
9619 APFloat AC = A * C;
9620 APFloat BD = B * D;
9621 APFloat AD = A * D;
9622 APFloat BC = B * C;
9623 ResR = AC - BD;
9624 ResI = AD + BC;
9625 if (ResR.isNaN() && ResI.isNaN()) {
9626 bool Recalc = false;
9627 if (A.isInfinity() || B.isInfinity()) {
9628 A = APFloat::copySign(
9629 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9630 B = APFloat::copySign(
9631 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9632 if (C.isNaN())
9633 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9634 if (D.isNaN())
9635 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9636 Recalc = true;
9637 }
9638 if (C.isInfinity() || D.isInfinity()) {
9639 C = APFloat::copySign(
9640 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9641 D = APFloat::copySign(
9642 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9643 if (A.isNaN())
9644 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9645 if (B.isNaN())
9646 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9647 Recalc = true;
9648 }
9649 if (!Recalc && (AC.isInfinity() || BD.isInfinity() ||
9650 AD.isInfinity() || BC.isInfinity())) {
9651 if (A.isNaN())
9652 A = APFloat::copySign(APFloat(A.getSemantics()), A);
9653 if (B.isNaN())
9654 B = APFloat::copySign(APFloat(B.getSemantics()), B);
9655 if (C.isNaN())
9656 C = APFloat::copySign(APFloat(C.getSemantics()), C);
9657 if (D.isNaN())
9658 D = APFloat::copySign(APFloat(D.getSemantics()), D);
9659 Recalc = true;
9660 }
9661 if (Recalc) {
9662 ResR = APFloat::getInf(A.getSemantics()) * (A * C - B * D);
9663 ResI = APFloat::getInf(A.getSemantics()) * (A * D + B * C);
9664 }
9665 }
9666 }
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009667 } else {
John McCall93d91dc2010-05-07 17:22:02 +00009668 ComplexValue LHS = Result;
Mike Stump11289f42009-09-09 15:08:12 +00009669 Result.getComplexIntReal() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009670 (LHS.getComplexIntReal() * RHS.getComplexIntReal() -
9671 LHS.getComplexIntImag() * RHS.getComplexIntImag());
Mike Stump11289f42009-09-09 15:08:12 +00009672 Result.getComplexIntImag() =
Daniel Dunbar0aa26062009-01-29 01:32:56 +00009673 (LHS.getComplexIntReal() * RHS.getComplexIntImag() +
9674 LHS.getComplexIntImag() * RHS.getComplexIntReal());
9675 }
9676 break;
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009677 case BO_Div:
9678 if (Result.isComplexFloat()) {
Chandler Carrutha216cad2014-10-11 00:57:18 +00009679 // This is an implementation of complex division according to the
Hiroshi Inoue0c2734f2017-07-05 05:37:45 +00009680 // constraints laid out in C11 Annex G. The implemention uses the
Chandler Carrutha216cad2014-10-11 00:57:18 +00009681 // following naming scheme:
9682 // (a + ib) / (c + id)
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009683 ComplexValue LHS = Result;
Chandler Carrutha216cad2014-10-11 00:57:18 +00009684 APFloat &A = LHS.getComplexFloatReal();
9685 APFloat &B = LHS.getComplexFloatImag();
9686 APFloat &C = RHS.getComplexFloatReal();
9687 APFloat &D = RHS.getComplexFloatImag();
9688 APFloat &ResR = Result.getComplexFloatReal();
9689 APFloat &ResI = Result.getComplexFloatImag();
9690 if (RHSReal) {
9691 ResR = A / C;
9692 ResI = B / C;
9693 } else {
9694 if (LHSReal) {
9695 // No real optimizations we can do here, stub out with zero.
9696 B = APFloat::getZero(A.getSemantics());
9697 }
9698 int DenomLogB = 0;
9699 APFloat MaxCD = maxnum(abs(C), abs(D));
9700 if (MaxCD.isFinite()) {
9701 DenomLogB = ilogb(MaxCD);
Matt Arsenaultc477f482016-03-13 05:12:47 +00009702 C = scalbn(C, -DenomLogB, APFloat::rmNearestTiesToEven);
9703 D = scalbn(D, -DenomLogB, APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009704 }
9705 APFloat Denom = C * C + D * D;
Matt Arsenaultc477f482016-03-13 05:12:47 +00009706 ResR = scalbn((A * C + B * D) / Denom, -DenomLogB,
9707 APFloat::rmNearestTiesToEven);
9708 ResI = scalbn((B * C - A * D) / Denom, -DenomLogB,
9709 APFloat::rmNearestTiesToEven);
Chandler Carrutha216cad2014-10-11 00:57:18 +00009710 if (ResR.isNaN() && ResI.isNaN()) {
9711 if (Denom.isPosZero() && (!A.isNaN() || !B.isNaN())) {
9712 ResR = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * A;
9713 ResI = APFloat::getInf(ResR.getSemantics(), C.isNegative()) * B;
9714 } else if ((A.isInfinity() || B.isInfinity()) && C.isFinite() &&
9715 D.isFinite()) {
9716 A = APFloat::copySign(
9717 APFloat(A.getSemantics(), A.isInfinity() ? 1 : 0), A);
9718 B = APFloat::copySign(
9719 APFloat(B.getSemantics(), B.isInfinity() ? 1 : 0), B);
9720 ResR = APFloat::getInf(ResR.getSemantics()) * (A * C + B * D);
9721 ResI = APFloat::getInf(ResI.getSemantics()) * (B * C - A * D);
9722 } else if (MaxCD.isInfinity() && A.isFinite() && B.isFinite()) {
9723 C = APFloat::copySign(
9724 APFloat(C.getSemantics(), C.isInfinity() ? 1 : 0), C);
9725 D = APFloat::copySign(
9726 APFloat(D.getSemantics(), D.isInfinity() ? 1 : 0), D);
9727 ResR = APFloat::getZero(ResR.getSemantics()) * (A * C + B * D);
9728 ResI = APFloat::getZero(ResI.getSemantics()) * (B * C - A * D);
9729 }
9730 }
9731 }
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009732 } else {
Richard Smithf57d8cb2011-12-09 22:58:01 +00009733 if (RHS.getComplexIntReal() == 0 && RHS.getComplexIntImag() == 0)
9734 return Error(E, diag::note_expr_divide_by_zero);
9735
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009736 ComplexValue LHS = Result;
9737 APSInt Den = RHS.getComplexIntReal() * RHS.getComplexIntReal() +
9738 RHS.getComplexIntImag() * RHS.getComplexIntImag();
9739 Result.getComplexIntReal() =
9740 (LHS.getComplexIntReal() * RHS.getComplexIntReal() +
9741 LHS.getComplexIntImag() * RHS.getComplexIntImag()) / Den;
9742 Result.getComplexIntImag() =
9743 (LHS.getComplexIntImag() * RHS.getComplexIntReal() -
9744 LHS.getComplexIntReal() * RHS.getComplexIntImag()) / Den;
9745 }
9746 break;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009747 }
9748
John McCall93d91dc2010-05-07 17:22:02 +00009749 return true;
Anders Carlsson9ddf7be2008-11-16 21:51:21 +00009750}
9751
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009752bool ComplexExprEvaluator::VisitUnaryOperator(const UnaryOperator *E) {
9753 // Get the operand value into 'Result'.
9754 if (!Visit(E->getSubExpr()))
9755 return false;
9756
9757 switch (E->getOpcode()) {
9758 default:
Richard Smithf57d8cb2011-12-09 22:58:01 +00009759 return Error(E);
Abramo Bagnara9e0e7092010-12-11 16:05:48 +00009760 case UO_Extension:
9761 return true;
9762 case UO_Plus:
9763 // The result is always just the subexpr.
9764 return true;
9765 case UO_Minus:
9766 if (Result.isComplexFloat()) {
9767 Result.getComplexFloatReal().changeSign();
9768 Result.getComplexFloatImag().changeSign();
9769 }
9770 else {
9771 Result.getComplexIntReal() = -Result.getComplexIntReal();
9772 Result.getComplexIntImag() = -Result.getComplexIntImag();
9773 }
9774 return true;
9775 case UO_Not:
9776 if (Result.isComplexFloat())
9777 Result.getComplexFloatImag().changeSign();
9778 else
9779 Result.getComplexIntImag() = -Result.getComplexIntImag();
9780 return true;
9781 }
9782}
9783
Eli Friedmanc4b251d2012-01-10 04:58:17 +00009784bool ComplexExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
9785 if (E->getNumInits() == 2) {
9786 if (E->getType()->isComplexType()) {
9787 Result.makeComplexFloat();
9788 if (!EvaluateFloat(E->getInit(0), Result.FloatReal, Info))
9789 return false;
9790 if (!EvaluateFloat(E->getInit(1), Result.FloatImag, Info))
9791 return false;
9792 } else {
9793 Result.makeComplexInt();
9794 if (!EvaluateInteger(E->getInit(0), Result.IntReal, Info))
9795 return false;
9796 if (!EvaluateInteger(E->getInit(1), Result.IntImag, Info))
9797 return false;
9798 }
9799 return true;
9800 }
9801 return ExprEvaluatorBaseTy::VisitInitListExpr(E);
9802}
9803
Anders Carlsson537969c2008-11-16 20:27:53 +00009804//===----------------------------------------------------------------------===//
Richard Smitha23ab512013-05-23 00:30:41 +00009805// Atomic expression evaluation, essentially just handling the NonAtomicToAtomic
9806// implicit conversion.
9807//===----------------------------------------------------------------------===//
9808
9809namespace {
9810class AtomicExprEvaluator :
Aaron Ballman68af21c2014-01-03 19:26:43 +00009811 public ExprEvaluatorBase<AtomicExprEvaluator> {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009812 const LValue *This;
Richard Smitha23ab512013-05-23 00:30:41 +00009813 APValue &Result;
9814public:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009815 AtomicExprEvaluator(EvalInfo &Info, const LValue *This, APValue &Result)
9816 : ExprEvaluatorBaseTy(Info), This(This), Result(Result) {}
Richard Smitha23ab512013-05-23 00:30:41 +00009817
9818 bool Success(const APValue &V, const Expr *E) {
9819 Result = V;
9820 return true;
9821 }
9822
9823 bool ZeroInitialization(const Expr *E) {
9824 ImplicitValueInitExpr VIE(
9825 E->getType()->castAs<AtomicType>()->getValueType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009826 // For atomic-qualified class (and array) types in C++, initialize the
9827 // _Atomic-wrapped subobject directly, in-place.
9828 return This ? EvaluateInPlace(Result, Info, *This, &VIE)
9829 : Evaluate(Result, Info, &VIE);
Richard Smitha23ab512013-05-23 00:30:41 +00009830 }
9831
9832 bool VisitCastExpr(const CastExpr *E) {
9833 switch (E->getCastKind()) {
9834 default:
9835 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9836 case CK_NonAtomicToAtomic:
Richard Smith64cb9ca2017-02-22 22:09:50 +00009837 return This ? EvaluateInPlace(Result, Info, *This, E->getSubExpr())
9838 : Evaluate(Result, Info, E->getSubExpr());
Richard Smitha23ab512013-05-23 00:30:41 +00009839 }
9840 }
9841};
9842} // end anonymous namespace
9843
Richard Smith64cb9ca2017-02-22 22:09:50 +00009844static bool EvaluateAtomic(const Expr *E, const LValue *This, APValue &Result,
9845 EvalInfo &Info) {
Richard Smitha23ab512013-05-23 00:30:41 +00009846 assert(E->isRValue() && E->getType()->isAtomicType());
Richard Smith64cb9ca2017-02-22 22:09:50 +00009847 return AtomicExprEvaluator(Info, This, Result).Visit(E);
Richard Smitha23ab512013-05-23 00:30:41 +00009848}
9849
9850//===----------------------------------------------------------------------===//
Richard Smith42d3af92011-12-07 00:43:50 +00009851// Void expression evaluation, primarily for a cast to void on the LHS of a
9852// comma operator
9853//===----------------------------------------------------------------------===//
9854
9855namespace {
9856class VoidExprEvaluator
Aaron Ballman68af21c2014-01-03 19:26:43 +00009857 : public ExprEvaluatorBase<VoidExprEvaluator> {
Richard Smith42d3af92011-12-07 00:43:50 +00009858public:
9859 VoidExprEvaluator(EvalInfo &Info) : ExprEvaluatorBaseTy(Info) {}
9860
Richard Smith2e312c82012-03-03 22:46:17 +00009861 bool Success(const APValue &V, const Expr *e) { return true; }
Richard Smith42d3af92011-12-07 00:43:50 +00009862
Richard Smith7cd577b2017-08-17 19:35:50 +00009863 bool ZeroInitialization(const Expr *E) { return true; }
9864
Richard Smith42d3af92011-12-07 00:43:50 +00009865 bool VisitCastExpr(const CastExpr *E) {
9866 switch (E->getCastKind()) {
9867 default:
9868 return ExprEvaluatorBaseTy::VisitCastExpr(E);
9869 case CK_ToVoid:
9870 VisitIgnoredValue(E->getSubExpr());
9871 return true;
9872 }
9873 }
Hal Finkela8443c32014-07-17 14:49:58 +00009874
9875 bool VisitCallExpr(const CallExpr *E) {
9876 switch (E->getBuiltinCallee()) {
9877 default:
9878 return ExprEvaluatorBaseTy::VisitCallExpr(E);
9879 case Builtin::BI__assume:
Hal Finkelbcc06082014-09-07 22:58:14 +00009880 case Builtin::BI__builtin_assume:
Hal Finkela8443c32014-07-17 14:49:58 +00009881 // The argument is not evaluated!
9882 return true;
9883 }
9884 }
Richard Smith42d3af92011-12-07 00:43:50 +00009885};
9886} // end anonymous namespace
9887
9888static bool EvaluateVoid(const Expr *E, EvalInfo &Info) {
9889 assert(E->isRValue() && E->getType()->isVoidType());
9890 return VoidExprEvaluator(Info).Visit(E);
9891}
9892
9893//===----------------------------------------------------------------------===//
Richard Smith7b553f12011-10-29 00:50:52 +00009894// Top level Expr::EvaluateAsRValue method.
Chris Lattner05706e882008-07-11 18:11:29 +00009895//===----------------------------------------------------------------------===//
9896
Richard Smith2e312c82012-03-03 22:46:17 +00009897static bool Evaluate(APValue &Result, EvalInfo &Info, const Expr *E) {
Richard Smith11562c52011-10-28 17:51:58 +00009898 // In C, function designators are not lvalues, but we evaluate them as if they
9899 // are.
Richard Smitha23ab512013-05-23 00:30:41 +00009900 QualType T = E->getType();
9901 if (E->isGLValue() || T->isFunctionType()) {
Richard Smith11562c52011-10-28 17:51:58 +00009902 LValue LV;
9903 if (!EvaluateLValue(E, LV, Info))
9904 return false;
9905 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009906 } else if (T->isVectorType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009907 if (!EvaluateVector(E, Result, Info))
Nate Begeman2f2bdeb2009-01-18 03:20:47 +00009908 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009909 } else if (T->isIntegralOrEnumerationType()) {
Richard Smith725810a2011-10-16 21:26:27 +00009910 if (!IntExprEvaluator(Info, Result).Visit(E))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009911 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009912 } else if (T->hasPointerRepresentation()) {
John McCall45d55e42010-05-07 21:00:08 +00009913 LValue LV;
9914 if (!EvaluatePointer(E, LV, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009915 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009916 LV.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009917 } else if (T->isRealFloatingType()) {
John McCall45d55e42010-05-07 21:00:08 +00009918 llvm::APFloat F(0.0);
9919 if (!EvaluateFloat(E, F, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009920 return false;
Richard Smith2e312c82012-03-03 22:46:17 +00009921 Result = APValue(F);
Richard Smitha23ab512013-05-23 00:30:41 +00009922 } else if (T->isAnyComplexType()) {
John McCall45d55e42010-05-07 21:00:08 +00009923 ComplexValue C;
9924 if (!EvaluateComplex(E, C, Info))
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009925 return false;
Richard Smith725810a2011-10-16 21:26:27 +00009926 C.moveInto(Result);
Richard Smitha23ab512013-05-23 00:30:41 +00009927 } else if (T->isMemberPointerType()) {
Richard Smith027bf112011-11-17 22:56:20 +00009928 MemberPtr P;
9929 if (!EvaluateMemberPointer(E, P, Info))
9930 return false;
9931 P.moveInto(Result);
9932 return true;
Richard Smitha23ab512013-05-23 00:30:41 +00009933 } else if (T->isArrayType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009934 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009935 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009936 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9937 if (!EvaluateArray(E, LV, Value, Info))
Richard Smithf3e9e432011-11-07 09:22:26 +00009938 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009939 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009940 } else if (T->isRecordType()) {
Richard Smithd62306a2011-11-10 06:34:14 +00009941 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +00009942 LV.set(E, Info.CurrentCall->Index);
Richard Smith08d6a2c2013-07-24 07:11:57 +00009943 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9944 if (!EvaluateRecord(E, LV, Value, Info))
Richard Smithd62306a2011-11-10 06:34:14 +00009945 return false;
Richard Smith08d6a2c2013-07-24 07:11:57 +00009946 Result = Value;
Richard Smitha23ab512013-05-23 00:30:41 +00009947 } else if (T->isVoidType()) {
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009948 if (!Info.getLangOpts().CPlusPlus11)
Richard Smithce1ec5e2012-03-15 04:53:45 +00009949 Info.CCEDiag(E, diag::note_constexpr_nonliteral)
Richard Smith357362d2011-12-13 06:39:58 +00009950 << E->getType();
Richard Smith42d3af92011-12-07 00:43:50 +00009951 if (!EvaluateVoid(E, Info))
9952 return false;
Richard Smitha23ab512013-05-23 00:30:41 +00009953 } else if (T->isAtomicType()) {
Richard Smith64cb9ca2017-02-22 22:09:50 +00009954 QualType Unqual = T.getAtomicUnqualifiedType();
9955 if (Unqual->isArrayType() || Unqual->isRecordType()) {
9956 LValue LV;
9957 LV.set(E, Info.CurrentCall->Index);
9958 APValue &Value = Info.CurrentCall->createTemporary(E, false);
9959 if (!EvaluateAtomic(E, &LV, Value, Info))
9960 return false;
9961 } else {
9962 if (!EvaluateAtomic(E, nullptr, Result, Info))
9963 return false;
9964 }
Richard Smith2bf7fdb2013-01-02 11:42:31 +00009965 } else if (Info.getLangOpts().CPlusPlus11) {
Faisal Valie690b7a2016-07-02 22:34:24 +00009966 Info.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
Richard Smith357362d2011-12-13 06:39:58 +00009967 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009968 } else {
Faisal Valie690b7a2016-07-02 22:34:24 +00009969 Info.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
Anders Carlsson7c282e42008-11-22 22:56:32 +00009970 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +00009971 }
Anders Carlsson475f4bc2008-11-22 21:50:49 +00009972
Anders Carlsson7b6f0af2008-11-30 16:58:53 +00009973 return true;
9974}
9975
Richard Smithb228a862012-02-15 02:18:13 +00009976/// EvaluateInPlace - Evaluate an expression in-place in an APValue. In some
9977/// cases, the in-place evaluation is essential, since later initializers for
9978/// an object can indirectly refer to subobjects which were initialized earlier.
9979static bool EvaluateInPlace(APValue &Result, EvalInfo &Info, const LValue &This,
Richard Smith7525ff62013-05-09 07:14:00 +00009980 const Expr *E, bool AllowNonLiteralTypes) {
Argyrios Kyrtzidis3d9e3822014-02-20 04:00:01 +00009981 assert(!E->isValueDependent());
9982
Richard Smith7525ff62013-05-09 07:14:00 +00009983 if (!AllowNonLiteralTypes && !CheckLiteralType(Info, E, &This))
Richard Smithfddd3842011-12-30 21:15:51 +00009984 return false;
9985
9986 if (E->isRValue()) {
Richard Smithed5165f2011-11-04 05:33:44 +00009987 // Evaluate arrays and record types in-place, so that later initializers can
9988 // refer to earlier-initialized members of the object.
Richard Smith64cb9ca2017-02-22 22:09:50 +00009989 QualType T = E->getType();
9990 if (T->isArrayType())
Richard Smithd62306a2011-11-10 06:34:14 +00009991 return EvaluateArray(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009992 else if (T->isRecordType())
Richard Smithd62306a2011-11-10 06:34:14 +00009993 return EvaluateRecord(E, This, Result, Info);
Richard Smith64cb9ca2017-02-22 22:09:50 +00009994 else if (T->isAtomicType()) {
9995 QualType Unqual = T.getAtomicUnqualifiedType();
9996 if (Unqual->isArrayType() || Unqual->isRecordType())
9997 return EvaluateAtomic(E, &This, Result, Info);
9998 }
Richard Smithed5165f2011-11-04 05:33:44 +00009999 }
10000
10001 // For any other type, in-place evaluation is unimportant.
Richard Smith2e312c82012-03-03 22:46:17 +000010002 return Evaluate(Result, Info, E);
Richard Smithed5165f2011-11-04 05:33:44 +000010003}
10004
Richard Smithf57d8cb2011-12-09 22:58:01 +000010005/// EvaluateAsRValue - Try to evaluate this expression, performing an implicit
10006/// lvalue-to-rvalue cast if it is an lvalue.
10007static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
James Dennett0492ef02014-03-14 17:44:10 +000010008 if (E->getType().isNull())
10009 return false;
10010
Nick Lewyckyc190f962017-05-02 01:06:16 +000010011 if (!CheckLiteralType(Info, E))
Richard Smithfddd3842011-12-30 21:15:51 +000010012 return false;
10013
Richard Smith2e312c82012-03-03 22:46:17 +000010014 if (!::Evaluate(Result, Info, E))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010015 return false;
10016
10017 if (E->isGLValue()) {
10018 LValue LV;
Richard Smith2e312c82012-03-03 22:46:17 +000010019 LV.setFrom(Info.Ctx, Result);
Richard Smith243ef902013-05-05 23:31:59 +000010020 if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
Richard Smithf57d8cb2011-12-09 22:58:01 +000010021 return false;
10022 }
10023
Richard Smith2e312c82012-03-03 22:46:17 +000010024 // Check this core constant expression is a constant expression.
Richard Smithb228a862012-02-15 02:18:13 +000010025 return CheckConstantExpression(Info, E->getExprLoc(), E->getType(), Result);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010026}
Richard Smith11562c52011-10-28 17:51:58 +000010027
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010028static bool FastEvaluateAsRValue(const Expr *Exp, Expr::EvalResult &Result,
Richard Smith9f7df0c2017-06-26 23:19:32 +000010029 const ASTContext &Ctx, bool &IsConst) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010030 // Fast-path evaluations of integer literals, since we sometimes see files
10031 // containing vast quantities of these.
10032 if (const IntegerLiteral *L = dyn_cast<IntegerLiteral>(Exp)) {
10033 Result.Val = APValue(APSInt(L->getValue(),
10034 L->getType()->isUnsignedIntegerType()));
10035 IsConst = true;
10036 return true;
10037 }
James Dennett0492ef02014-03-14 17:44:10 +000010038
10039 // This case should be rare, but we need to check it before we check on
10040 // the type below.
10041 if (Exp->getType().isNull()) {
10042 IsConst = false;
10043 return true;
10044 }
Daniel Jasperffdee092017-05-02 19:21:42 +000010045
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010046 // FIXME: Evaluating values of large array and record types can cause
10047 // performance problems. Only do so in C++11 for now.
10048 if (Exp->isRValue() && (Exp->getType()->isArrayType() ||
10049 Exp->getType()->isRecordType()) &&
Richard Smith9f7df0c2017-06-26 23:19:32 +000010050 !Ctx.getLangOpts().CPlusPlus11) {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010051 IsConst = false;
10052 return true;
10053 }
10054 return false;
10055}
10056
10057
Richard Smith7b553f12011-10-29 00:50:52 +000010058/// EvaluateAsRValue - Return true if this is a constant which we can fold using
John McCallc07a0c72011-02-17 10:25:35 +000010059/// any crazy technique (that has nothing to do with language standards) that
10060/// we want to. If this function returns true, it returns the folded constant
Richard Smith11562c52011-10-28 17:51:58 +000010061/// in Result. If this expression is a glvalue, an lvalue-to-rvalue conversion
10062/// will be applied to the result.
Richard Smith7b553f12011-10-29 00:50:52 +000010063bool Expr::EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010064 bool IsConst;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010065 if (FastEvaluateAsRValue(this, Result, Ctx, IsConst))
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010066 return IsConst;
Daniel Jasperffdee092017-05-02 19:21:42 +000010067
Richard Smith6d4c6582013-11-05 22:18:15 +000010068 EvalInfo Info(Ctx, Result, EvalInfo::EM_IgnoreSideEffects);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010069 return ::EvaluateAsRValue(Info, this, Result.Val);
John McCallc07a0c72011-02-17 10:25:35 +000010070}
10071
Jay Foad39c79802011-01-12 09:06:06 +000010072bool Expr::EvaluateAsBooleanCondition(bool &Result,
10073 const ASTContext &Ctx) const {
Richard Smith11562c52011-10-28 17:51:58 +000010074 EvalResult Scratch;
Richard Smith7b553f12011-10-29 00:50:52 +000010075 return EvaluateAsRValue(Scratch, Ctx) &&
Richard Smith2e312c82012-03-03 22:46:17 +000010076 HandleConversionToBool(Scratch.Val, Result);
John McCall1be1c632010-01-05 23:42:56 +000010077}
10078
Richard Smithce8eca52015-12-08 03:21:47 +000010079static bool hasUnacceptableSideEffect(Expr::EvalStatus &Result,
10080 Expr::SideEffectsKind SEK) {
10081 return (SEK < Expr::SE_AllowSideEffects && Result.HasSideEffects) ||
10082 (SEK < Expr::SE_AllowUndefinedBehavior && Result.HasUndefinedBehavior);
10083}
10084
Richard Smith5fab0c92011-12-28 19:48:30 +000010085bool Expr::EvaluateAsInt(APSInt &Result, const ASTContext &Ctx,
10086 SideEffectsKind AllowSideEffects) const {
10087 if (!getType()->isIntegralOrEnumerationType())
10088 return false;
10089
Richard Smith11562c52011-10-28 17:51:58 +000010090 EvalResult ExprResult;
Richard Smith5fab0c92011-12-28 19:48:30 +000010091 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isInt() ||
Richard Smithce8eca52015-12-08 03:21:47 +000010092 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
Richard Smith11562c52011-10-28 17:51:58 +000010093 return false;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010094
Richard Smith11562c52011-10-28 17:51:58 +000010095 Result = ExprResult.Val.getInt();
10096 return true;
Richard Smithcaf33902011-10-10 18:28:20 +000010097}
10098
Richard Trieube234c32016-04-21 21:04:55 +000010099bool Expr::EvaluateAsFloat(APFloat &Result, const ASTContext &Ctx,
10100 SideEffectsKind AllowSideEffects) const {
10101 if (!getType()->isRealFloatingType())
10102 return false;
10103
10104 EvalResult ExprResult;
10105 if (!EvaluateAsRValue(ExprResult, Ctx) || !ExprResult.Val.isFloat() ||
10106 hasUnacceptableSideEffect(ExprResult, AllowSideEffects))
10107 return false;
10108
10109 Result = ExprResult.Val.getFloat();
10110 return true;
10111}
10112
Jay Foad39c79802011-01-12 09:06:06 +000010113bool Expr::EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx) const {
Richard Smith6d4c6582013-11-05 22:18:15 +000010114 EvalInfo Info(Ctx, Result, EvalInfo::EM_ConstantFold);
Anders Carlsson43168122009-04-10 04:54:13 +000010115
John McCall45d55e42010-05-07 21:00:08 +000010116 LValue LV;
Richard Smithb228a862012-02-15 02:18:13 +000010117 if (!EvaluateLValue(this, LV, Info) || Result.HasSideEffects ||
10118 !CheckLValueConstantExpression(Info, getExprLoc(),
10119 Ctx.getLValueReferenceType(getType()), LV))
10120 return false;
10121
Richard Smith2e312c82012-03-03 22:46:17 +000010122 LV.moveInto(Result.Val);
Richard Smithb228a862012-02-15 02:18:13 +000010123 return true;
Eli Friedman7d45c482009-09-13 10:17:44 +000010124}
10125
Richard Smithd0b4dd62011-12-19 06:19:21 +000010126bool Expr::EvaluateAsInitializer(APValue &Value, const ASTContext &Ctx,
10127 const VarDecl *VD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010128 SmallVectorImpl<PartialDiagnosticAt> &Notes) const {
Richard Smithdafff942012-01-14 04:30:29 +000010129 // FIXME: Evaluating initializers for large array and record types can cause
10130 // performance problems. Only do so in C++11 for now.
10131 if (isRValue() && (getType()->isArrayType() || getType()->isRecordType()) &&
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010132 !Ctx.getLangOpts().CPlusPlus11)
Richard Smithdafff942012-01-14 04:30:29 +000010133 return false;
10134
Richard Smithd0b4dd62011-12-19 06:19:21 +000010135 Expr::EvalStatus EStatus;
10136 EStatus.Diag = &Notes;
10137
Richard Smith0c6124b2015-12-03 01:36:22 +000010138 EvalInfo InitInfo(Ctx, EStatus, VD->isConstexpr()
10139 ? EvalInfo::EM_ConstantExpression
10140 : EvalInfo::EM_ConstantFold);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010141 InitInfo.setEvaluatingDecl(VD, Value);
10142
10143 LValue LVal;
10144 LVal.set(VD);
10145
Richard Smithfddd3842011-12-30 21:15:51 +000010146 // C++11 [basic.start.init]p2:
10147 // Variables with static storage duration or thread storage duration shall be
10148 // zero-initialized before any other initialization takes place.
10149 // This behavior is not present in C.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010150 if (Ctx.getLangOpts().CPlusPlus && !VD->hasLocalStorage() &&
Richard Smithfddd3842011-12-30 21:15:51 +000010151 !VD->getType()->isReferenceType()) {
10152 ImplicitValueInitExpr VIE(VD->getType());
Richard Smith7525ff62013-05-09 07:14:00 +000010153 if (!EvaluateInPlace(Value, InitInfo, LVal, &VIE,
Richard Smithb228a862012-02-15 02:18:13 +000010154 /*AllowNonLiteralTypes=*/true))
Richard Smithfddd3842011-12-30 21:15:51 +000010155 return false;
10156 }
10157
Richard Smith7525ff62013-05-09 07:14:00 +000010158 if (!EvaluateInPlace(Value, InitInfo, LVal, this,
10159 /*AllowNonLiteralTypes=*/true) ||
Richard Smithb228a862012-02-15 02:18:13 +000010160 EStatus.HasSideEffects)
10161 return false;
10162
10163 return CheckConstantExpression(InitInfo, VD->getLocation(), VD->getType(),
10164 Value);
Richard Smithd0b4dd62011-12-19 06:19:21 +000010165}
10166
Richard Smith7b553f12011-10-29 00:50:52 +000010167/// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
10168/// constant folded, but discard the result.
Richard Smithce8eca52015-12-08 03:21:47 +000010169bool Expr::isEvaluatable(const ASTContext &Ctx, SideEffectsKind SEK) const {
Anders Carlsson5b3638b2008-12-01 06:44:05 +000010170 EvalResult Result;
Richard Smithce8eca52015-12-08 03:21:47 +000010171 return EvaluateAsRValue(Result, Ctx) &&
10172 !hasUnacceptableSideEffect(Result, SEK);
Chris Lattnercb136912008-10-06 06:49:02 +000010173}
Anders Carlsson59689ed2008-11-22 21:04:56 +000010174
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010175APSInt Expr::EvaluateKnownConstInt(const ASTContext &Ctx,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010176 SmallVectorImpl<PartialDiagnosticAt> *Diag) const {
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010177 EvalResult EvalResult;
Fariborz Jahanian8b115b72013-01-09 23:04:56 +000010178 EvalResult.Diag = Diag;
Richard Smith7b553f12011-10-29 00:50:52 +000010179 bool Result = EvaluateAsRValue(EvalResult, Ctx);
Jeffrey Yasskinb3321532010-12-23 01:01:28 +000010180 (void)Result;
Anders Carlsson59689ed2008-11-22 21:04:56 +000010181 assert(Result && "Could not evaluate expression");
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010182 assert(EvalResult.Val.isInt() && "Expression did not evaluate to integer");
Anders Carlsson59689ed2008-11-22 21:04:56 +000010183
Anders Carlsson6736d1a22008-12-19 20:58:05 +000010184 return EvalResult.Val.getInt();
Anders Carlsson59689ed2008-11-22 21:04:56 +000010185}
John McCall864e3962010-05-07 05:32:02 +000010186
Richard Smithe9ff7702013-11-05 22:23:30 +000010187void Expr::EvaluateForOverflow(const ASTContext &Ctx) const {
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010188 bool IsConst;
10189 EvalResult EvalResult;
Richard Smith9f7df0c2017-06-26 23:19:32 +000010190 if (!FastEvaluateAsRValue(this, EvalResult, Ctx, IsConst)) {
Richard Smith6d4c6582013-11-05 22:18:15 +000010191 EvalInfo Info(Ctx, EvalResult, EvalInfo::EM_EvaluateForOverflow);
Fariborz Jahaniane735ff92013-01-24 22:11:45 +000010192 (void)::EvaluateAsRValue(Info, this, EvalResult.Val);
10193 }
10194}
10195
Richard Smithe6c01442013-06-05 00:46:14 +000010196bool Expr::EvalResult::isGlobalLValue() const {
10197 assert(Val.isLValue());
10198 return IsGlobalLValue(Val.getLValueBase());
10199}
Abramo Bagnaraf8199452010-05-14 17:07:14 +000010200
10201
John McCall864e3962010-05-07 05:32:02 +000010202/// isIntegerConstantExpr - this recursive routine will test if an expression is
10203/// an integer constant expression.
10204
10205/// FIXME: Pass up a reason why! Invalid operation in i-c-e, division by zero,
10206/// comma, etc
John McCall864e3962010-05-07 05:32:02 +000010207
10208// CheckICE - This function does the fundamental ICE checking: the returned
Richard Smith9e575da2012-12-28 13:25:52 +000010209// ICEDiag contains an ICEKind indicating whether the expression is an ICE,
10210// and a (possibly null) SourceLocation indicating the location of the problem.
10211//
John McCall864e3962010-05-07 05:32:02 +000010212// Note that to reduce code duplication, this helper does no evaluation
10213// itself; the caller checks whether the expression is evaluatable, and
10214// in the rare cases where CheckICE actually cares about the evaluated
George Burgess IV57317072017-02-02 07:53:55 +000010215// value, it calls into Evaluate.
John McCall864e3962010-05-07 05:32:02 +000010216
Dan Gohman28ade552010-07-26 21:25:24 +000010217namespace {
10218
Richard Smith9e575da2012-12-28 13:25:52 +000010219enum ICEKind {
10220 /// This expression is an ICE.
10221 IK_ICE,
10222 /// This expression is not an ICE, but if it isn't evaluated, it's
10223 /// a legal subexpression for an ICE. This return value is used to handle
10224 /// the comma operator in C99 mode, and non-constant subexpressions.
10225 IK_ICEIfUnevaluated,
10226 /// This expression is not an ICE, and is not a legal subexpression for one.
10227 IK_NotICE
10228};
10229
John McCall864e3962010-05-07 05:32:02 +000010230struct ICEDiag {
Richard Smith9e575da2012-12-28 13:25:52 +000010231 ICEKind Kind;
John McCall864e3962010-05-07 05:32:02 +000010232 SourceLocation Loc;
10233
Richard Smith9e575da2012-12-28 13:25:52 +000010234 ICEDiag(ICEKind IK, SourceLocation l) : Kind(IK), Loc(l) {}
John McCall864e3962010-05-07 05:32:02 +000010235};
10236
Alexander Kornienkoab9db512015-06-22 23:07:51 +000010237}
Dan Gohman28ade552010-07-26 21:25:24 +000010238
Richard Smith9e575da2012-12-28 13:25:52 +000010239static ICEDiag NoDiag() { return ICEDiag(IK_ICE, SourceLocation()); }
10240
10241static ICEDiag Worst(ICEDiag A, ICEDiag B) { return A.Kind >= B.Kind ? A : B; }
John McCall864e3962010-05-07 05:32:02 +000010242
Craig Toppera31a8822013-08-22 07:09:37 +000010243static ICEDiag CheckEvalInICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010244 Expr::EvalResult EVResult;
Richard Smith7b553f12011-10-29 00:50:52 +000010245 if (!E->EvaluateAsRValue(EVResult, Ctx) || EVResult.HasSideEffects ||
Richard Smith9e575da2012-12-28 13:25:52 +000010246 !EVResult.Val.isInt())
10247 return ICEDiag(IK_NotICE, E->getLocStart());
10248
John McCall864e3962010-05-07 05:32:02 +000010249 return NoDiag();
10250}
10251
Craig Toppera31a8822013-08-22 07:09:37 +000010252static ICEDiag CheckICE(const Expr* E, const ASTContext &Ctx) {
John McCall864e3962010-05-07 05:32:02 +000010253 assert(!E->isValueDependent() && "Should not see value dependent exprs!");
Richard Smith9e575da2012-12-28 13:25:52 +000010254 if (!E->getType()->isIntegralOrEnumerationType())
10255 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010256
10257 switch (E->getStmtClass()) {
John McCallbd066782011-02-09 08:16:59 +000010258#define ABSTRACT_STMT(Node)
John McCall864e3962010-05-07 05:32:02 +000010259#define STMT(Node, Base) case Expr::Node##Class:
10260#define EXPR(Node, Base)
10261#include "clang/AST/StmtNodes.inc"
10262 case Expr::PredefinedExprClass:
10263 case Expr::FloatingLiteralClass:
10264 case Expr::ImaginaryLiteralClass:
10265 case Expr::StringLiteralClass:
10266 case Expr::ArraySubscriptExprClass:
Alexey Bataev1a3320e2015-08-25 14:24:04 +000010267 case Expr::OMPArraySectionExprClass:
John McCall864e3962010-05-07 05:32:02 +000010268 case Expr::MemberExprClass:
10269 case Expr::CompoundAssignOperatorClass:
10270 case Expr::CompoundLiteralExprClass:
10271 case Expr::ExtVectorElementExprClass:
John McCall864e3962010-05-07 05:32:02 +000010272 case Expr::DesignatedInitExprClass:
Richard Smith410306b2016-12-12 02:53:20 +000010273 case Expr::ArrayInitLoopExprClass:
10274 case Expr::ArrayInitIndexExprClass:
Yunzhong Gaocb779302015-06-10 00:27:52 +000010275 case Expr::NoInitExprClass:
10276 case Expr::DesignatedInitUpdateExprClass:
John McCall864e3962010-05-07 05:32:02 +000010277 case Expr::ImplicitValueInitExprClass:
10278 case Expr::ParenListExprClass:
10279 case Expr::VAArgExprClass:
10280 case Expr::AddrLabelExprClass:
10281 case Expr::StmtExprClass:
10282 case Expr::CXXMemberCallExprClass:
Peter Collingbourne41f85462011-02-09 21:07:24 +000010283 case Expr::CUDAKernelCallExprClass:
John McCall864e3962010-05-07 05:32:02 +000010284 case Expr::CXXDynamicCastExprClass:
10285 case Expr::CXXTypeidExprClass:
Francois Pichet5cc0a672010-09-08 23:47:05 +000010286 case Expr::CXXUuidofExprClass:
John McCall5e77d762013-04-16 07:28:30 +000010287 case Expr::MSPropertyRefExprClass:
Alexey Bataevf7630272015-11-25 12:01:00 +000010288 case Expr::MSPropertySubscriptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010289 case Expr::CXXNullPtrLiteralExprClass:
Richard Smithc67fdd42012-03-07 08:35:16 +000010290 case Expr::UserDefinedLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010291 case Expr::CXXThisExprClass:
10292 case Expr::CXXThrowExprClass:
10293 case Expr::CXXNewExprClass:
10294 case Expr::CXXDeleteExprClass:
10295 case Expr::CXXPseudoDestructorExprClass:
10296 case Expr::UnresolvedLookupExprClass:
Kaelyn Takatae1f49d52014-10-27 18:07:20 +000010297 case Expr::TypoExprClass:
John McCall864e3962010-05-07 05:32:02 +000010298 case Expr::DependentScopeDeclRefExprClass:
10299 case Expr::CXXConstructExprClass:
Richard Smith5179eb72016-06-28 19:03:57 +000010300 case Expr::CXXInheritedCtorInitExprClass:
Richard Smithcc1b96d2013-06-12 22:31:48 +000010301 case Expr::CXXStdInitializerListExprClass:
John McCall864e3962010-05-07 05:32:02 +000010302 case Expr::CXXBindTemporaryExprClass:
John McCall5d413782010-12-06 08:20:24 +000010303 case Expr::ExprWithCleanupsClass:
John McCall864e3962010-05-07 05:32:02 +000010304 case Expr::CXXTemporaryObjectExprClass:
10305 case Expr::CXXUnresolvedConstructExprClass:
10306 case Expr::CXXDependentScopeMemberExprClass:
10307 case Expr::UnresolvedMemberExprClass:
10308 case Expr::ObjCStringLiteralClass:
Patrick Beard0caa3942012-04-19 00:25:12 +000010309 case Expr::ObjCBoxedExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010310 case Expr::ObjCArrayLiteralClass:
10311 case Expr::ObjCDictionaryLiteralClass:
John McCall864e3962010-05-07 05:32:02 +000010312 case Expr::ObjCEncodeExprClass:
10313 case Expr::ObjCMessageExprClass:
10314 case Expr::ObjCSelectorExprClass:
10315 case Expr::ObjCProtocolExprClass:
10316 case Expr::ObjCIvarRefExprClass:
10317 case Expr::ObjCPropertyRefExprClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010318 case Expr::ObjCSubscriptRefExprClass:
John McCall864e3962010-05-07 05:32:02 +000010319 case Expr::ObjCIsaExprClass:
Erik Pilkington29099de2016-07-16 00:35:23 +000010320 case Expr::ObjCAvailabilityCheckExprClass:
John McCall864e3962010-05-07 05:32:02 +000010321 case Expr::ShuffleVectorExprClass:
Hal Finkelc4d7c822013-09-18 03:29:45 +000010322 case Expr::ConvertVectorExprClass:
John McCall864e3962010-05-07 05:32:02 +000010323 case Expr::BlockExprClass:
John McCall864e3962010-05-07 05:32:02 +000010324 case Expr::NoStmtClass:
John McCall8d69a212010-11-15 23:31:06 +000010325 case Expr::OpaqueValueExprClass:
Douglas Gregore8e9dd62011-01-03 17:17:50 +000010326 case Expr::PackExpansionExprClass:
Douglas Gregorcdbc5392011-01-15 01:15:58 +000010327 case Expr::SubstNonTypeTemplateParmPackExprClass:
Richard Smithb15fe3a2012-09-12 00:56:43 +000010328 case Expr::FunctionParmPackExprClass:
Tanya Lattner55808c12011-06-04 00:47:47 +000010329 case Expr::AsTypeExprClass:
John McCall31168b02011-06-15 23:02:42 +000010330 case Expr::ObjCIndirectCopyRestoreExprClass:
Douglas Gregorfe314812011-06-21 17:03:29 +000010331 case Expr::MaterializeTemporaryExprClass:
John McCallfe96e0b2011-11-06 09:01:30 +000010332 case Expr::PseudoObjectExprClass:
Eli Friedmandf14b3a2011-10-11 02:20:01 +000010333 case Expr::AtomicExprClass:
Douglas Gregore31e6062012-02-07 10:09:13 +000010334 case Expr::LambdaExprClass:
Richard Smith0f0af192014-11-08 05:07:16 +000010335 case Expr::CXXFoldExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010336 case Expr::CoawaitExprClass:
Eric Fiselier20f25cb2017-03-06 23:38:15 +000010337 case Expr::DependentCoawaitExprClass:
Richard Smith9f690bd2015-10-27 06:02:45 +000010338 case Expr::CoyieldExprClass:
Richard Smith9e575da2012-12-28 13:25:52 +000010339 return ICEDiag(IK_NotICE, E->getLocStart());
Sebastian Redl12757ab2011-09-24 17:48:14 +000010340
Richard Smithf137f932014-01-25 20:50:08 +000010341 case Expr::InitListExprClass: {
10342 // C++03 [dcl.init]p13: If T is a scalar type, then a declaration of the
10343 // form "T x = { a };" is equivalent to "T x = a;".
10344 // Unless we're initializing a reference, T is a scalar as it is known to be
10345 // of integral or enumeration type.
10346 if (E->isRValue())
10347 if (cast<InitListExpr>(E)->getNumInits() == 1)
10348 return CheckICE(cast<InitListExpr>(E)->getInit(0), Ctx);
10349 return ICEDiag(IK_NotICE, E->getLocStart());
10350 }
10351
Douglas Gregor820ba7b2011-01-04 17:33:58 +000010352 case Expr::SizeOfPackExprClass:
John McCall864e3962010-05-07 05:32:02 +000010353 case Expr::GNUNullExprClass:
10354 // GCC considers the GNU __null value to be an integral constant expression.
10355 return NoDiag();
10356
John McCall7c454bb2011-07-15 05:09:51 +000010357 case Expr::SubstNonTypeTemplateParmExprClass:
10358 return
10359 CheckICE(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(), Ctx);
10360
John McCall864e3962010-05-07 05:32:02 +000010361 case Expr::ParenExprClass:
10362 return CheckICE(cast<ParenExpr>(E)->getSubExpr(), Ctx);
Peter Collingbourne91147592011-04-15 00:35:48 +000010363 case Expr::GenericSelectionExprClass:
10364 return CheckICE(cast<GenericSelectionExpr>(E)->getResultExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010365 case Expr::IntegerLiteralClass:
10366 case Expr::CharacterLiteralClass:
Ted Kremeneke65b0862012-03-06 20:05:56 +000010367 case Expr::ObjCBoolLiteralExprClass:
John McCall864e3962010-05-07 05:32:02 +000010368 case Expr::CXXBoolLiteralExprClass:
Douglas Gregor747eb782010-07-08 06:14:04 +000010369 case Expr::CXXScalarValueInitExprClass:
Douglas Gregor29c42f22012-02-24 07:38:34 +000010370 case Expr::TypeTraitExprClass:
John Wiegley6242b6a2011-04-28 00:16:57 +000010371 case Expr::ArrayTypeTraitExprClass:
John Wiegleyf9f65842011-04-25 06:54:41 +000010372 case Expr::ExpressionTraitExprClass:
Sebastian Redl4202c0f2010-09-10 20:55:43 +000010373 case Expr::CXXNoexceptExprClass:
John McCall864e3962010-05-07 05:32:02 +000010374 return NoDiag();
10375 case Expr::CallExprClass:
Alexis Hunt3b791862010-08-30 17:47:05 +000010376 case Expr::CXXOperatorCallExprClass: {
Richard Smith62f65952011-10-24 22:35:48 +000010377 // C99 6.6/3 allows function calls within unevaluated subexpressions of
10378 // constant expressions, but they can never be ICEs because an ICE cannot
10379 // contain an operand of (pointer to) function type.
John McCall864e3962010-05-07 05:32:02 +000010380 const CallExpr *CE = cast<CallExpr>(E);
Alp Tokera724cff2013-12-28 21:59:02 +000010381 if (CE->getBuiltinCallee())
John McCall864e3962010-05-07 05:32:02 +000010382 return CheckEvalInICE(E, Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010383 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010384 }
Richard Smith6365c912012-02-24 22:12:32 +000010385 case Expr::DeclRefExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010386 if (isa<EnumConstantDecl>(cast<DeclRefExpr>(E)->getDecl()))
10387 return NoDiag();
Richard Smith6365c912012-02-24 22:12:32 +000010388 const ValueDecl *D = dyn_cast<ValueDecl>(cast<DeclRefExpr>(E)->getDecl());
David Blaikiebbafb8a2012-03-11 07:00:24 +000010389 if (Ctx.getLangOpts().CPlusPlus &&
Richard Smith6365c912012-02-24 22:12:32 +000010390 D && IsConstNonVolatile(D->getType())) {
John McCall864e3962010-05-07 05:32:02 +000010391 // Parameter variables are never constants. Without this check,
10392 // getAnyInitializer() can find a default argument, which leads
10393 // to chaos.
10394 if (isa<ParmVarDecl>(D))
Richard Smith9e575da2012-12-28 13:25:52 +000010395 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010396
10397 // C++ 7.1.5.1p2
10398 // A variable of non-volatile const-qualified integral or enumeration
10399 // type initialized by an ICE can be used in ICEs.
10400 if (const VarDecl *Dcl = dyn_cast<VarDecl>(D)) {
Richard Smithec8dcd22011-11-08 01:31:09 +000010401 if (!Dcl->getType()->isIntegralOrEnumerationType())
Richard Smith9e575da2012-12-28 13:25:52 +000010402 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
Richard Smithec8dcd22011-11-08 01:31:09 +000010403
Richard Smithd0b4dd62011-12-19 06:19:21 +000010404 const VarDecl *VD;
10405 // Look for a declaration of this variable that has an initializer, and
10406 // check whether it is an ICE.
10407 if (Dcl->getAnyInitializer(VD) && VD->checkInitIsICE())
10408 return NoDiag();
10409 else
Richard Smith9e575da2012-12-28 13:25:52 +000010410 return ICEDiag(IK_NotICE, cast<DeclRefExpr>(E)->getLocation());
John McCall864e3962010-05-07 05:32:02 +000010411 }
10412 }
Richard Smith9e575da2012-12-28 13:25:52 +000010413 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith6365c912012-02-24 22:12:32 +000010414 }
John McCall864e3962010-05-07 05:32:02 +000010415 case Expr::UnaryOperatorClass: {
10416 const UnaryOperator *Exp = cast<UnaryOperator>(E);
10417 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010418 case UO_PostInc:
10419 case UO_PostDec:
10420 case UO_PreInc:
10421 case UO_PreDec:
10422 case UO_AddrOf:
10423 case UO_Deref:
Richard Smith9f690bd2015-10-27 06:02:45 +000010424 case UO_Coawait:
Richard Smith62f65952011-10-24 22:35:48 +000010425 // C99 6.6/3 allows increment and decrement within unevaluated
10426 // subexpressions of constant expressions, but they can never be ICEs
10427 // because an ICE cannot contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010428 return ICEDiag(IK_NotICE, E->getLocStart());
John McCalle3027922010-08-25 11:45:40 +000010429 case UO_Extension:
10430 case UO_LNot:
10431 case UO_Plus:
10432 case UO_Minus:
10433 case UO_Not:
10434 case UO_Real:
10435 case UO_Imag:
John McCall864e3962010-05-07 05:32:02 +000010436 return CheckICE(Exp->getSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010437 }
Richard Smith9e575da2012-12-28 13:25:52 +000010438
John McCall864e3962010-05-07 05:32:02 +000010439 // OffsetOf falls through here.
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010440 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010441 }
10442 case Expr::OffsetOfExprClass: {
Richard Smith9e575da2012-12-28 13:25:52 +000010443 // Note that per C99, offsetof must be an ICE. And AFAIK, using
10444 // EvaluateAsRValue matches the proposed gcc behavior for cases like
10445 // "offsetof(struct s{int x[4];}, x[1.0])". This doesn't affect
10446 // compliance: we should warn earlier for offsetof expressions with
10447 // array subscripts that aren't ICEs, and if the array subscripts
10448 // are ICEs, the value of the offsetof must be an integer constant.
10449 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010450 }
Peter Collingbournee190dee2011-03-11 19:24:49 +000010451 case Expr::UnaryExprOrTypeTraitExprClass: {
10452 const UnaryExprOrTypeTraitExpr *Exp = cast<UnaryExprOrTypeTraitExpr>(E);
10453 if ((Exp->getKind() == UETT_SizeOf) &&
10454 Exp->getTypeOfArgument()->isVariableArrayType())
Richard Smith9e575da2012-12-28 13:25:52 +000010455 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010456 return NoDiag();
10457 }
10458 case Expr::BinaryOperatorClass: {
10459 const BinaryOperator *Exp = cast<BinaryOperator>(E);
10460 switch (Exp->getOpcode()) {
John McCalle3027922010-08-25 11:45:40 +000010461 case BO_PtrMemD:
10462 case BO_PtrMemI:
10463 case BO_Assign:
10464 case BO_MulAssign:
10465 case BO_DivAssign:
10466 case BO_RemAssign:
10467 case BO_AddAssign:
10468 case BO_SubAssign:
10469 case BO_ShlAssign:
10470 case BO_ShrAssign:
10471 case BO_AndAssign:
10472 case BO_XorAssign:
10473 case BO_OrAssign:
Richard Smithc70f1d62017-12-14 15:16:18 +000010474 case BO_Cmp: // FIXME: Re-enable once we can evaluate this.
Richard Smith62f65952011-10-24 22:35:48 +000010475 // C99 6.6/3 allows assignments within unevaluated subexpressions of
10476 // constant expressions, but they can never be ICEs because an ICE cannot
10477 // contain an lvalue operand.
Richard Smith9e575da2012-12-28 13:25:52 +000010478 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010479
John McCalle3027922010-08-25 11:45:40 +000010480 case BO_Mul:
10481 case BO_Div:
10482 case BO_Rem:
10483 case BO_Add:
10484 case BO_Sub:
10485 case BO_Shl:
10486 case BO_Shr:
10487 case BO_LT:
10488 case BO_GT:
10489 case BO_LE:
10490 case BO_GE:
10491 case BO_EQ:
10492 case BO_NE:
10493 case BO_And:
10494 case BO_Xor:
10495 case BO_Or:
10496 case BO_Comma: {
John McCall864e3962010-05-07 05:32:02 +000010497 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10498 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
John McCalle3027922010-08-25 11:45:40 +000010499 if (Exp->getOpcode() == BO_Div ||
10500 Exp->getOpcode() == BO_Rem) {
Richard Smith7b553f12011-10-29 00:50:52 +000010501 // EvaluateAsRValue gives an error for undefined Div/Rem, so make sure
John McCall864e3962010-05-07 05:32:02 +000010502 // we don't evaluate one.
Richard Smith9e575da2012-12-28 13:25:52 +000010503 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE) {
Richard Smithcaf33902011-10-10 18:28:20 +000010504 llvm::APSInt REval = Exp->getRHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010505 if (REval == 0)
Richard Smith9e575da2012-12-28 13:25:52 +000010506 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010507 if (REval.isSigned() && REval.isAllOnesValue()) {
Richard Smithcaf33902011-10-10 18:28:20 +000010508 llvm::APSInt LEval = Exp->getLHS()->EvaluateKnownConstInt(Ctx);
John McCall864e3962010-05-07 05:32:02 +000010509 if (LEval.isMinSignedValue())
Richard Smith9e575da2012-12-28 13:25:52 +000010510 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010511 }
10512 }
10513 }
John McCalle3027922010-08-25 11:45:40 +000010514 if (Exp->getOpcode() == BO_Comma) {
David Blaikiebbafb8a2012-03-11 07:00:24 +000010515 if (Ctx.getLangOpts().C99) {
John McCall864e3962010-05-07 05:32:02 +000010516 // C99 6.6p3 introduces a strange edge case: comma can be in an ICE
10517 // if it isn't evaluated.
Richard Smith9e575da2012-12-28 13:25:52 +000010518 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICE)
10519 return ICEDiag(IK_ICEIfUnevaluated, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010520 } else {
10521 // In both C89 and C++, commas in ICEs are illegal.
Richard Smith9e575da2012-12-28 13:25:52 +000010522 return ICEDiag(IK_NotICE, E->getLocStart());
John McCall864e3962010-05-07 05:32:02 +000010523 }
10524 }
Richard Smith9e575da2012-12-28 13:25:52 +000010525 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010526 }
John McCalle3027922010-08-25 11:45:40 +000010527 case BO_LAnd:
10528 case BO_LOr: {
John McCall864e3962010-05-07 05:32:02 +000010529 ICEDiag LHSResult = CheckICE(Exp->getLHS(), Ctx);
10530 ICEDiag RHSResult = CheckICE(Exp->getRHS(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010531 if (LHSResult.Kind == IK_ICE && RHSResult.Kind == IK_ICEIfUnevaluated) {
John McCall864e3962010-05-07 05:32:02 +000010532 // Rare case where the RHS has a comma "side-effect"; we need
10533 // to actually check the condition to see whether the side
10534 // with the comma is evaluated.
John McCalle3027922010-08-25 11:45:40 +000010535 if ((Exp->getOpcode() == BO_LAnd) !=
Richard Smithcaf33902011-10-10 18:28:20 +000010536 (Exp->getLHS()->EvaluateKnownConstInt(Ctx) == 0))
John McCall864e3962010-05-07 05:32:02 +000010537 return RHSResult;
10538 return NoDiag();
10539 }
10540
Richard Smith9e575da2012-12-28 13:25:52 +000010541 return Worst(LHSResult, RHSResult);
John McCall864e3962010-05-07 05:32:02 +000010542 }
10543 }
Galina Kistanovaf87496d2017-06-03 06:31:42 +000010544 LLVM_FALLTHROUGH;
John McCall864e3962010-05-07 05:32:02 +000010545 }
10546 case Expr::ImplicitCastExprClass:
10547 case Expr::CStyleCastExprClass:
10548 case Expr::CXXFunctionalCastExprClass:
10549 case Expr::CXXStaticCastExprClass:
10550 case Expr::CXXReinterpretCastExprClass:
Richard Smithc3e31e72011-10-24 18:26:35 +000010551 case Expr::CXXConstCastExprClass:
John McCall31168b02011-06-15 23:02:42 +000010552 case Expr::ObjCBridgedCastExprClass: {
John McCall864e3962010-05-07 05:32:02 +000010553 const Expr *SubExpr = cast<CastExpr>(E)->getSubExpr();
Richard Smith0b973d02011-12-18 02:33:09 +000010554 if (isa<ExplicitCastExpr>(E)) {
10555 if (const FloatingLiteral *FL
10556 = dyn_cast<FloatingLiteral>(SubExpr->IgnoreParenImpCasts())) {
10557 unsigned DestWidth = Ctx.getIntWidth(E->getType());
10558 bool DestSigned = E->getType()->isSignedIntegerOrEnumerationType();
10559 APSInt IgnoredVal(DestWidth, !DestSigned);
10560 bool Ignored;
10561 // If the value does not fit in the destination type, the behavior is
10562 // undefined, so we are not required to treat it as a constant
10563 // expression.
10564 if (FL->getValue().convertToInteger(IgnoredVal,
10565 llvm::APFloat::rmTowardZero,
10566 &Ignored) & APFloat::opInvalidOp)
Richard Smith9e575da2012-12-28 13:25:52 +000010567 return ICEDiag(IK_NotICE, E->getLocStart());
Richard Smith0b973d02011-12-18 02:33:09 +000010568 return NoDiag();
10569 }
10570 }
Eli Friedman76d4e432011-09-29 21:49:34 +000010571 switch (cast<CastExpr>(E)->getCastKind()) {
10572 case CK_LValueToRValue:
David Chisnallfa35df62012-01-16 17:27:18 +000010573 case CK_AtomicToNonAtomic:
10574 case CK_NonAtomicToAtomic:
Eli Friedman76d4e432011-09-29 21:49:34 +000010575 case CK_NoOp:
10576 case CK_IntegralToBoolean:
10577 case CK_IntegralCast:
John McCall864e3962010-05-07 05:32:02 +000010578 return CheckICE(SubExpr, Ctx);
Eli Friedman76d4e432011-09-29 21:49:34 +000010579 default:
Richard Smith9e575da2012-12-28 13:25:52 +000010580 return ICEDiag(IK_NotICE, E->getLocStart());
Eli Friedman76d4e432011-09-29 21:49:34 +000010581 }
John McCall864e3962010-05-07 05:32:02 +000010582 }
John McCallc07a0c72011-02-17 10:25:35 +000010583 case Expr::BinaryConditionalOperatorClass: {
10584 const BinaryConditionalOperator *Exp = cast<BinaryConditionalOperator>(E);
10585 ICEDiag CommonResult = CheckICE(Exp->getCommon(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010586 if (CommonResult.Kind == IK_NotICE) return CommonResult;
John McCallc07a0c72011-02-17 10:25:35 +000010587 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010588 if (FalseResult.Kind == IK_NotICE) return FalseResult;
10589 if (CommonResult.Kind == IK_ICEIfUnevaluated) return CommonResult;
10590 if (FalseResult.Kind == IK_ICEIfUnevaluated &&
Richard Smith74fc7212012-12-28 12:53:55 +000010591 Exp->getCommon()->EvaluateKnownConstInt(Ctx) != 0) return NoDiag();
John McCallc07a0c72011-02-17 10:25:35 +000010592 return FalseResult;
10593 }
John McCall864e3962010-05-07 05:32:02 +000010594 case Expr::ConditionalOperatorClass: {
10595 const ConditionalOperator *Exp = cast<ConditionalOperator>(E);
10596 // If the condition (ignoring parens) is a __builtin_constant_p call,
10597 // then only the true side is actually considered in an integer constant
10598 // expression, and it is fully evaluated. This is an important GNU
10599 // extension. See GCC PR38377 for discussion.
10600 if (const CallExpr *CallCE
10601 = dyn_cast<CallExpr>(Exp->getCond()->IgnoreParenCasts()))
Alp Tokera724cff2013-12-28 21:59:02 +000010602 if (CallCE->getBuiltinCallee() == Builtin::BI__builtin_constant_p)
Richard Smith5fab0c92011-12-28 19:48:30 +000010603 return CheckEvalInICE(E, Ctx);
John McCall864e3962010-05-07 05:32:02 +000010604 ICEDiag CondResult = CheckICE(Exp->getCond(), Ctx);
Richard Smith9e575da2012-12-28 13:25:52 +000010605 if (CondResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010606 return CondResult;
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010607
Richard Smithf57d8cb2011-12-09 22:58:01 +000010608 ICEDiag TrueResult = CheckICE(Exp->getTrueExpr(), Ctx);
10609 ICEDiag FalseResult = CheckICE(Exp->getFalseExpr(), Ctx);
Douglas Gregorfcafc6e2011-05-24 16:02:01 +000010610
Richard Smith9e575da2012-12-28 13:25:52 +000010611 if (TrueResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010612 return TrueResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010613 if (FalseResult.Kind == IK_NotICE)
John McCall864e3962010-05-07 05:32:02 +000010614 return FalseResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010615 if (CondResult.Kind == IK_ICEIfUnevaluated)
John McCall864e3962010-05-07 05:32:02 +000010616 return CondResult;
Richard Smith9e575da2012-12-28 13:25:52 +000010617 if (TrueResult.Kind == IK_ICE && FalseResult.Kind == IK_ICE)
John McCall864e3962010-05-07 05:32:02 +000010618 return NoDiag();
10619 // Rare case where the diagnostics depend on which side is evaluated
10620 // Note that if we get here, CondResult is 0, and at least one of
10621 // TrueResult and FalseResult is non-zero.
Richard Smith9e575da2012-12-28 13:25:52 +000010622 if (Exp->getCond()->EvaluateKnownConstInt(Ctx) == 0)
John McCall864e3962010-05-07 05:32:02 +000010623 return FalseResult;
John McCall864e3962010-05-07 05:32:02 +000010624 return TrueResult;
10625 }
10626 case Expr::CXXDefaultArgExprClass:
10627 return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
Richard Smith852c9db2013-04-20 22:23:05 +000010628 case Expr::CXXDefaultInitExprClass:
10629 return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010630 case Expr::ChooseExprClass: {
Eli Friedman75807f22013-07-20 00:40:58 +000010631 return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(), Ctx);
John McCall864e3962010-05-07 05:32:02 +000010632 }
10633 }
10634
David Blaikiee4d798f2012-01-20 21:50:17 +000010635 llvm_unreachable("Invalid StmtClass!");
John McCall864e3962010-05-07 05:32:02 +000010636}
10637
Richard Smithf57d8cb2011-12-09 22:58:01 +000010638/// Evaluate an expression as a C++11 integral constant expression.
Craig Toppera31a8822013-08-22 07:09:37 +000010639static bool EvaluateCPlusPlus11IntegralConstantExpr(const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010640 const Expr *E,
10641 llvm::APSInt *Value,
10642 SourceLocation *Loc) {
10643 if (!E->getType()->isIntegralOrEnumerationType()) {
10644 if (Loc) *Loc = E->getExprLoc();
10645 return false;
10646 }
10647
Richard Smith66e05fe2012-01-18 05:21:49 +000010648 APValue Result;
10649 if (!E->isCXX11ConstantExpr(Ctx, &Result, Loc))
Richard Smith92b1ce02011-12-12 09:28:41 +000010650 return false;
10651
Richard Smith98710fc2014-11-13 23:03:19 +000010652 if (!Result.isInt()) {
10653 if (Loc) *Loc = E->getExprLoc();
10654 return false;
10655 }
10656
Richard Smith66e05fe2012-01-18 05:21:49 +000010657 if (Value) *Value = Result.getInt();
Richard Smith92b1ce02011-12-12 09:28:41 +000010658 return true;
Richard Smithf57d8cb2011-12-09 22:58:01 +000010659}
10660
Craig Toppera31a8822013-08-22 07:09:37 +000010661bool Expr::isIntegerConstantExpr(const ASTContext &Ctx,
10662 SourceLocation *Loc) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010663 if (Ctx.getLangOpts().CPlusPlus11)
Craig Topper36250ad2014-05-12 05:36:57 +000010664 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, nullptr, Loc);
Richard Smithf57d8cb2011-12-09 22:58:01 +000010665
Richard Smith9e575da2012-12-28 13:25:52 +000010666 ICEDiag D = CheckICE(this, Ctx);
10667 if (D.Kind != IK_ICE) {
10668 if (Loc) *Loc = D.Loc;
John McCall864e3962010-05-07 05:32:02 +000010669 return false;
10670 }
Richard Smithf57d8cb2011-12-09 22:58:01 +000010671 return true;
10672}
10673
Craig Toppera31a8822013-08-22 07:09:37 +000010674bool Expr::isIntegerConstantExpr(llvm::APSInt &Value, const ASTContext &Ctx,
Richard Smithf57d8cb2011-12-09 22:58:01 +000010675 SourceLocation *Loc, bool isEvaluated) const {
Richard Smith2bf7fdb2013-01-02 11:42:31 +000010676 if (Ctx.getLangOpts().CPlusPlus11)
Richard Smithf57d8cb2011-12-09 22:58:01 +000010677 return EvaluateCPlusPlus11IntegralConstantExpr(Ctx, this, &Value, Loc);
10678
10679 if (!isIntegerConstantExpr(Ctx, Loc))
10680 return false;
Richard Smith5c40f092015-12-04 03:00:44 +000010681 // The only possible side-effects here are due to UB discovered in the
10682 // evaluation (for instance, INT_MAX + 1). In such a case, we are still
10683 // required to treat the expression as an ICE, so we produce the folded
10684 // value.
10685 if (!EvaluateAsInt(Value, Ctx, SE_AllowSideEffects))
John McCall864e3962010-05-07 05:32:02 +000010686 llvm_unreachable("ICE cannot be evaluated!");
John McCall864e3962010-05-07 05:32:02 +000010687 return true;
10688}
Richard Smith66e05fe2012-01-18 05:21:49 +000010689
Craig Toppera31a8822013-08-22 07:09:37 +000010690bool Expr::isCXX98IntegralConstantExpr(const ASTContext &Ctx) const {
Richard Smith9e575da2012-12-28 13:25:52 +000010691 return CheckICE(this, Ctx).Kind == IK_ICE;
Richard Smith98a0a492012-02-14 21:38:30 +000010692}
10693
Craig Toppera31a8822013-08-22 07:09:37 +000010694bool Expr::isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result,
Richard Smith66e05fe2012-01-18 05:21:49 +000010695 SourceLocation *Loc) const {
10696 // We support this checking in C++98 mode in order to diagnose compatibility
10697 // issues.
David Blaikiebbafb8a2012-03-11 07:00:24 +000010698 assert(Ctx.getLangOpts().CPlusPlus);
Richard Smith66e05fe2012-01-18 05:21:49 +000010699
Richard Smith98a0a492012-02-14 21:38:30 +000010700 // Build evaluation settings.
Richard Smith66e05fe2012-01-18 05:21:49 +000010701 Expr::EvalStatus Status;
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010702 SmallVector<PartialDiagnosticAt, 8> Diags;
Richard Smith66e05fe2012-01-18 05:21:49 +000010703 Status.Diag = &Diags;
Richard Smith6d4c6582013-11-05 22:18:15 +000010704 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpression);
Richard Smith66e05fe2012-01-18 05:21:49 +000010705
10706 APValue Scratch;
10707 bool IsConstExpr = ::EvaluateAsRValue(Info, this, Result ? *Result : Scratch);
10708
10709 if (!Diags.empty()) {
10710 IsConstExpr = false;
10711 if (Loc) *Loc = Diags[0].first;
10712 } else if (!IsConstExpr) {
10713 // FIXME: This shouldn't happen.
10714 if (Loc) *Loc = getExprLoc();
10715 }
10716
10717 return IsConstExpr;
10718}
Richard Smith253c2a32012-01-27 01:14:48 +000010719
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010720bool Expr::EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
10721 const FunctionDecl *Callee,
George Burgess IV177399e2017-01-09 04:12:14 +000010722 ArrayRef<const Expr*> Args,
10723 const Expr *This) const {
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010724 Expr::EvalStatus Status;
10725 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantExpressionUnevaluated);
10726
George Burgess IV177399e2017-01-09 04:12:14 +000010727 LValue ThisVal;
10728 const LValue *ThisPtr = nullptr;
10729 if (This) {
10730#ifndef NDEBUG
10731 auto *MD = dyn_cast<CXXMethodDecl>(Callee);
10732 assert(MD && "Don't provide `this` for non-methods.");
10733 assert(!MD->isStatic() && "Don't provide `this` for static methods.");
10734#endif
10735 if (EvaluateObjectArgument(Info, This, ThisVal))
10736 ThisPtr = &ThisVal;
10737 if (Info.EvalStatus.HasSideEffects)
10738 return false;
10739 }
10740
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010741 ArgVector ArgValues(Args.size());
10742 for (ArrayRef<const Expr*>::iterator I = Args.begin(), E = Args.end();
10743 I != E; ++I) {
Nick Lewyckyf0202ca2014-12-16 06:12:01 +000010744 if ((*I)->isValueDependent() ||
10745 !Evaluate(ArgValues[I - Args.begin()], Info, *I))
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010746 // If evaluation fails, throw away the argument entirely.
10747 ArgValues[I - Args.begin()] = APValue();
10748 if (Info.EvalStatus.HasSideEffects)
10749 return false;
10750 }
10751
10752 // Build fake call to Callee.
George Burgess IV177399e2017-01-09 04:12:14 +000010753 CallStackFrame Frame(Info, Callee->getLocation(), Callee, ThisPtr,
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010754 ArgValues.data());
10755 return Evaluate(Value, Info, this) && !Info.EvalStatus.HasSideEffects;
10756}
10757
Richard Smith253c2a32012-01-27 01:14:48 +000010758bool Expr::isPotentialConstantExpr(const FunctionDecl *FD,
Dmitri Gribenkof8579502013-01-12 19:30:44 +000010759 SmallVectorImpl<
Richard Smith253c2a32012-01-27 01:14:48 +000010760 PartialDiagnosticAt> &Diags) {
10761 // FIXME: It would be useful to check constexpr function templates, but at the
10762 // moment the constant expression evaluator cannot cope with the non-rigorous
10763 // ASTs which we build for dependent expressions.
10764 if (FD->isDependentContext())
10765 return true;
10766
10767 Expr::EvalStatus Status;
10768 Status.Diag = &Diags;
10769
Richard Smith6d4c6582013-11-05 22:18:15 +000010770 EvalInfo Info(FD->getASTContext(), Status,
10771 EvalInfo::EM_PotentialConstantExpression);
Richard Smith253c2a32012-01-27 01:14:48 +000010772
10773 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD);
Craig Topper36250ad2014-05-12 05:36:57 +000010774 const CXXRecordDecl *RD = MD ? MD->getParent()->getCanonicalDecl() : nullptr;
Richard Smith253c2a32012-01-27 01:14:48 +000010775
Richard Smith7525ff62013-05-09 07:14:00 +000010776 // Fabricate an arbitrary expression on the stack and pretend that it
Richard Smith253c2a32012-01-27 01:14:48 +000010777 // is a temporary being used as the 'this' pointer.
10778 LValue This;
10779 ImplicitValueInitExpr VIE(RD ? Info.Ctx.getRecordType(RD) : Info.Ctx.IntTy);
Richard Smithb228a862012-02-15 02:18:13 +000010780 This.set(&VIE, Info.CurrentCall->Index);
Richard Smith253c2a32012-01-27 01:14:48 +000010781
Richard Smith253c2a32012-01-27 01:14:48 +000010782 ArrayRef<const Expr*> Args;
10783
Richard Smith2e312c82012-03-03 22:46:17 +000010784 APValue Scratch;
Richard Smith7525ff62013-05-09 07:14:00 +000010785 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD)) {
10786 // Evaluate the call as a constant initializer, to allow the construction
10787 // of objects of non-literal types.
10788 Info.setEvaluatingDecl(This.getLValueBase(), Scratch);
Richard Smith5179eb72016-06-28 19:03:57 +000010789 HandleConstructorCall(&VIE, This, Args, CD, Info, Scratch);
10790 } else {
10791 SourceLocation Loc = FD->getLocation();
Craig Topper36250ad2014-05-12 05:36:57 +000010792 HandleFunctionCall(Loc, FD, (MD && MD->isInstance()) ? &This : nullptr,
Richard Smith52a980a2015-08-28 02:43:42 +000010793 Args, FD->getBody(), Info, Scratch, nullptr);
Richard Smith5179eb72016-06-28 19:03:57 +000010794 }
Richard Smith253c2a32012-01-27 01:14:48 +000010795
10796 return Diags.empty();
10797}
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010798
10799bool Expr::isPotentialConstantExprUnevaluated(Expr *E,
10800 const FunctionDecl *FD,
10801 SmallVectorImpl<
10802 PartialDiagnosticAt> &Diags) {
10803 Expr::EvalStatus Status;
10804 Status.Diag = &Diags;
10805
10806 EvalInfo Info(FD->getASTContext(), Status,
10807 EvalInfo::EM_PotentialConstantExpressionUnevaluated);
10808
10809 // Fabricate a call stack frame to give the arguments a plausible cover story.
10810 ArrayRef<const Expr*> Args;
10811 ArgVector ArgValues(0);
10812 bool Success = EvaluateArgs(Args, ArgValues, Info);
10813 (void)Success;
10814 assert(Success &&
10815 "Failed to set up arguments for potential constant evaluation");
Craig Topper36250ad2014-05-12 05:36:57 +000010816 CallStackFrame Frame(Info, SourceLocation(), FD, nullptr, ArgValues.data());
Nick Lewycky35a6ef42014-01-11 02:50:57 +000010817
10818 APValue ResultScratch;
10819 Evaluate(ResultScratch, Info, E);
10820 return Diags.empty();
10821}
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010822
10823bool Expr::tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
10824 unsigned Type) const {
10825 if (!getType()->isPointerType())
10826 return false;
10827
10828 Expr::EvalStatus Status;
10829 EvalInfo Info(Ctx, Status, EvalInfo::EM_ConstantFold);
George Burgess IVe3763372016-12-22 02:50:20 +000010830 return tryEvaluateBuiltinObjectSize(this, Type, Info, Result);
George Burgess IV3e3bb95b2015-12-02 21:58:08 +000010831}